write_barcode.py

Die Python-Datei des Beispiels „Code 128 und Handels-Barcodes“. Striche für die beiden Aufgaben, die sie wollen: Code 128 für beliebigen Text und die drei, die eine Kasse liest — EAN-13, UPC-A, EAN-8 —, jeder mit berechneter statt eingetippter letzter Ziffer.

Python 480 Zeilen

Wofür dieses Beispiel da ist

Ein Barcode, der sich nicht scannen lässt, hält die Palette am Tor und die Schlange an der Kasse auf. Er scheitert aus Gründen, die niemand auf den ersten Blick sieht — eine um eins verschobene Prüfziffer, Striche, die eine Spur zu dünn sind, weil der Code als Bild gespeichert und dann skaliert wurde, ein weißer Rand, den jemand abgeschnitten hat, damit er passt.

Was dieses Beispiel zeigt

  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
"""Writes a page of barcodes, drawn as bars: Code 128 for arbitrary text, an EAN-13
for a thirteen-digit article number, a UPC-A for its twelve-digit North American
cousin, and a short EAN-8.

A second page sizes its modules as a whole number of pixels of the device, sets the
same digits in Code 128 paired and one by one, sets a UPC-E with its digits and the
UPC-A it stands for, and an EAN-13 with a five-digit add-on beside it, the add-on's
digits over it.

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

Whether a barcode works is not a question the page can answer, and not one a human
eye can: it is answered by a scanner. So the page carries what each barcode says
under it, and `scripts/check_barcode.sh` points a decoder at the rendered image and
compares.

The head of the sheet says what the bars are for, so that the page is worth something
to whoever opens it without the code beside it. Those words are held in `Words`, once
per language, and `HQF_PDF_LANG` picks which set the sheet is headed in. What the
barcodes carry stands apart from them: a scanner reads it, not a person, and it is the
same in every language.

The digits under the three retail codes are set in Spectral, whatever font the
rest is written in: they are sized by the capital height a face states, and Spectral
states it.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The font the digits under the retail codes are set in.
DIGIT_FONT = (
    _out.ROOT / "crates" / "hqf-pdf" / "tests" / "fonts" / "Spectral-Regular.ttf"
)

# What the Code 128 barcodes carry: an invoice number, a payment reference, and a line
# holding every kind of character code set B carries.
CARRIED = ["FR-1964413", "REF 2026-07-16/ACME", "a-Z 0..9 +*#%"]

# The thirteen-digit article number the EAN-13 barcode carries.
ARTICLE = "9780201379624"

# The twelve-digit article number the UPC-A barcode carries.
UPC_ARTICLE = "036000291452"

# The eight-digit article number the EAN-8 barcode carries.
EAN8_ARTICLE = "96385074"

# The digits the two Code 128 barcodes of the second page carry, the one packing them
# two to a character, the other setting them one by one.
PAIRED = "40063813339301"

# The eight digits the UPC-E barcode carries.
UPC_E_ARTICLE = "01234565"

# The five digits the add-on beside the second page's EAN-13 carries.
ADD_ON = "52495"

# The resolution the modules of the second page are a whole number of pixels at, in dots
# per inch: the one `scripts/check_barcode.sh` renders at.
DPI = 288.0

# The size the lines under the second page's codes are set at, in points.
CAPTION = 9.0

# 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 = 40.0

# Where the foot of the first barcode sits, in points up from the foot of the sheet.
TOP = 700.0

# How far in from the left edge of the sheet the head of the page is set. The quiet zone
# of the first barcode starts here too, so the heading stands over the left edge of the
# block of bars.
MARGIN = 72.0

# Where the baseline of the heading sits, in points up from the foot of the sheet.
HEAD_TOP = 794.0

# The size the heading is set at, in points.
HEADING = 16.0

# The size the lines under the heading are set at, in points.
BODY = 10.5

# How far under the heading the first line beneath it sits, in points.
HEAD_GAP = 24.0

# How far below one line under the heading the next one sits, in points.
LINE_STEP = 15.0

@dataclass(frozen=True)
class Words:
    """Every word the sheet is headed in, in one language."""

    # What the page says it is, at its head and in what the file says of itself.
    title: str
    # What the page says under its heading.
    lines: tuple[str, str]
    # The second page's heading.
    more_title: str
    # What the second page says under its heading.
    more_lines: tuple[str, str]
    # What the Code 128 packing digits in pairs is; `{modules}` stands for how many
    # modules it counts and `{pixels}` for the pixels to a module.
    paired: str
    # What the Code 128 setting the same digits one by one is; `{modules}` stands for
    # how many modules it counts.
    spelt: str
    # What the UPC-E is; `{upc_a}` stands for the UPC-A it stands for.
    short: str
    # What the EAN-13 and its add-on are; `{extra}` stands for the add-on's digits and
    # `{gap}` for the modules between the two.
    add_on: str


# The head of the sheet in English.
ENGLISH = Words(
    title="Barcodes, drawn as bars",
    lines=(
        (
            "Each barcode below is drawn as bars, not pasted in as a picture, so it "
            "prints"
        ),
        "exactly as wide as it should. Under each one is what a scanner reads back.",
    ),
    more_title="Codes built and sized other ways",
    more_lines=(
        (
            "Each module below is a whole number of printer pixels, so every bar edge "
            "falls"
        ),
        "on a pixel. Under each code, what it carries and how it was built.",
    ),
    paired=(
        "Digits packed two to a character: {modules} modules of {pixels} pixels at 288 "
        "dpi"
    ),
    spelt="The same digits one character at a time: {modules} modules",
    short="A UPC-E, its zeros left out: a scanner hands back the UPC-A {upc_a}",
    add_on=(
        "An EAN-13 with the five-digit add-on {extra} beside it, {gap} modules away"
    ),
)

# The head of the sheet in French.
FRENCH = Words(
    title="Des codes-barres, dessinés en barres",
    lines=(
        (
            "Chaque code-barres ci-dessous est dessiné en barres, pas collé comme une "
            "image :"
        ),
        (
            "il s’imprime exactement à la bonne largeur. Sous chacun, ce qu’un scanner "
            "y lit."
        ),
    ),
    more_title="Des codes construits et dimensionnés autrement",
    more_lines=(
        "Chaque module ci-dessous vaut un nombre entier de pixels de l’imprimante :",
        (
            "tout bord de barre tombe sur un pixel. Sous chaque code : contenu et "
            "construction."
        ),
    ),
    paired="Chiffres groupés par deux : {modules} modules de {pixels} pixels à 288 ppp",
    spelt="Les mêmes chiffres un par un : {modules} modules",
    short="Un UPC-E, ses zéros omis : un scanner y lit l’UPC-A {upc_a}",
    add_on=(
        "Un EAN-13 suivi de son code complémentaire à cinq chiffres {extra}, à "
        "{gap} modules"
    ),
)

# The head of the sheet in Dutch.
DUTCH = Words(
    title="Streepjescodes, getekend als streepjes",
    lines=(
        (
            "Elke code hieronder is getekend als streepjes, niet als afbeelding "
            "geplakt, dus"
        ),
        "wordt hij precies zo breed gedrukt als hij moet. Eronder wat een scanner leest.",
    ),
    more_title="Codes die anders zijn opgebouwd en bemeten",
    more_lines=(
        (
            "Elke module hieronder is een geheel aantal printerpixels breed, dus valt "
            "elke"
        ),
        "streeprand op een pixel. Eronder wat hij bevat en hoe hij is opgebouwd.",
    ),
    paired=(
        "Cijfers per twee in een teken: {modules} modules van {pixels} pixels bij 288 "
        "dpi"
    ),
    spelt="Dezelfde cijfers één per teken: {modules} modules",
    short="Een UPC-E zonder zijn nullen: een scanner geeft de UPC-A {upc_a} terug",
    add_on=(
        "Een EAN-13 met de vijfcijferige toevoeging {extra} ernaast, {gap} modules verderop"
    ),
)

# The head of the sheet in Portuguese.
PORTUGUESE = Words(
    title="Códigos de barras, desenhados como barras",
    lines=(
        (
            "Cada código abaixo é desenhado como barras, não colado como imagem, por "
            "isso"
        ),
        "imprime-se com a largura exata. Por baixo de cada um, o que um leitor lê.",
    ),
    more_title="Códigos construídos e dimensionados de outras formas",
    more_lines=(
        (
            "Cada módulo abaixo mede um número inteiro de píxeis da impressora, por "
            "isso cada"
        ),
        "aresta de barra cai num píxel. Por baixo, o que leva e como foi construído.",
    ),
    paired=(
        "Algarismos dois a dois por carácter: {modules} módulos de {pixels} píxeis a "
        "288 ppp"
    ),
    spelt="Os mesmos algarismos um a um: {modules} módulos",
    short="Um UPC-E sem os seus zeros: um leitor devolve o UPC-A {upc_a}",
    add_on=(
        "Um EAN-13 com o suplemento de cinco algarismos {extra} ao lado, a {gap} módulos"
    ),
)

# The head of the sheet in Italian.
ITALIAN = Words(
    title="Codici a barre, disegnati a barre",
    lines=(
        (
            "Ogni codice qui sotto è disegnato a barre, non incollato come immagine, "
            "così si"
        ),
        "stampa esattamente largo quanto deve. Sotto ciascuno, ciò che legge uno scanner.",
    ),
    more_title="Codici costruiti e dimensionati in altri modi",
    more_lines=(
        (
            "Ogni modulo qui sotto misura un numero intero di pixel di stampante, "
            "così ogni"
        ),
        "bordo di barra cade su un pixel. Sotto, ciò che porta e come è stato costruito.",
    ),
    paired=(
        "Cifre, due per carattere: {modules} moduli di {pixels} pixel a 288 dpi"
    ),
    spelt="Le stesse cifre, una per carattere: {modules} moduli",
    short="Un UPC-E senza i suoi zeri: uno scanner restituisce l’UPC-A {upc_a}",
    add_on=(
        "Un EAN-13 con l’aggiunta a cinque cifre {extra} accanto, a {gap} moduli"
    ),
)

# The head of the sheet in Spanish.
SPANISH = Words(
    title="Códigos de barras, dibujados como barras",
    lines=(
        (
            "Cada código de abajo se dibuja como barras, no se pega como imagen, así "
            "que se"
        ),
        "imprime con el ancho exacto. Debajo de cada uno, lo que lee un escáner.",
    ),
    more_title="Códigos construidos y dimensionados de otras formas",
    more_lines=(
        (
            "Cada módulo de abajo mide un número entero de píxeles de impresora, así "
            "que"
        ),
        "cada borde de barra cae en un píxel. Debajo, lo que lleva y cómo se construyó.",
    ),
    paired=(
        "Dos cifras por carácter: {modules} módulos de {pixels} píxeles a 288 ppp"
    ),
    spelt="Las mismas cifras, una por carácter: {modules} módulos",
    short="Un UPC-E sin sus ceros: un escáner devuelve el UPC-A {upc_a}",
    add_on=(
        "Un EAN-13 con el complemento de cinco cifras {extra} al lado, a {gap} módulos"
    ),
)

# The head of the sheet in German.
GERMAN = Words(
    title="Strichcodes, als Balken gezeichnet",
    lines=(
        (
            "Jeder Strichcode unten ist als Balken gezeichnet, nicht als Bild, und "
            "wird"
        ),
        "genau so breit gedruckt, wie er soll. Darunter steht, was ein Scanner liest.",
    ),
    more_title="Codes, anders aufgebaut und bemessen",
    more_lines=(
        (
            "Jedes Modul unten misst ganze Druckerpixel, also fällt jede Balkenkante"
        ),
        "auf ein Pixel. Unter jedem Code steht, was er trägt und wie er gebaut wurde.",
    ),
    paired=(
        "Zwei Ziffern je Zeichen: {modules} Module zu je {pixels} Pixeln bei 288 dpi"
    ),
    spelt="Dieselben Ziffern, ein Zeichen nach dem anderen: {modules} Module",
    short="Ein UPC-E ohne seine Nullen: Ein Scanner gibt den UPC-A {upc_a} zurück",
    add_on=(
        "Ein EAN-13 mit dem fünfstelligen Zusatz {extra} daneben, {gap} Module entfernt"
    ),
)

# 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, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}


def head(content, handle, title, lines) -> None:
    """Draw the heading `title`, and the `lines` under it that say what the page is
    for."""
    content.draw_text(handle, HEADING, MARGIN, HEAD_TOP, title)

    y = HEAD_TOP - HEAD_GAP
    for line in lines:
        content.draw_text(handle, BODY, MARGIN, y, line)
        y -= LINE_STEP



def caption(content, handle, left, y, lines) -> None:
    """Set `lines` at `left`, the first with its baseline at `y` and each next one a
    line below it."""
    baseline = y
    for line in lines:
        content.draw_text(handle, CAPTION, left, baseline, line)
        baseline -= 11.0


def second_page(handle, digits, digit_cap, words) -> hqf_pdf.Page:
    """The second page: modules of a whole number of pixels, Code 128 paired and spelt,
    a UPC-E with its digits, and an EAN-13 with its add-on. `digit_cap` is the capital
    height of the digits' face at one point."""
    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    head(content, handle, words.more_title, words.more_lines)

    quiet = hqf_pdf.BARCODE_QUIET_ZONE
    # A third of a millimetre asked for, made a whole number of pixels.
    module = hqf_pdf.BarcodeModule.on_pixels(0.33 * 72.0 / 25.4, DPI)
    left = MARGIN + module.across(quiet)
    top = TOP - 20.0
    for code, said in (
        (hqf_pdf.Code128.numeric(PAIRED), words.paired),
        (hqf_pdf.Code128(PAIRED), words.spelt),
    ):
        count = code.module_count
        content.draw_barcode(code, left, top, module.across(count), BAR_HEIGHT)
        described = said.replace("{modules}", str(count)).replace(
            "{pixels}", str(module.pixels)
        )
        caption(content, handle, left, top - 12.0, (PAIRED, described))
        top -= 100.0

    # Six pixels to a module: half as wide again as the codes above.
    wide = hqf_pdf.BarcodeModule.pixels_at(6, DPI)
    upc_e = hqf_pdf.UpcE(UPC_E_ARTICLE)
    left_e = MARGIN + wide.across(quiet)
    width = wide.across(upc_e.module_count)
    content.draw_upc_e(upc_e, left_e, top, width, BAR_HEIGHT)
    content.draw_upc_e_digits(upc_e, digits, left_e, top, width)
    described = words.short.replace("{upc_a}", upc_e.expanded)
    below = top - hqf_pdf.BARCODE_DIGIT_DEPTH * wide.points - 12.0
    caption(content, handle, left_e, below, (UPC_E_ARTICLE, described))
    top -= 130.0

    ean = hqf_pdf.Ean13(ARTICLE)
    width = module.across(ean.module_count)
    content.draw_ean13(ean, left, top, width, BAR_HEIGHT)
    supplement = hqf_pdf.AddOn5(ADD_ON)
    separation = hqf_pdf.AddOn5.separation()
    beside = left + width + module.across(separation)
    content.draw_add_on5(
        supplement, beside, top, module.across(supplement.module_count), BAR_HEIGHT
    )
    # The add-on's digits stand over it, as tall as a retail code's digits.
    size = hqf_pdf.BARCODE_DIGIT_HEIGHT * module.points / digit_cap
    content.draw_text(digits, size, beside, top + BAR_HEIGHT + 2.0, ADD_ON)
    described = words.add_on.replace("{extra}", ADD_ON).replace(
        "{gap}", str(separation)
    )
    # The guard bars reach below the box: the caption stands under them.
    below = top - module.across(hqf_pdf.Ean13.guard_extension()) - 12.0
    caption(content, handle, left, below, (ARTICLE, described))

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    return page


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("barcode.pdf", language)).stem)

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

    handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
    digit_face = hqf_pdf.Font.from_path(DIGIT_FONT)
    digit_cap = digit_face.cap_height(1.0)
    digits = document.add_font(digit_face)

    content = hqf_pdf.Content()
    content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
    head(content, handle, words.title, words.lines)

    top = TOP
    for carried in CARRIED:
        code = hqf_pdf.Code128(carried)

        # The quiet zone is the caller's: the bars start ten modules in, and nothing
        # else is drawn beside them.
        left = MARGIN + hqf_pdf.Code128.quiet_zone() * MODULE
        content.draw_barcode(code, left, top, code.module_count * MODULE, BAR_HEIGHT)
        content.draw_text(handle, 9.0, left, top - 12.0, carried)

        top -= 120.0

    left = MARGIN + hqf_pdf.Code128.quiet_zone() * MODULE

    ean = hqf_pdf.Ean13(ARTICLE)
    content.draw_ean13(ean, left, top, ean.module_count * MODULE, BAR_HEIGHT)
    # The digits a shop assistant types in stand where the standard sets them, with the
    # `>` that marks how far the quiet zone runs.
    content.draw_ean13_digits(ean, digits, left, top, ean.module_count * MODULE, True)
    top -= 120.0

    upc = hqf_pdf.UpcA(UPC_ARTICLE)
    content.draw_upc_a(upc, left, top, upc.module_count * MODULE, BAR_HEIGHT)
    content.draw_upc_a_digits(upc, digits, left, top, upc.module_count * MODULE)
    top -= 120.0

    ean8 = hqf_pdf.Ean8(EAN8_ARTICLE)
    content.draw_ean8(ean8, left, top, ean8.module_count * MODULE, BAR_HEIGHT)
    content.draw_ean8_digits(ean8, digits, left, top, ean8.module_count * MODULE, True)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)
    document.add_page(second_page(handle, digits, digit_cap, words))

    written = document.write(out)
    print(f"wrote {out} ({written} bytes)")


if __name__ == "__main__":
    main()