write_till_receipt.py

Le fichier Python de l'exemple « Un ticket de caisse sur un rouleau de papier ». Le ticket qu'une caisse imprime sur un rouleau de 80 mm de large : six articles, la TVA rassemblée par taux, le rendu de monnaie calculé sur le billet donné, et le code-barres que le magasin lit quand le ticket revient.

Python 608 lignes

À quoi sert cet exemple

Une caisse de comptoir imprime sur un rouleau de 80 mm de large, et un rouleau n'a pas de bord du bas : le papier est coupé là où le panier s'arrête. La page fait donc la longueur de ce qui a été acheté, et aucun chiffre n'y est écrit d'avance. Une ligne vaut sa quantité fois son prix unitaire, la TVA de chaque taux est prise sur le TTC qui la porte, et le rendu est ce qui reste du billet donné. Passez un article de plus et le rouleau grandit d'une ligne, les totaux toujours en dessous.

Ce que montre cet exemple

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
"""Creates the receipt a shop's till prints on a roll: the shop at the head, the
basket line by line, the tax gathered by rate, what was handed over and what was
handed back, and the ticket's own barcode at the foot.

The Python twin of the `write_till_receipt` example in Rust: the same ticket, through
the binding rather than through the library directly.

The roll is 80 mm across, which is the paper a counter printer takes, and the page is
as long as this basket makes it. Every figure on it is worked out rather than written
down: a line comes to its quantity times its unit price, the tax at each rate is taken
out of the gross that carries it, the total is the sum of the lines, and the change is
what is left of the note handed over.

The barcode is what the shop scans when the ticket comes back — a return, an exchange,
a warranty claim. `Code128.automatic` reads the number and picks the code set for it: a
ticket number of nothing but digits goes into code set C, two digits to a symbol, and
takes 112 modules where code set B would spell it out over 189.

Whether that barcode scans is not for the page to say, and not for an eye: a scanner
says. `scripts/check_barcode.sh` points a decoder at the rendered page and reads the
number back.

Every word the ticket prints is held in `Words`, once per language, and `HQF_PDF_LANG`
picks which one it is printed in. What is not language stays out of it: the shop, the
date, the till, the amounts, the rates and the ticket number read the same whichever
set of words is drawn.

Usage: python examples/write_till_receipt.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_till_receipt.py [out.pdf]
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The space that holds an amount and what stands beside it together.
NO_BREAK = " "

# The roll, in points: 80 mm across, cut long enough for this basket.
PAGE_WIDTH = 226.772
PAGE_HEIGHT = 486.0

# The margins the printer keeps clear, and the middle a centred line sits on.
LEFT = 14.0
RIGHT = PAGE_WIDTH - LEFT
CENTRE = PAGE_WIDTH / 2.0

# Where the first baseline sits, in points down from the top of the roll.
HEAD_TOP = 24.0

# The steps the ticket comes down the roll by: between two lines of a block, between two
# blocks, from one article to the next, and from an article to the quantity line under
# it.
LINE = 10.0
BLOCK = 13.0
ITEM = 20.0
SUB = 8.0

# The sizes the ticket is set at: the shop's name, the small print, the body of the
# basket, the line the ticket ends on, and the total.
SHOP_SIZE = 13.0
SMALL = 6.5
BODY = 8.0
THANKS_SIZE = 7.5
TOTAL_SIZE = 11.0

# The near-black a till prints in, and the grey the labels and the small print are set
# in.
INK = hqf_pdf.Rgb(0.1, 0.1, 0.12)
MUTED = hqf_pdf.Rgb(0.42, 0.42, 0.45)

# The shop: its name, where it stands, what to ring, and the number it is registered for
# tax under. It is the same shop whichever language the ticket is printed in.
SHOP = "Comptoir Vaugelade"
ADDRESS = "18 rue des Trois-Fontaines"
TOWN = "13290 Les Milles"
PHONE = "+33 4 42 00 71 30"
REGISTRATION = "FR 41 802 337 190"

# When the basket was rung up, at which till, and by whom.
DATE = "2026-08-31"
TIME = "18:42"
TILL = "04"
CASHIER = "Naïma"

# The ticket's own number: the till, the day, and the basket's place in the day. Nothing
# but digits, which is what sends it into code set C.
TICKET = "04202608310731"

# The currency every amount on the ticket is in.
CURRENCY = "EUR"

# What was handed over, in cents.
TENDERED = 6000

# The width of the narrowest bar, in points. Everything else is a whole number of these.
MODULE = 1.0

# How tall the bars are drawn, in points.
BAR_HEIGHT = 34.0

# The right edge of two of the three columns of figures in the tax table. The third ends
# at the right margin, and the rate is set from the left one.
NET_RIGHT = 120.0
TAX_RIGHT = 166.0


@dataclass(frozen=True)
class Rate:
    """A rate of tax: the reduced rate a grocer charges on food, and the standard rate
    on everything else.
    """

    # The rate itself, in tenths of a percent.
    tenths: int
    # The letter the ticket marks a line with, and the tax table names.
    letter: str

    def shown(self) -> str:
        """The rate as the ticket writes it: a point before the tenth, and a no-break
        space before the sign.
        """
        return f"{self.tenths // 10}.{self.tenths % 10}{NO_BREAK}%"


REDUCED = Rate(tenths=55, letter="A")
STANDARD = Rate(tenths=200, letter="B")

# Both rates, in the order the tax table sets them out.
RATES = (REDUCED, STANDARD)


@dataclass(frozen=True)
class Article:
    """One line of the basket: how many were scanned, what one of them costs in cents,
    and the rate of tax it carries.

    What the article is called is a word, and is held in `Words` at the place the line
    has here.
    """

    # How many of it were scanned.
    quantity: int
    # What one of them costs, in cents.
    unit: int
    # The rate of tax it carries.
    rate: Rate


# The basket, in the order it was scanned.
BASKET = (
    Article(quantity=1, unit=120, rate=REDUCED),
    Article(quantity=2, unit=890, rate=REDUCED),
    Article(quantity=3, unit=105, rate=REDUCED),
    Article(quantity=1, unit=1240, rate=REDUCED),
    Article(quantity=1, unit=675, rate=STANDARD),
    Article(quantity=1, unit=995, rate=STANDARD),
)


@dataclass(frozen=True)
class Words:
    """Every word the ticket prints, in one language.

    What is not language stays out of it: the shop, its address, the date, the till,
    the cashier, the amounts, the rates and the ticket number are drawn from constants
    of their own and read the same in every language.
    """

    # What the file says it is, and the line under the shop's name.
    title: str
    tagline: str
    # What the shop's tax registration stands under.
    registration: str
    # The five marks at the head of the ticket.
    date: str
    time: str
    till: str
    served: str
    receipt: str
    # The two column heads over the basket.
    item: str
    amount: str
    # The six articles, in the order the basket holds them.
    articles: tuple[str, str, str, str, str, str]
    # The line that adds the basket up before tax, and the four column heads of the tax
    # table.
    net_total: str
    rate: str
    net: str
    tax: str
    gross: str
    # What the ticket comes to, what was handed over, what was handed back, and how many
    # articles were sold.
    total: str
    cash: str
    change: str
    count: str
    # The two lines under the barcode.
    keep: str
    thanks: str


# The ticket in English.
ENGLISH = Words(
    title="Till receipt",
    tagline="Grocer and general store",
    registration="VAT no.",
    date="DATE",
    time="TIME",
    till="TILL",
    served="SERVED BY",
    receipt="RECEIPT",
    item="ITEM",
    amount="AMOUNT",
    articles=(
        "Sourdough loaf",
        "Coffee beans 1 kg",
        "Whole milk 1 L",
        "Olive oil 75 cl",
        "Washing powder 2 kg",
        "Batteries AA, 8",
    ),
    net_total="TOTAL BEFORE TAX",
    rate="RATE",
    net="NET",
    tax="TAX",
    gross="GROSS",
    total="TOTAL",
    cash="CASH",
    change="CHANGE",
    count="ARTICLES SOLD",
    keep="Keep this ticket for any return or exchange.",
    thanks="Thank you for your visit — see you soon",
)

# The ticket in French.
FRENCH = Words(
    title="Ticket de caisse",
    tagline="Épicerie et bazar",
    registration="TVA n°",
    date="DATE",
    time="HEURE",
    till="CAISSE",
    served="SERVI PAR",
    receipt="TICKET",
    item="ARTICLE",
    amount="MONTANT",
    articles=(
        "Pain au levain",
        "Café en grains 1 kg",
        "Lait entier 1 L",
        "Huile d'olive 75 cl",
        "Lessive en poudre 2 kg",
        "Piles AA, 8",
    ),
    net_total="TOTAL HORS TAXE",
    rate="TAUX",
    net="HT",
    tax="TVA",
    gross="TTC",
    total="TOTAL",
    cash="ESPÈCES",
    change="RENDU",
    count="ARTICLES VENDUS",
    keep="Conservez ce ticket pour tout retour ou échange.",
    thanks="Merci de votre visite — à bientôt",
)

# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH}


def money(cents: int) -> str:
    """An amount of cents, its thousands parted by a no-break space and its decimals by
    a point, which is how every language this example is written in writes one.

    The currency is named once at the head of the column of amounts and once on the
    line of the total; the figures themselves are bare, as a till prints them.
    """
    whole, fraction = divmod(cents, 100)
    digits = str(whole)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(NO_BREAK)
        out.append(digit)
    return f"{''.join(out)}.{fraction:02d}"


def line_total(article: Article) -> int:
    """What one line of the basket comes to, in cents."""
    return article.quantity * article.unit


def total() -> int:
    """What the whole basket comes to, in cents."""
    return sum(line_total(article) for article in BASKET)


def sold() -> int:
    """How many articles were sold, all lines together."""
    return sum(article.quantity for article in BASKET)


def gross_at(rate: Rate) -> int:
    """What the lines carrying ``rate`` come to, in cents, tax included."""
    return sum(line_total(article) for article in BASKET if article.rate == rate)


def tax_of(gross: int, rate: Rate) -> int:
    """What ``gross`` holds of tax at ``rate``, in cents, rounded to the nearest cent.

    The prices a shop shows already carry their tax, so the tax is taken out of the
    gross rather than added to a net: at a rate of ``t`` tenths of a percent, it is
    ``gross × t / (1000 + t)``.
    """
    denominator = 1000 + rate.tenths
    return (gross * rate.tenths * 2 + denominator) // (denominator * 2)


def ticket_code() -> hqf_pdf.Code128:
    """The bars the ticket carries.

    The number is nothing but digits, so ``automatic`` takes code set C for it and
    draws it in a little over half the bars code set B would spell it out in.
    """
    return hqf_pdf.Code128.automatic(TICKET)


def text(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    x: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text, left-aligned, in a colour of its own."""
    content.set_fill(color)
    content.draw_text(font, size, x, y, s)


def text_right(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    right: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text whose right edge sits at ``right``."""
    text(content, font, size, right - font.measure(s, size), y, color, s)


def text_centre(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    y: float,
    color: hqf_pdf.Rgb,
    s: str,
) -> None:
    """Draws a line of text set across the middle of the roll."""
    text(content, font, size, CENTRE - font.measure(s, size) / 2.0, y, color, s)


def row(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    size: float,
    y: float,
    color: hqf_pdf.Rgb,
    left: str,
    right: str,
) -> None:
    """Draws a row with something at the left margin and something at the right."""
    text(content, font, size, LEFT, y, color, left)
    text_right(content, font, size, RIGHT, y, color, right)


def dashes(content: hqf_pdf.Content, y: float) -> None:
    """Draws the row of dashes a till prints between the parts of a ticket."""
    content.set_stroke(MUTED)
    content.set_line_width(0.5)
    content.set_dash(hqf_pdf.Dash.on_off(2.0, 2.0))
    content.move_to(LEFT, y)
    content.line_to(RIGHT, y)
    content.stroke()
    content.set_solid()


def head(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws the shop at the head of the roll, and hands back the baseline it ends
    on.
    """
    y = top
    text_centre(content, font, SHOP_SIZE, y, INK, SHOP)
    y -= 12.0
    text_centre(content, font, SMALL, y, MUTED, words.tagline)
    y -= LINE
    text_centre(content, font, SMALL, y, INK, ADDRESS)
    y -= SUB
    text_centre(content, font, SMALL, y, INK, TOWN)
    y -= SUB
    text_centre(content, font, SMALL, y, INK, PHONE)
    y -= SUB
    text_centre(content, font, SMALL, y, MUTED, f"{words.registration} {REGISTRATION}")
    return y


def marks(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws when the basket was rung up, at which till, by whom and under which
    number, and hands back the baseline it ends on.
    """
    y = top
    row(
        content,
        font,
        SMALL,
        y,
        INK,
        f"{words.date} {DATE}",
        f"{words.time} {TIME}",
    )
    y -= LINE
    row(
        content,
        font,
        SMALL,
        y,
        INK,
        f"{words.till} {TILL}",
        f"{words.served} {CASHIER}",
    )
    y -= LINE
    row(content, font, SMALL, y, INK, words.receipt, TICKET)
    return y


def basket(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws the basket, one article to two lines: what it is against what it came to,
    and under that how many at what price and which rate it carries. Hands back the
    baseline it ends on.
    """
    y = top
    for article, name in zip(BASKET, words.articles):
        row(content, font, BODY, y, INK, name, money(line_total(article)))

        counted = f"{article.quantity} × {money(article.unit)}"
        text(content, font, SMALL, LEFT + SUB, y - SUB, MUTED, counted)
        text_right(content, font, SMALL, RIGHT, y - SUB, MUTED, article.rate.letter)
        y -= ITEM
    return y + ITEM - SUB


def taxes(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws what the basket comes to before tax and the tax gathered by rate, and
    hands back the baseline it ends on.
    """
    y = top
    before_tax = sum(gross_at(rate) - tax_of(gross_at(rate), rate) for rate in RATES)
    row(content, font, BODY, y, INK, words.net_total, money(before_tax))

    y -= BLOCK
    text(content, font, SMALL, LEFT, y, MUTED, words.rate)
    text_right(content, font, SMALL, NET_RIGHT, y, MUTED, words.net)
    text_right(content, font, SMALL, TAX_RIGHT, y, MUTED, words.tax)
    text_right(content, font, SMALL, RIGHT, y, MUTED, words.gross)

    for rate in RATES:
        y -= LINE
        gross = gross_at(rate)
        tax = tax_of(gross, rate)
        text(content, font, SMALL, LEFT, y, INK, f"{rate.letter} {rate.shown()}")
        text_right(content, font, SMALL, NET_RIGHT, y, INK, money(gross - tax))
        text_right(content, font, SMALL, TAX_RIGHT, y, INK, money(tax))
        text_right(content, font, SMALL, RIGHT, y, INK, money(gross))
    return y


def settlement(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws what the ticket came to, what was handed over and what was handed back,
    and hands back the baseline it ends on.
    """
    y = top
    due = total()
    paid = f"{money(due)}{NO_BREAK}{CURRENCY}"
    row(content, font, TOTAL_SIZE, y, INK, words.total, paid)

    y -= BLOCK
    row(content, font, BODY, y, INK, words.cash, money(TENDERED))
    y -= LINE
    row(content, font, BODY, y, INK, words.change, money(TENDERED - due))
    y -= LINE
    row(content, font, SMALL, y, MUTED, words.count, str(sold()))
    return y


def foot(
    content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words, top: float
) -> float:
    """Draws the ticket's own barcode and the two lines under it, and hands back the
    baseline it ends on.
    """
    code = ticket_code()
    width = code.module_count * MODULE

    # The quiet zone is the caller's: nothing else is drawn beside the bars, and the
    # roll leaves far more than the ten modules a scanner needs.
    y = top - BAR_HEIGHT
    content.set_fill(hqf_pdf.Rgb.gray(0.0))
    content.draw_barcode(code, (PAGE_WIDTH - width) / 2.0, y, width, BAR_HEIGHT)

    y -= LINE
    text_centre(content, font, SMALL, y, INK, TICKET)
    y -= LINE
    text_centre(content, font, SMALL, y, MUTED, words.keep)
    y -= 12.0
    text_centre(content, font, THANKS_SIZE, y, INK, words.thanks)
    return y


def ticket(content: hqf_pdf.Content, font: hqf_pdf.FontHandle, words: Words) -> float:
    """Draws the whole ticket, and hands back the baseline it ends on."""
    y = head(content, font, words, PAGE_HEIGHT - HEAD_TOP)

    y -= BLOCK
    dashes(content, y)
    y = marks(content, font, words, y - BLOCK)

    y -= BLOCK
    dashes(content, y)
    y -= BLOCK
    row(
        content,
        font,
        SMALL,
        y,
        MUTED,
        words.item,
        f"{words.amount}{NO_BREAK}{CURRENCY}",
    )
    y = basket(content, font, words, y - 12.0)

    y -= BLOCK
    dashes(content, y)
    y = taxes(content, font, words, y - BLOCK)

    y -= BLOCK
    dashes(content, y)
    y = settlement(content, font, words, y - 16.0)

    return foot(content, font, words, y - 18.0)


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(
        Path(_language.file_name("till_receipt.pdf", language)).stem
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_info("Title", f"{words.title} {TICKET}")

    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    content = hqf_pdf.Content()
    ticket(content, font, words)

    page = hqf_pdf.Page(PAGE_WIDTH, PAGE_HEIGHT)
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, ticket {TICKET}, {sold()} articles, "
        f"{money(total())}{NO_BREAK}{CURRENCY}"
    )


if __name__ == "__main__":
    main()