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 | """Writes a page of QR codes, drawn as squares.
The Python twin of the `write_qr` example in Rust: the same page, through the
binding rather than through the library directly.
Whether a QR 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_qr.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 four codes built other ways: figures in the numeric mode, a
text at the highest correction, bytes as they are, and bytes at a stated correction. A
line under them counts the last one's dark modules, read square by square.
Usage: python examples/write_qr.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_qr.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: an invoice link, a payment reference, and a line of mixed
# punctuation.
CARRIED = [
"https://example.test/invoice/FR-1964413",
"REF 2026-07-16/ACME",
"a-Z 0..9 +*#% and on",
]
# A payload of figures only, written in the numeric mode.
NUMERIC = "20260716"
# A payload written at the highest correction.
CORRECTED = "HQF-2026-0917"
# A payload handed over as bytes, as they are.
BYTES = "HQF BYTES 2026"
# A payload handed over as bytes, at a stated correction.
LOT = "LOT 4472"
# How far the foot of one row of codes stands under the foot of the row above it.
ROW_STEP = 140.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="QR codes, drawn as squares",
lines=(
(
"A QR code holds a link or a reference that a telephone reads in one shot. "
"It is"
),
(
"drawn square by square here, so it stays readable at any size it is "
"printed at."
),
),
dark="The last code holds {dark} dark modules out of {all}.",
)
# The sheet in French.
FRENCH = Words(
title="Des codes QR, dessinés en carrés",
lines=(
(
"Un code QR contient un lien ou une référence qu’un téléphone lit d’un "
"seul coup. Il"
),
(
"est dessiné ici carré par carré : il reste donc lisible à toute taille "
"d’impression."
),
),
dark="Le dernier code compte {dark} modules sombres sur {all}.",
)
# The sheet in Dutch.
DUTCH = Words(
title="QR-codes, getekend als vierkantjes",
lines=(
(
"Een QR-code bevat een link of een kenmerk dat een telefoon in één keer "
"leest. Hij is"
),
(
"hier vierkantje voor vierkantje getekend, dus blijft hij leesbaar op elk "
"drukformaat."
),
),
dark="De laatste code heeft {dark} donkere modules van de {all}.",
)
# The sheet in Portuguese.
PORTUGUESE = Words(
title="Códigos QR, desenhados como quadrados",
lines=(
(
"Um código QR guarda uma ligação ou referência que um telemóvel lê de uma "
"vez."
),
(
"Aqui é desenhado quadrado a quadrado: lê-se em qualquer tamanho impresso."
),
),
dark="O último código tem {dark} módulos escuros em {all}.",
)
# The sheet in Italian.
ITALIAN = Words(
title="Codici QR, disegnati a quadrati",
lines=(
(
"Un codice QR contiene un link o un riferimento che un telefono legge in "
"un colpo."
),
(
"Qui è disegnato quadrato per quadrato: resta leggibile a ogni formato di "
"stampa."
),
),
dark="L’ultimo codice ha {dark} moduli scuri su {all}.",
)
# The sheet in Spanish.
SPANISH = Words(
title="Códigos QR, dibujados como cuadrados",
lines=(
(
"Un código QR guarda un enlace o una referencia que un teléfono lee de "
"una vez."
),
(
"Aquí se dibuja cuadrado a cuadrado, así que se lee a cualquier tamaño de "
"impresión."
),
),
dark="El último código tiene {dark} módulos oscuros de {all}.",
)
# The sheet in German.
GERMAN = Words(
title="QR-Codes, als Quadrate gezeichnet",
lines=(
(
"Ein QR-Code fasst einen Link oder eine Referenz, die ein Handy mit einem "
"Blick liest."
),
(
"Hier Quadrat für Quadrat gezeichnet, bleibt er in jeder Druckgröße "
"lesbar."
),
),
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("qr.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.QrCode.quiet_zone() * MODULE
left = MARGIN
top = TOP
for carried in CARRIED:
code = hqf_pdf.QrCode(carried)
side = code.size * MODULE
caption = handle.measure(carried, 8.0)
# The quiet zone is the caller's: the code is drawn that far in, and nothing
# else is drawn beside it.
content.draw_qr(code, left + quiet, top, side)
content.draw_text(handle, 8.0, left + quiet, top - 12.0, carried)
left += max(side, caption) + quiet * 2.0 + 24.0
# Four more, each built another way: figures in the numeric mode, a text at the
# highest correction, bytes as they are, and bytes at a stated correction.
others = [
(hqf_pdf.QrCode(NUMERIC, mode=hqf_pdf.QrMode.Numeric), NUMERIC),
(hqf_pdf.QrCode(CORRECTED, correction=hqf_pdf.QrCorrection.High), CORRECTED),
(hqf_pdf.QrCode(BYTES.encode()), BYTES),
(hqf_pdf.QrCode(LOT.encode(), correction=hqf_pdf.QrCorrection.Quartile), LOT),
]
row_top = TOP
for first in range(0, len(others), 3):
row_top -= ROW_STEP
left = MARGIN
for code, carried in others[first : first + 3]:
side = code.size * MODULE
caption = handle.measure(carried, 8.0)
content.draw_qr(code, left + quiet, row_top, side)
content.draw_text(handle, 8.0, left + quiet, row_top - 12.0, carried)
left += max(side, caption) + quiet * 2.0 + 24.0
# How many modules of the last code are dark, read square by square.
last, __ = others[-1]
size = last.size
dark = sum(
1 for row in range(size) for column in range(size) if last.is_dark(row, column)
)
counted = words.dark.replace("{dark}", str(dark)).replace("{all}", str(size * size))
content.draw_text(handle, BODY, MARGIN, row_top - 50.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()
|