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 | """Draws one badge, and places it eight times.
The Python twin of the `write_drawing` example in Rust. The badge — its frame, its
coloured head, its mark — is built once as a drawing, and the file holds its
operators once however many times it is placed. Each placing costs a name and a
matrix. The names on the badges are drawn by the page, over the drawing, because
they are what differs.
A second page places the badge once more, built this time with a matrix of its own
that turns it a quarter wherever it is placed, a packet of metadata saying what it is,
and the guest list carried as a file of its own; the page states each from what the
drawing says of itself. A file tied to a drawing is PDF 2.0, so the file says so on its
first line.
Every position is measured from the top-left corner, `y` growing down the page the
way a screen measures: the badge in axes laid on its own box, each page in axes laid
on its sheet. The axes hand back the numbers PDF writes, so the text stays upright and
nothing is mirrored.
What the page reads is held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn. The guests' names are not language, and neither is the company's:
a name is written the way its owner writes it.
Usage: python examples/write_drawing.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_drawing.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# The size of one badge, in points.
BADGE = (220.0, 96.0)
# The left edge of everything the page draws.
LEFT = 70.0
# The baseline of each page's title, down from the top edge of the sheet.
TITLE = 61.89
# The baseline of the line under the first page's title.
INTRO = 79.89
# The top edge of the first row of badges.
FIRST_ROW = 145.89
# How far down from a badge's top edge the guest's name and trade sit.
NAME = 48.0
ROLE = 64.0
# The top edge of the badge placed at half size, and the baseline of the line under it.
HALF = 643.89
HALF_CAPTION = 707.89
# The top edge of the second page's turned badge, and the baseline of the first line
# beside it.
TURNED_TOP = 101.89
TURNED_LINES = 121.89
# Who the badges are for. A name is not language.
GUESTS = [
"Amélie Roussel",
"Bertrand Colin",
"Chloé Marchand",
"Damien Leclerc",
"Élise Fontaine",
"Fabien Deschamps",
"Gabrielle Vidal",
"Hugo Mercier",
]
# The company the badges are issued by, drawn in the badge itself. A company writes its
# name one way.
COMPANY = "HQF Development"
@dataclass(frozen=True)
class Words:
"""Every word the page draws, in one language."""
# The line at the head of the page.
title: str
# The line under it, saying what a drawing costs.
intro: str
# What the badge itself says under the company's name, drawn once for all eight.
occasion: str
# What each guest does, in the order the badges are placed.
roles: tuple[str, str, str, str, str, str, str, str]
# The line under the badge placed at half size.
half: str
# The line at the head of the second page.
turned_title: str
# What the second page says of the turned badge's matrix.
turned: str
# What it says of its metadata; `{title}` stands for the title the metadata gives.
says: str
# What it says of the files it carries; `{count}` stands for how many.
carries: str
# The title the turned badge's metadata gives it.
badge_title: str
# What the carried guest list is.
list: str
# The page in English.
ENGLISH = Words(
title="One badge, placed eight times",
intro=(
"The badge is drawn once; the file holds its operators once, whatever it "
"costs to place."
),
occasion="Open house — visitor",
roles=(
"Bindery",
"Typesetting",
"Prepress",
"Colour",
"Plates",
"Press",
"Finishing",
"Despatch",
),
half="The same drawing, placed at half size.",
turned_title="The badge, turned by a matrix of its own",
turned="Its own matrix turns it a quarter wherever it is placed.",
says="It says what it is in a packet of its own: {title}.",
carries="It carries {count} file of its own: the guest list.",
badge_title="Visitor badge",
list="The guests the badges are made for",
)
# The page in French.
FRENCH = Words(
title="Un badge, posé huit fois",
intro=(
(("Dessiné une fois, le badge n’a qu’un jeu d’instructions, même posé huit "
"fois."))
),
occasion="Portes ouvertes — visiteur",
roles=(
"Reliure",
"Composition",
"Prépresse",
"Couleur",
"Plaques",
"Impression",
"Façonnage",
"Expédition",
),
half="Le même dessin, posé à la moitié de sa taille.",
turned_title="Le badge, tourné par sa propre matrice",
turned="Sa propre matrice le tourne d’un quart de tour où qu’on le pose.",
says="Il dit ce qu’il est dans son propre paquet : {title}.",
carries="Il contient {count} fichier bien à lui : la liste des invités.",
badge_title="Badge visiteur",
list="Les invités à qui les badges sont destinés",
)
# The page in Dutch.
DUTCH = Words(
title="Eén badge, acht keer geplaatst",
intro=(
"De badge wordt één keer getekend; zijn operatoren staan één keer in het "
"bestand."
),
occasion="Open dag — bezoeker",
roles=(
"Binderij",
"Zetterij",
"Prepress",
"Kleur",
"Platen",
"Pers",
"Afwerking",
"Verzending",
),
half="Dezelfde tekening, op halve grootte geplaatst.",
turned_title="De badge, gedraaid door een eigen matrix",
turned="Zijn eigen matrix draait hem een kwartslag waar hij ook staat.",
says="Hij vermeldt in een eigen pakket wat hij is: {title}.",
carries="Hij bevat {count} eigen bestand: de gastenlijst.",
badge_title="Bezoekersbadge",
list="De gasten voor wie de badges gemaakt worden",
)
# The page in Portuguese.
PORTUGUESE = Words(
title="Um crachá, colocado oito vezes",
intro=(
"O crachá é desenhado uma vez; os seus operadores ficam uma só vez no "
"ficheiro."
),
occasion="Dia aberto — visitante",
roles=(
"Encadernação",
"Composição",
"Pré-impressão",
"Cor",
"Chapas",
"Impressão",
"Acabamento",
"Expedição",
),
half="O mesmo desenho, colocado a meia escala.",
turned_title="O crachá, rodado por uma matriz própria",
turned="A sua matriz roda-o um quarto de volta onde quer que esteja.",
says="Diz o que é num pacote próprio: {title}.",
carries="Leva {count} ficheiro próprio: a lista de convidados.",
badge_title="Crachá de visitante",
list="Os convidados para quem se fazem os crachás",
)
# The page in Italian.
ITALIAN = Words(
title="Un distintivo, collocato otto volte",
intro=(
"Il distintivo è disegnato una volta; i suoi operatori stanno una sola volta "
"nel file."
),
occasion="Porte aperte — visitatore",
roles=(
"Legatoria",
"Composizione",
"Prestampa",
"Colore",
"Lastre",
"Stampa",
"Finitura",
"Spedizione",
),
half="Lo stesso disegno, collocato a metà scala.",
turned_title="Il distintivo, ruotato da una matrice propria",
turned="La sua matrice lo ruota di un quarto ovunque sia collocato.",
says="Dice cosa è in un pacchetto proprio: {title}.",
carries="Porta {count} file proprio: l’elenco degli ospiti.",
badge_title="Distintivo visitatore",
list="Gli ospiti per cui si fanno i distintivi",
)
# The page in Spanish.
SPANISH = Words(
title="Una insignia, colocada ocho veces",
intro=(
"La insignia se dibuja una vez; sus operadores están una sola vez en el "
"archivo."
),
occasion="Puertas abiertas — visitante",
roles=(
"Encuadernación",
"Composición",
"Preimpresión",
"Color",
"Planchas",
"Prensa",
"Acabado",
"Expedición",
),
half="El mismo dibujo, colocado a media escala.",
turned_title="La insignia, girada por una matriz propia",
turned="Su propia matriz la gira un cuarto dondequiera que se coloque.",
says="Dice lo que es en un paquete propio: {title}.",
carries="Lleva {count} archivo propio: la lista de invitados.",
badge_title="Insignia de visitante",
list="Los invitados para los que se hacen las insignias",
)
# The page in German.
GERMAN = Words(
title="Ein Abzeichen, achtmal platziert",
intro=(
"Einmal gezeichnet; die Datei enthält seine Operatoren einmal, wie oft es "
"erscheint."
),
occasion="Tag der offenen Tür — Besucher",
roles=(
"Buchbinderei",
"Satz",
"Druckvorstufe",
"Farbe",
"Platten",
"Druck",
"Weiterverarbeitung",
"Versand",
),
half="Dieselbe Zeichnung, in halber Größe platziert.",
turned_title="Das Abzeichen, durch eine eigene Matrix gedreht",
turned="Seine Matrix dreht es um ein Viertel, wo immer es steht.",
says="Es sagt in einem eigenen Paket, was es ist: {title}.",
carries="Es trägt {count} eigene Datei: die Gästeliste.",
badge_title="Besucherabzeichen",
list="Die Gäste, für die die Abzeichen gemacht sind",
)
# 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 text(
content: hqf_pdf.Content,
font: hqf_pdf.FontHandle,
size: float,
at: tuple[hqf_pdf.Axes, float, float],
line: str,
) -> None:
"""Draws one line of text with its baseline at `(x, y)` in `axes`."""
axes, x, y = at
x, y = axes.point_to_page(x, y)
content.draw_text(font, size, x, y, line)
def rect(content: hqf_pdf.Content, axes: hqf_pdf.Axes, rect: hqf_pdf.Rect) -> None:
"""Draws `rect`, stated in `axes`, as a rectangle path."""
placed = axes.rect_to_page(rect)
content.rect(placed.x, placed.y, placed.width, placed.height)
def badge(font: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Drawing:
"""The badge itself: everything every badge has, measured from the top-left corner
of its box."""
width, height = BADGE
room = hqf_pdf.Rect(0.0, 0.0, width, height)
axes = hqf_pdf.Axes.top_left(room)
content = hqf_pdf.Content()
content.set_fill(hqf_pdf.Rgb(0.96, 0.97, 0.99))
rect(content, axes, hqf_pdf.Rect(0.0, 0.0, width, height))
content.fill()
content.set_fill(hqf_pdf.Rgb(0.12, 0.28, 0.52))
rect(content, axes, hqf_pdf.Rect(0.0, 0.0, width, 24.0))
content.fill()
content.set_stroke(hqf_pdf.Rgb(0.12, 0.28, 0.52))
content.set_line_width(1.0)
rect(content, axes, hqf_pdf.Rect(0.0, 0.0, width, height))
content.stroke()
content.set_fill(hqf_pdf.Rgb(1.0, 1.0, 1.0))
text(content, font, 11.0, (axes, 12.0, 17.0), COMPANY)
content.set_fill(hqf_pdf.Rgb.gray(0.45))
text(content, font, 8.0, (axes, 12.0, 84.0), words.occasion)
return hqf_pdf.Drawing(content, room)
# What turns the second page's badge a quarter anticlockwise: its box, from the origin,
# then stands to the left of the point it is placed at.
QUARTER = (0.0, 1.0, -1.0, 0.0, 0.0, 0.0)
# Where the second page's lines start, in points from the left edge.
TURNED_TEXT = LEFT + 130.0
def turned_page(
document: hqf_pdf.Document, font: hqf_pdf.FontHandle, words: Words
) -> hqf_pdf.Page:
"""The second page: the badge built with a matrix, metadata and a carried file of
its own, placed once, and what it says of each."""
guests = document.attach(
hqf_pdf.Attachment(
"guests.txt",
words.list,
"text/plain",
hqf_pdf.Relationship.Data,
"2026-09-17T09:00:00+02:00",
"\n".join(GUESTS).encode(),
)
)
turned = (
badge(font, words)
.matrix(QUARTER)
.with_metadata(hqf_pdf.Xmp.facts(hqf_pdf.Metadata(title=words.badge_title)))
.associated_with([guests])
)
lines = [words.turned]
if turned.metadata is not None:
lines.append(words.says.replace("{title}", words.badge_title))
lines.append(words.carries.replace("{count}", str(len(turned.associated_files))))
handle = document.add_drawing(turned)
width, height = BADGE
page = hqf_pdf.Page.a4()
axes = page.top_left_axes()
content = hqf_pdf.Content()
text(content, font, 15.0, (axes, LEFT, TITLE), words.turned_title)
# Turned a quarter, the badge stands `height` wide and `width` tall, and its own
# matrix puts its box to the left of the point it is placed at.
seen = axes.rect_to_page(hqf_pdf.Rect(LEFT, TURNED_TOP, height, width))
content.draw_form(handle, seen.x + height, seen.y, 1.0)
y = TURNED_LINES
for line in lines:
text(content, font, 10.0, (axes, TURNED_TEXT, y), line)
y += 16.0
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("drawing.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
handle = document.add_drawing(badge(font, words))
width, height = BADGE
page = hqf_pdf.Page.a4()
axes = page.top_left_axes()
content = hqf_pdf.Content()
text(content, font, 15.0, (axes, LEFT, TITLE), words.title)
content.save_state()
content.set_fill(hqf_pdf.Rgb.gray(0.35))
text(content, font, 10.0, (axes, LEFT, INTRO), words.intro)
content.restore_state()
top = FIRST_ROW
for start in range(0, len(GUESTS), 2):
x = LEFT
for index in range(start, min(start + 2, len(GUESTS))):
placed = axes.rect_to_page(hqf_pdf.Rect(x, top, width, height))
content.draw_form(handle, placed.x, placed.y, 1.0)
text(content, font, 14.0, (axes, x + 12.0, top + NAME), GUESTS[index])
content.save_state()
content.set_fill(hqf_pdf.Rgb.gray(0.4))
text(content, font, 10.0, (axes, x + 12.0, top + ROLE), words.roles[index])
content.restore_state()
x += width + 20.0
top += height + 20.0
# The same drawing again, at half size: a placing carries its own scale.
half = axes.rect_to_page(hqf_pdf.Rect(LEFT, HALF, width / 2.0, height / 2.0))
content.draw_form(handle, half.x, half.y, 0.5)
content.save_state()
content.set_fill(hqf_pdf.Rgb.gray(0.35))
text(content, font, 10.0, (axes, LEFT, HALF_CAPTION), words.half)
content.restore_state()
page.set_content(content)
document.add_page(page)
document.add_page(turned_page(document, font, words))
document.set_version(hqf_pdf.Version.V2_0)
written = document.write(out)
print(f"wrote {out}: {written} bytes, {len(GUESTS) + 2} placings of one drawing")
if __name__ == "__main__":
main()
|