write_datamatrix.py

Die Python-Datei des Beispiels „Data-Matrix-Codes“. Der Code, mit dem die Industrie kleine Teile kennzeichnet: noch lesbar in Größen, in denen ein QR-Code aufgegeben hat, auf einer Platine oder einer Ampulle in einer Laborschale.

Python 274 Zeilen

Wofür dieses Beispiel da ist

Mit Data Matrix kennzeichnet die Industrie kleine Teile. Er bleibt in Größen lesbar, in denen ein QR-Code aufgegeben hat, und seine rechteckigen Formen passen auf Bauteile und Etiketten, die keinen Platz für ein Quadrat haben: eine Platine, ein chirurgisches Instrument, eine Ampulle in einer Laborschale.

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
"""Writes a page of Data Matrix codes, drawn as squares.

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

Whether a Data Matrix code 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
code says under it, and `scripts/check_datamatrix.sh` points a decoder at the
rendered image and compares.

The head of the sheet says what the squares 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 codes carry stands apart from them: a scanner reads it, not a person, and it is
the same in every language.

Under the first row stand five more, each built another way: text as an oblong, text at
a stated size, bytes as they are, bytes as an oblong, and bytes at a stated size. Each
says its size in modules, and a line counts the last one's dark modules.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# What the codes carry: a tracking link, a serial number, and a line of mixed
# punctuation.
CARRIED = [
    "https://example.test/track/FR-1964413",
    "SN:2026-07-19/ACME-4472",
    "a-Z 0..9 +*#% and on",
]

# What the codes of the second and third rows carry, each built another way.
OTHERS = ("SN 2026 RECT", "SIZE 24", "DM BYTES", "DM RECT", "DM 20")

# How far the foot of one row of codes stands under the foot of the row above it.
ROW_STEP = 130.0

# The side of one module, in points. Four pixels to a module at 288dpi, so every
# module's edge lands on a pixel boundary.
MODULE = 3.0

# Where the foot of the row of codes sits, in points up from the foot of the sheet.
TOP = 640.0

# How far in from the left edge of the sheet the head of the page is set. The quiet zone
# of the first code starts here too, so the heading stands over the left edge of the row
# of codes.
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 line under the codes that counts the last one's dark modules; `{dark}` and
    # `{all}` stand for the two counts.
    dark: str


# The head of the sheet in English.
ENGLISH = Words(
    title="Data Matrix codes, drawn as squares",
    lines=(
        (
            "A Data Matrix holds as much as a QR code in less room, which is why it is "
            "found"
        ),
        "on small parts and on parcels. Under each one is what a scanner reads back.",
    ),
    dark="The last code holds {dark} dark modules out of {all}.",
)

# The sheet in French.
FRENCH = Words(
    title="Des codes Data Matrix, dessinés en carrés",
    lines=(
        (
            "Un Data Matrix contient autant qu’un code QR en moins de place : on le "
            "trouve sur"
        ),
        "les petites pièces et les colis. Sous chacun figure ce qu’un scanner y lit.",
    ),
    dark="Le dernier code compte {dark} modules sombres sur {all}.",
)

# The sheet in Dutch.
DUTCH = Words(
    title="Data Matrix-codes, getekend als vierkantjes",
    lines=(
        (
            "Een Data Matrix bevat evenveel als een QR-code op minder ruimte, dus "
            "staat hij"
        ),
        "op kleine onderdelen en op pakketten. Onder elke code wat een scanner leest.",
    ),
    dark="De laatste code heeft {dark} donkere modules van de {all}.",
)

# The sheet in Portuguese.
PORTUGUESE = Words(
    title="Códigos Data Matrix, desenhados como quadrados",
    lines=(
        (
            "Um Data Matrix guarda tanto como um código QR em menos espaço, por isso "
            "se vê"
        ),
        "em peças pequenas e em encomendas. Por baixo de cada um, o que um leitor lê.",
    ),
    dark="O último código tem {dark} módulos escuros em {all}.",
)

# The sheet in Italian.
ITALIAN = Words(
    title="Codici Data Matrix, disegnati a quadrati",
    lines=(
        (
            "Un Data Matrix contiene quanto un codice QR in meno spazio, per questo "
            "si trova"
        ),
        "su piccoli pezzi e sui pacchi. Sotto ciascuno, ciò che legge uno scanner.",
    ),
    dark="L’ultimo codice ha {dark} moduli scuri su {all}.",
)

# The sheet in Spanish.
SPANISH = Words(
    title="Códigos Data Matrix, dibujados como cuadrados",
    lines=(
        (
            "Un Data Matrix guarda tanto como un código QR en menos sitio, por eso se "
            "ve"
        ),
        "en piezas pequeñas y en paquetes. Debajo de cada uno, lo que lee un escáner.",
    ),
    dark="El último código tiene {dark} módulos oscuros de {all}.",
)

# The sheet in German.
GERMAN = Words(
    title="Data-Matrix-Codes, als Quadrate gezeichnet",
    lines=(
        (
            "Ein Data-Matrix-Code fasst so viel wie ein QR-Code auf weniger Platz; "
            "man findet"
        ),
        "ihn daher auf kleinen Teilen und Paketen. Darunter steht, was ein Scanner liest.",
    ),
    dark="Der letzte Code hat {dark} dunkle Module von {all}.",
)

# 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, words) -> None:
    """Draw the heading, and the lines under it that say what the page is for."""
    content.draw_text(handle, HEADING, MARGIN, HEAD_TOP, words.title)

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


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("datamatrix.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()))

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

    quiet = hqf_pdf.DataMatrix.quiet_zone() * MODULE
    left = MARGIN
    top = TOP
    for carried in CARRIED:
        code = hqf_pdf.DataMatrix(carried)
        side = code.width * MODULE

        # The quiet zone is the caller's: the code is drawn that far in, and nothing
        # else is drawn beside it.
        content.draw_data_matrix(code, left + quiet, top, side)
        content.draw_text(handle, 8.0, left + quiet, top - 12.0, carried)

        # The next code stands clear of this one's caption as well as of the code
        # itself.
        left += max(side, handle.measure(carried, 8.0)) + quiet * 2.0 + 24.0

    # Five more, each built another way: text as an oblong, text at a stated size, bytes
    # as they are, bytes as an oblong, and bytes at a stated size. Under each, its size
    # in modules, read back from it.
    others = [
        hqf_pdf.DataMatrix.rectangular(OTHERS[0]),
        hqf_pdf.DataMatrix.with_size(OTHERS[1], 24, 24),
        hqf_pdf.DataMatrix(OTHERS[2].encode()),
        hqf_pdf.DataMatrix.rectangular(OTHERS[3].encode()),
        hqf_pdf.DataMatrix.with_size(OTHERS[4].encode(), 20, 20),
    ]
    row_top = top
    for first in range(0, len(others), 3):
        row_top -= ROW_STEP
        left = MARGIN
        for code, carried in zip(others[first : first + 3], OTHERS[first:]):
            side = code.width * MODULE
            content.draw_data_matrix(code, left + quiet, row_top, side)
            size = f"{code.height} × {code.width}"
            for line, drop in ((carried, 12.0), (size, 22.0)):
                content.draw_text(handle, 8.0, left + quiet, row_top - drop, line)
            left += max(side, 100.0) + quiet * 2.0 + 24.0

    # How many modules of the last code are dark, read square by square.
    last = others[-1]
    lit = sum(
        1
        for row in range(last.height)
        for column in range(last.width)
        if last.is_dark(row, column)
    )
    counted = words.dark.replace("{dark}", str(lit)).replace(
        "{all}", str(last.height * last.width)
    )
    content.draw_text(handle, BODY, MARGIN, row_top - 60.0, counted)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

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


if __name__ == "__main__":
    main()