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 | """Writes a one-page price offer whose text cannot be selected, searched, copied or
extracted: every letter on the page is a shape traced from the outline of its font, and
the file holds no text at all.
The Python twin of the `write_text_as_shapes` example in Rust. The page reads as any
price offer would. A note at its foot says what was done to it, and what that costs:
nothing on the page can be read aloud, the file carries no structure for accessibility,
and it is larger.
The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
the page is written in.
Usage: python examples/write_text_as_shapes.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_text_as_shapes.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# How far in from the left and right edges of the sheet the text stands, in points.
MARGIN = 56.0
# How wide the text runs, in points: the A4 sheet less both margins.
WIDTH = 595.0 - 2.0 * MARGIN
# How wide the column of amounts is, in points, at the right of the text.
AMOUNT_WIDTH = 110.0
# How wide the column of what each amount pays for is, in points.
LABEL_WIDTH = WIDTH - AMOUNT_WIDTH
# Where the top of the first line stands, in points up from the foot of the sheet.
TOP = 800.0
# How far one row of the price list stands below the one above it, in points.
ROW = 20.0
# The firm that sends the price offer, written the same way in every language.
SENDER = "Northfield Acoustics"
# The amount of each line of the price list, in the order of `Words.items`.
AMOUNTS = ("1 850.00 EUR", "14 400.00 EUR", "2 200.00 EUR")
# The sum of `AMOUNTS`.
TOTAL = "18 450.00 EUR"
@dataclass(frozen=True)
class Words:
"""Every word the page sets, in one language."""
# What the document is, set large under the sender.
title: str
# The price offer's reference, the day it was issued and how long it holds.
reference: str
# Who the price offer is for, and what it is about.
addressee: str
# The paragraph saying what the work is.
intro: str
# What each amount of the price list pays for, one line each.
items: tuple[str, str, str]
# What the total under the price list is.
total: str
# The terms of payment and of the start of the work.
terms: str
# The heading of the note at the foot of the page.
note_title: str
# The note at the foot of the page, saying that the page holds no text.
note: str
# The page in English.
ENGLISH = Words(
title="Price offer",
reference="Reference Q-2026-0147 · issued on 2026-10-25 · valid for sixty days",
addressee="For Harbour Theatre: the acoustics of the main hall",
intro=(
"Following our visit on 2026-10-12, we propose to measure how the main hall "
"answers speech and music, to fit sound-absorbing panels along the side walls "
"and under the balcony, and to tune the room once they are up, so that an "
"actor speaking without a microphone is heard clearly from the last row."
),
items=(
"Survey: acoustic measurements from twelve seats, report",
"Supply and fitting of 48 fabric-covered panels",
"Tuning after fitting, second measurement, final report",
),
total="Total excluding VAT",
terms=(
"Prices exclude VAT. Thirty per cent on order, the balance on completion. Work"
" can start four weeks after the signed price offer reaches us."
),
note_title="Try to copy a word of this page",
note=(
"Every letter on this page is a shape traced from the outline of its font: the"
" file holds no text at all. A reader sees the price offer exactly as it would "
"otherwise look, but can neither select a word, nor search for one, nor copy "
"the prices into another document, and a program that extracts text finds "
"nothing. A sender uses this when a document must be read but not taken over. "
"What it costs: nothing can be read aloud, there is no structure for "
"accessibility, and the file is larger."
),
)
# The page in French.
FRENCH = Words(
title="Offre commerciale",
reference="Référence Q-2026-0147 · date d’émission 2026-10-25 · validité soixante jours",
addressee="Pour le Harbour Theatre : acoustique de la grande salle",
intro=(
"À la suite de notre visite du 2026-10-12, nous proposons de mesurer la façon "
"dont la grande salle restitue la voix et la musique, de poser des panneaux "
"absorbants le long des murs latéraux et sous le balcon, puis de procéder au "
"réglage une fois les panneaux posés, afin qu’un comédien parlant sans micro soit"
" entendu distinctement jusqu’au dernier rang."
),
items=(
"Relevé acoustique depuis 12 fauteuils et rapport",
"Fourniture et pose de 48 panneaux tendus de tissu",
"Réglage après pose, seconde mesure et rapport final",
),
total="Total hors TVA",
terms=(
"Prix indiqués hors TVA. Acompte de trente pour cent à la commande, solde à la "
"fin des travaux. Les travaux peuvent commencer quatre semaines après réception "
"de l’offre signée."
),
note_title="Essayez de copier un mot de cette page",
note=(
"Chaque lettre de cette page est une forme tracée d’après le contour de sa "
"police : le fichier ne contient aucun texte. Celui qui l’ouvre voit l’offre "
"exactement comme si elle était composée normalement, mais il ne peut ni "
"sélectionner"
" ni rechercher un mot, ni copier les prix dans un autre document ; un programme "
"d’extraction de texte ne trouve rien. On utilise ce procédé quand un document "
"doit être lu sans pouvoir être repris. En contrepartie : aucun lecteur d’écran "
"ne peut le lire à voix haute, le document n’a aucune structure utile à "
"l’accessibilité, et le fichier est plus lourd."
),
)
# The page in German.
GERMAN = Words(
title="Angebot",
reference="Referenz Q-2026-0147 · ausgestellt am 2026-10-25 · sechzig Tage gültig",
addressee="Für das Harbour Theatre: Raumakustik des großen Saals",
intro=(
"Nach unserem Besuch am 2026-10-12 schlagen wir vor, zu messen, wie der große "
"Saal auf Sprache und Musik antwortet, entlang der Seitenwände und unter dem "
"Rang schallabsorbierende Paneele anzubringen und den Raum danach abzustimmen,"
" damit ein Schauspieler ohne Mikrofon bis in die letzte Reihe deutlich zu "
"verstehen ist."
),
items=(
"Bestandsaufnahme: Messungen von zwölf Plätzen aus, Bericht",
"Lieferung und Montage von 48 stoffbespannten Paneelen",
"Abstimmung nach der Montage, zweite Messung, Abschlussbericht",
),
total="Summe ohne MwSt.",
terms=(
"Preise ohne MwSt. Dreißig Prozent bei Auftragserteilung, der Rest nach "
"Abschluss der Arbeiten. Die Arbeiten können vier Wochen nach Eingang des "
"unterschriebenen Angebots beginnen."
),
note_title="Versuchen Sie, ein Wort dieser Seite zu kopieren",
note=(
"Jeder Buchstabe dieser Seite ist eine Form, nachgezeichnet aus dem Umriss "
"seiner Schrift: Die Datei enthält überhaupt keinen Text. Der Leser sieht das "
"Angebot genau so, wie es sonst aussähe, kann aber weder ein Wort markieren "
"noch danach suchen noch die Preise in ein anderes Dokument kopieren, und ein "
"Programm, das Text ausliest, findet nichts. Ein Absender nutzt das, wenn ein "
"Dokument gelesen, aber nicht übernommen werden soll. Der Preis dafür: Nichts "
"kann vorgelesen werden, es gibt keine Struktur für die Barrierefreiheit, und "
"die Datei ist größer."
),
)
# The page in Spanish.
SPANISH = Words(
title="Presupuesto",
reference="Referencia Q-2026-0147 · emitido el 2026-10-25 · válido sesenta días",
addressee="Para el Harbour Theatre: acústica de la sala principal",
intro=(
"Tras nuestra visita del 2026-10-12, proponemos medir cómo responde la sala "
"principal a la voz y a la música, colocar paneles absorbentes a lo largo de "
"las paredes laterales y bajo el anfiteatro, y afinar la sala una vez "
"instalados, para que un actor que hable sin micrófono se oiga con claridad "
"desde la última fila."
),
items=(
"Estudio: mediciones acústicas desde doce butacas, informe",
"Suministro e instalación de 48 paneles forrados de tela",
"Afinado tras la instalación, segunda medición, informe final",
),
total="Total sin IVA",
terms=(
"Precios sin IVA. Un treinta por ciento al hacer el pedido y el resto al "
"terminar. Los trabajos pueden empezar cuatro semanas después de recibir el "
"presupuesto firmado."
),
note_title="Intente copiar una palabra de esta página",
note=(
"Cada letra de esta página es una forma trazada a partir del contorno de su "
"fuente: el archivo no contiene ningún texto. El lector ve el presupuesto "
"exactamente como se vería de otro modo, pero no puede seleccionar una "
"palabra, ni buscarla, ni copiar los precios en otro documento, y un programa "
"que extrae texto no encuentra nada. Un remitente lo usa cuando un documento "
"debe leerse pero no reutilizarse. Lo que cuesta: nada puede leerse en voz "
"alta, no hay estructura para la accesibilidad y el archivo pesa más."
),
)
# The page in Italian.
ITALIAN = Words(
title="Preventivo",
reference="Riferimento Q-2026-0147 · emesso il 2026-10-25 · valido sessanta giorni",
addressee="Per l’Harbour Theatre: acustica della sala grande",
intro=(
"Dopo il nostro sopralluogo del 2026-10-12, proponiamo di misurare come la "
"sala grande risponde alla voce e alla musica, di montare pannelli "
"fonoassorbenti lungo le pareti laterali e sotto la galleria, e di tarare la "
"sala una volta montati, perché un attore che parla senza microfono si senta "
"chiaramente fino all’ultima fila."
),
items=(
"Rilievo: misure acustiche da dodici poltrone, relazione",
"Fornitura e posa di 48 pannelli rivestiti in tessuto",
"Taratura dopo la posa, seconda misura, relazione finale",
),
total="Totale IVA esclusa",
terms=(
"Prezzi IVA esclusa. Il trenta per cento all’ordine, il saldo a fine lavori. I"
" lavori possono iniziare quattro settimane dopo il ricevimento del preventivo"
" firmato."
),
note_title="Provate a copiare una parola di questa pagina",
note=(
"Ogni lettera di questa pagina è una forma tracciata dal contorno del suo "
"carattere: il file non contiene alcun testo. Il lettore vede il preventivo "
"esattamente come apparirebbe altrimenti, ma non può selezionare una parola, "
"né cercarla, né copiare i prezzi in un altro documento, e un programma che "
"estrae il testo non trova nulla. Un mittente lo usa quando un documento deve "
"essere letto ma non ripreso. Il costo: nulla può essere letto ad alta voce, "
"non c’è struttura per l’accessibilità e il file è più pesante."
),
)
# The page in Portuguese.
PORTUGUESE = Words(
title="Orçamento",
reference="Referência Q-2026-0147 · emitido a 2026-10-25 · válido sessenta dias",
addressee="Para o Harbour Theatre: acústica da sala principal",
intro=(
"Na sequência da nossa visita de 2026-10-12, propomos medir a forma como a "
"sala principal responde à voz e à música, colocar painéis absorventes ao "
"longo das paredes laterais e sob o balcão, e afinar a sala depois de "
"colocados, para que um ator que fale sem microfone seja ouvido com clareza na"
" última fila."
),
items=(
"Levantamento: medições acústicas a partir de doze lugares, relatório",
"Fornecimento e colocação de 48 painéis revestidos a tecido",
"Afinação após a colocação, segunda medição, relatório final",
),
total="Total sem IVA",
terms=(
"Preços sem IVA. Trinta por cento com a encomenda, o restante no fim dos "
"trabalhos. Os trabalhos podem começar quatro semanas após recebermos o "
"orçamento assinado."
),
note_title="Experimente copiar uma palavra desta página",
note=(
"Cada letra desta página é uma forma traçada a partir do contorno da sua "
"fonte: o ficheiro não contém texto nenhum. O leitor vê o orçamento exatamente"
" como o veria de outra forma, mas não consegue selecionar uma palavra, nem "
"procurá-la, nem copiar os preços para outro documento, e um programa que "
"extrai texto não encontra nada. Um remetente usa isto quando um documento "
"deve ser lido, mas não reaproveitado. O que custa: nada pode ser lido em voz "
"alta, não há estrutura para a acessibilidade e o ficheiro fica maior."
),
)
# The page in Dutch.
DUTCH = Words(
title="Offerte",
reference="Referentie Q-2026-0147 · uitgegeven op 2026-10-25 · zestig dagen geldig",
addressee="Voor het Harbour Theatre: akoestiek van de grote zaal",
intro=(
"Na ons bezoek op 2026-10-12 stellen we voor te meten hoe de grote zaal op "
"spraak en muziek reageert, langs de zijwanden en onder het balkon "
"geluidsabsorberende panelen aan te brengen en de zaal daarna af te stemmen, "
"zodat een acteur die zonder microfoon spreekt tot op de laatste rij duidelijk"
" te verstaan is."
),
items=(
"Opname: akoestische metingen vanaf twaalf stoelen, rapport",
"Levering en montage van 48 met stof beklede panelen",
"Afstemming na montage, tweede meting, eindrapport",
),
total="Totaal exclusief btw",
terms=(
"Prijzen exclusief btw. Dertig procent bij bestelling, het saldo na "
"oplevering. De werkzaamheden kunnen vier weken na ontvangst van de "
"ondertekende offerte beginnen."
),
note_title="Probeer een woord van deze pagina te kopiëren",
note=(
"Elke letter op deze pagina is een vorm die is nagetrokken van de omtrek van "
"het lettertype: het bestand bevat helemaal geen tekst. De lezer ziet de "
"offerte precies zoals die er anders uit zou zien, maar kan geen woord "
"selecteren, er niet naar zoeken en de prijzen niet naar een ander document "
"kopiëren, en een programma dat tekst uitleest, vindt niets. Een afzender "
"gebruikt dit wanneer een document gelezen maar niet overgenomen mag worden. "
"Wat het kost: niets kan worden voorgelezen, er is geen structuur voor "
"toegankelijkheid en het bestand is groter."
),
)
# 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 row_flow(handle: hqf_pdf.FontHandle, align: hqf_pdf.Align) -> hqf_pdf.TextFlow:
"""The flow one row of the price list sets its label in, and its amount."""
return hqf_pdf.TextFlow(handle, 10.5, align=align, leading=14.0)
def set_text(
content: hqf_pdf.Content,
flow: hqf_pdf.TextFlow,
text: str,
x: float,
top: float,
width: float,
) -> float:
"""Sets `text` in `flow` across `width` points from `x`, its top at `top`, and
returns how tall it stands."""
lines = flow.break_lines(text, width)
flow.draw(content, lines, x, top, width)
return flow.height(lines)
def rule(content: hqf_pdf.Content, y: float) -> None:
"""A thin grey rule across the text at `y`."""
content.save_state()
content.set_stroke(hqf_pdf.Rgb.gray(0.6))
content.set_line_width(0.5)
content.move_to(MARGIN, y)
content.line_to(MARGIN + WIDTH, y)
content.stroke()
content.restore_state()
def compose(
content: hqf_pdf.Content, handle: hqf_pdf.FontHandle, words: Words
) -> float:
"""Sets the whole price offer in `words` onto `content`, from the top of the sheet
down, and returns where the last line ends, in points up from the foot of the
sheet."""
top = TOP
sender = hqf_pdf.TextFlow(handle, 12.0, leading=15.0)
top -= set_text(content, sender, SENDER, MARGIN, top, WIDTH) + 18.0
title = hqf_pdf.TextFlow(handle, 24.0, leading=28.0)
top -= set_text(content, title, words.title, MARGIN, top, WIDTH) + 6.0
small = hqf_pdf.TextFlow(handle, 9.5, leading=13.0)
top -= set_text(content, small, words.reference, MARGIN, top, WIDTH) + 4.0
addressee = hqf_pdf.TextFlow(handle, 11.0, leading=14.0)
top -= set_text(content, addressee, words.addressee, MARGIN, top, WIDTH) + 18.0
body = hqf_pdf.TextFlow(handle, 10.5, leading=15.0)
top -= set_text(content, body, words.intro, MARGIN, top, WIDTH) + 16.0
label = row_flow(handle, hqf_pdf.Align.Left)
amount = row_flow(handle, hqf_pdf.Align.Right)
for item, price in zip(words.items, AMOUNTS):
set_text(content, label, item, MARGIN, top, LABEL_WIDTH)
set_text(content, amount, price, MARGIN + LABEL_WIDTH, top, AMOUNT_WIDTH)
top -= ROW
rule(content, top - 2.0)
top -= 8.0
set_text(content, label, words.total, MARGIN, top, LABEL_WIDTH)
set_text(content, amount, TOTAL, MARGIN + LABEL_WIDTH, top, AMOUNT_WIDTH)
top -= ROW + 12.0
top -= set_text(content, small, words.terms, MARGIN, top, WIDTH) + 40.0
rule(content, top)
top -= 14.0
heading = hqf_pdf.TextFlow(handle, 11.0, leading=14.0)
top -= set_text(content, heading, words.note_title, MARGIN, top, WIDTH) + 4.0
top -= set_text(content, small, words.note, MARGIN, top, WIDTH)
return top
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
# languages do not overwrite each other in `tmp/`.
out = _out.output_path(
Path(_language.file_name("text_as_shapes.pdf", language)).stem
)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
content = hqf_pdf.Content()
compose(content, handle, words)
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
# Every letter of the page is written as a shape traced from the font: the file
# holds no text to select, search, copy or extract.
document.set_text_as_shapes(True)
written = document.write(out)
print(f"wrote {out}: {written} bytes")
if __name__ == "__main__":
main()
|