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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597 | """Sets paragraphs whose style changes inside them: sizes that shift mid-line, a
total that is underlined, and a word that turns underlined halfway through. Under them,
a heading set hollow and thickened, rules set where they are told rather than where the
font puts them, a long reference broken after its slashes and cut where nothing else
will do, and a paragraph centred in a box, with what its lines measure said under it.
The Python twin of the `write_rich_text` example in Rust. Each block is laid out in
the same box, so a line is as tall as the tallest style standing on it, and an
underline is drawn where each font says one goes.
The paragraphs are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
set is set. Each is cut around the run whose style changes, so that a language says
what it has to say around the same three pieces.
Usage: python examples/write_rich_text.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_rich_text.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# The left edge of every box, the width they are broken to, the top of the first one,
# and the gap between one block and the next.
LEFT = 56.0
WIDTH = 420.0
TOP = 760.0
GAP = 26.0
# The sum the first paragraph is about. A total is not language.
AMOUNT = "1 240.00 EUR"
# The reference broken in a narrow box: an address that breaks after its slashes, and a
# code with nowhere to break but where the box cuts it.
REFERENCE = "hqf-pdf.com/examples/rich-text/overlong/ABCDEFGHJKLMNPQRSTUVWXYZ0123456789"
# How wide the box the reference is broken in is, in points.
NARROW = 150.0
# How tall the box the centred paragraph sits in is, in points.
BOX_HEIGHT = 60.0
@dataclass(frozen=True)
class Words:
"""Every word the page sets, in one language.
Every paragraph is cut around the run that carries the style being shown, so the
piece that is underlined, enlarged or coloured is a piece of the sentence rather
than a sentence of its own.
"""
# The line at the head of the page.
title: str
# The first paragraph, cut around the amount it names.
due: tuple[str, str]
# The second, cut around the run set in the largest type.
tallest: tuple[str, str, str]
# The third, cut around the run that carries its own colour.
coloured: tuple[str, str, str]
# The fourth, cut in the middle of a word: the second piece turns underlined without
# the word being broken at the join.
joined: tuple[str, str, str]
# The fifth, cut around the run named by the alignment it is set to.
small: tuple[str, str, str]
# A heading cut around its hollow run and its thickened one.
hollow: tuple[str, str, str, str, str]
# A sentence cut around its heavy underline and its thin strikeout.
rules: tuple[str, str, str, str, str]
# What stands over the reference broken in a narrow box.
wrapped: str
# The paragraph centred in a box.
centred: str
# What the centred paragraph's lines measure; `{count}`, `{tall}` and `{wide}` stand
# for how many hold words, how tall they are together and how wide the widest runs.
measured: str
# The page in English.
ENGLISH = Words(
title="Rich text: styles, sizes, underlining, colour",
due=(
"The amount due is ",
(
", payable within thirty days. The balance carries interest at the "
"statutory rate from the day it falls due, and no reminder has to be sent "
"for it to do so."
),
),
tallest=(
"A line is as tall as ",
"the largest",
" of the styles standing on it, and no taller.",
),
coloured=(
"A run can carry its own ",
"colour",
", set apart from the black around it.",
),
joined=(
"A word may change style in the middle: under",
"lined",
" is still one word, and is never broken at the join.",
),
small=(
"The small print sits in small type, ",
"flush right",
", below the body of the text.",
),
hollow=(
"A heading set ",
"hollow",
", or ",
"thickened",
" without a bolder font",
),
rules=(
"A rule can sit where it is told: ",
"a heavy underline",
" clear of the descenders, or ",
"a hairline",
" through the letters.",
),
wrapped=(
"A reference broken after its slashes, and cut where nothing else will do:"
),
centred="This paragraph is centred, across and down, in the box drawn around it.",
measured="{count} lines, {tall} pt tall together, the widest {wide} pt wide.",
)
# The page in French.
FRENCH = Words(
title="Texte enrichi : styles, tailles, soulignement, couleur",
due=(
"Le montant dû est de ",
(
", payable sous trente jours. Le solde produit des intérêts au taux légal "
"à compter du jour de son échéance, sans qu’aucun rappel n’ait à être "
"envoyé."
),
),
tallest=(
"Une ligne est aussi haute que ",
"le plus grand",
" des styles qu’elle contient, et pas davantage.",
),
coloured=(
"Un passage peut avoir sa propre ",
"couleur",
", distincte du noir qui l’entoure.",
),
joined=(
"Un mot peut changer de style en son milieu : souli",
"gné",
" reste un seul mot, et n’est jamais coupé à la jointure.",
),
small=(
"Les mentions légales sont en petits caractères, ",
"alignées à droite",
", sous le corps du texte.",
),
hollow=(
"Un titre ",
"évidé",
", ou ",
"épaissi",
" sans police plus grasse",
),
rules=(
"Un filet peut se placer où on le demande : ",
"un soulignement épais",
" sous les jambages, ou ",
"un trait fin",
" à travers les lettres.",
),
wrapped=(
"Une référence coupée après ses barres obliques, et tranchée là où il n’y a pas "
"d’autre choix :"
),
centred=(
"Ce paragraphe est centré, en largeur et en hauteur, dans le cadre tracé "
"autour de lui."
),
measured="{count} lignes, {tall} pt de haut ensemble, la plus large de {wide} pt.",
)
# The page in Dutch.
DUTCH = Words(
title="Opgemaakte tekst: stijlen, groottes, onderstreping, kleur",
due=(
"Het verschuldigde bedrag is",
(
", te betalen binnen dertig dagen. Over het saldo is vanaf de vervaldag "
"wettelijke rente verschuldigd, zonder dat daarvoor een herinnering hoeft "
"te worden gestuurd."
),
),
tallest=(
"Een regel is zo hoog als",
"de grootste",
" van de stijlen die erop staan, en niet hoger.",
),
coloured=(
"Een stuk kan een eigen",
"kleur",
" hebben, los van het zwart eromheen.",
),
joined=(
"Een woord kan halverwege van stijl veranderen: onder",
"streept",
" is nog steeds één woord, en wordt nooit bij de naad gebroken.",
),
small=(
"De kleine lettertjes staan in kleine letter,",
"rechts uitgelijnd",
", onder de hoofdtekst.",
),
hollow=(
"Een kop gezet",
"hol",
", of",
"verdikt",
" zonder een vettere letter",
),
rules=(
"Een lijn kan staan waar ze moet:",
"een zware onderstreping",
" vrij van de onderstokken, of",
"een haarlijn",
" door de letters.",
),
wrapped=(
"Een kenmerk afgebroken na zijn schuine strepen, en gesneden waar niets anders kan:"
),
centred="Deze alinea is gecentreerd, in de breedte en de hoogte, in het kader eromheen.",
measured="{count} regels, samen {tall} pt hoog, de breedste {wide} pt breed.",
)
# The page in Portuguese.
PORTUGUESE = Words(
title="Texto rico: estilos, tamanhos, sublinhado, cor",
due=(
"O montante em dívida é",
(
", pagável no prazo de trinta dias. O saldo vence juros à taxa legal "
"desde o vencimento, sem necessidade de enviar qualquer aviso."
),
),
tallest=(
"Uma linha é tão alta como",
"o maior",
" dos estilos que leva, e não mais.",
),
coloured=(
"Um troço pode levar a sua própria",
"cor",
", separada do preto à volta.",
),
joined=(
"Uma palavra pode mudar de estilo a meio: sub",
"linhado",
" continua a ser uma palavra, e nunca se parte na junção.",
),
small=(
"As letras miudinhas vão em corpo pequeno,",
"alinhadas à direita",
", por baixo do corpo do texto.",
),
hollow=(
"Um título composto",
"oco",
", ou",
"engrossado",
" sem um tipo de letra mais negro",
),
rules=(
"Um filete pode ficar onde se lhe diz:",
"um sublinhado grosso",
" livre das descendentes, ou",
"um filete fino",
" através das letras.",
),
wrapped=(
"Uma referência partida depois das barras, e cortada onde não há outra forma:"
),
centred="Este parágrafo está centrado, na largura e na altura, na caixa desenhada à sua volta.",
measured="{count} linhas, {tall} pt de altura no total, a mais larga com {wide} pt.",
)
# The page in Italian.
ITALIAN = Words(
title="Testo ricco: stili, corpi, sottolineatura, colore",
due=(
"L’importo dovuto è",
(
", pagabile entro trenta giorni. Il saldo produce interessi al tasso "
"legale dalla scadenza, senza bisogno di alcun sollecito."
),
),
tallest=(
"Una riga è alta quanto",
"il più grande",
" degli stili che porta, e non di più.",
),
coloured=(
"Un tratto può portare il proprio",
"colore",
", separato dal nero che lo circonda.",
),
joined=(
"Una parola può cambiare stile a metà: sotto",
"lineato",
" resta una parola, e non si spezza mai alla giunzione.",
),
small=(
"Le clausole minori stanno in corpo piccolo,",
"allineate a destra",
", sotto il corpo del testo.",
),
hollow=(
"Un titolo composto",
"vuoto",
", o",
"ispessito",
" senza un font più nero",
),
rules=(
"Un filetto può stare dove gli si dice:",
"una sottolineatura spessa",
" libera dai discendenti, o",
"un filetto sottile",
" attraverso le lettere.",
),
wrapped=(
"Un riferimento spezzato dopo le barre, e tagliato dove non c’è altro modo:"
),
centred="Questo paragrafo è centrato, in larghezza e in altezza, nel riquadro disegnato intorno.",
measured="{count} righe, alte {tall} pt in tutto, la più larga di {wide} pt.",
)
# The page in Spanish.
SPANISH = Words(
title="Texto enriquecido: estilos, tamaños, subrayado, color",
due=(
"El importe a pagar es ",
(
", pagadero en treinta días. El saldo devenga intereses al tipo legal "
"desde su vencimiento, sin necesidad de enviar ningún recordatorio."
),
),
tallest=(
"Una línea es tan alta como ",
"el mayor",
" de los estilos que lleva, y no más.",
),
coloured=(
"Un tramo puede llevar su propio ",
"color",
", separado del negro que lo rodea.",
),
joined=(
"Una palabra puede cambiar de estilo a mitad: sub",
"rayado",
" sigue siendo una palabra, y nunca se corta en la unión.",
),
small=(
"La letra pequeña va en cuerpo pequeño, ",
"alineada a la derecha",
", bajo el cuerpo del texto.",
),
hollow=(
"Un título compuesto ",
"hueco",
", o ",
"engrosado",
" sin una fuente más negra",
),
rules=(
"Una raya puede ir donde se le diga: ",
"un subrayado grueso",
" libre de los descendentes, o ",
"un filete",
" a través de las letras.",
),
wrapped=(
"Una referencia cortada tras sus barras, y partida donde no queda otra:"
),
centred="Este párrafo está centrado, a lo ancho y a lo alto, en la caja dibujada a su alrededor.",
measured="{count} líneas, {tall} pt de alto en total, la más ancha de {wide} pt.",
)
# The page in German.
GERMAN = Words(
title="Formatierter Text: Stile, Größen, Unterstreichung, Farbe",
due=(
"Der fällige Betrag ist ",
(
", zahlbar binnen dreißig Tagen. Der Restbetrag wird ab Fälligkeit zum "
"gesetzlichen Zinssatz verzinst, ohne dass dafür eine Mahnung nötig ist."
),
),
tallest=(
"Eine Zeile ist so hoch wie ",
"der größte",
" der Stile, die auf ihr stehen, und nicht höher.",
),
coloured=(
"Ein Abschnitt kann seine eigene ",
"Farbe",
" tragen, abgesetzt vom Schwarz ringsum.",
),
joined=(
"Ein Wort darf mitten im Wort den Stil wechseln: unter",
"strichen",
" bleibt ein Wort und wird an der Naht nie getrennt.",
),
small=(
"Das Kleingedruckte steht in kleiner Schrift, ",
"rechtsbündig",
", unter dem Haupttext.",
),
hollow=(
"Eine Überschrift, ",
"hohl",
" gesetzt oder ",
"verstärkt",
" ohne fettere Schrift",
),
rules=(
"Eine Linie kann stehen, wo man sie hinstellt: ",
"eine kräftige Unterstreichung",
" frei von den Unterlängen, oder ",
"eine Haarlinie",
" durch die Buchstaben.",
),
wrapped=(
"Eine Referenz, nach ihren Schrägstrichen umbrochen und dort getrennt, wo nichts anderes geht:"
),
centred="Dieser Absatz ist in dem um ihn gezeichneten Rahmen waagrecht und senkrecht zentriert.",
measured="{count} Zeilen, zusammen {tall} pt hoch, die breiteste {wide} pt breit.",
)
# 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 blocks(font: hqf_pdf.FontHandle, words: Words) -> list[hqf_pdf.RichText]:
"""The paragraphs, in the order they are shown."""
regular = hqf_pdf.Style(font, 11.0)
small = hqf_pdf.Style(font, 8.0)
large = hqf_pdf.Style(font, 17.0)
marked = hqf_pdf.Style(font, 11.0, underline=True)
accent = hqf_pdf.Style(font, 11.0, color=hqf_pdf.Rgb(0.0, 0.35, 0.7))
return [
hqf_pdf.RichText(align=hqf_pdf.Align.Justify)
.span(words.due[0], regular)
.span(AMOUNT, marked)
.span(words.due[1], regular),
hqf_pdf.RichText()
.span(words.tallest[0], regular)
.span(words.tallest[1], large)
.span(words.tallest[2], regular),
hqf_pdf.RichText()
.span(words.coloured[0], regular)
.span(words.coloured[1], accent)
.span(words.coloured[2], regular),
hqf_pdf.RichText()
.span(words.joined[0], regular)
.span(words.joined[1], marked)
.span(words.joined[2], regular),
hqf_pdf.RichText(align=hqf_pdf.Align.Right)
.span(words.small[0], small)
.span(words.small[1], small)
.span(words.small[2], small),
]
def more(content, font, words, top) -> float:
"""Set the blocks under the first five from `top` down: the hollow and thickened
heading, the rules set where they are told, the reference broken in a narrow box,
and the paragraph centred in a box with what its lines measure; hand back where the
last of them ends."""
regular = hqf_pdf.Style(font, 11.0)
small = hqf_pdf.Style(font, 8.0)
ink = hqf_pdf.Rgb(0.0, 0.0, 0.0)
hollow = hqf_pdf.Style(font, 17.0, outline=0.6, outline_color=ink)
thickened = hqf_pdf.Style(
font,
17.0,
color=hqf_pdf.Rgb(0.0, 0.35, 0.7),
outline=0.8,
outline_color=hqf_pdf.Rgb(0.0, 0.2, 0.45),
outline_filled=True,
)
heading = hqf_pdf.Style(font, 17.0)
# A heavy underline four points under the baseline, and a hairline three points over
# it.
heavy = hqf_pdf.Style(font, 11.0, underline_at=(-4.0, 1.5))
hairline = hqf_pdf.Style(font, 11.0, strikethrough_at=(3.0, 0.4))
blocks_under = [
hqf_pdf.RichText()
.span(words.hollow[0], heading)
.span(words.hollow[1], hollow)
.span(words.hollow[2], heading)
.span(words.hollow[3], thickened)
.span(words.hollow[4], heading),
hqf_pdf.RichText()
.span(words.rules[0], regular)
.span(words.rules[1], heavy)
.span(words.rules[2], regular)
.span(words.rules[3], hairline)
.span(words.rules[4], regular),
hqf_pdf.RichText().span(words.wrapped, regular),
]
for block in blocks_under:
lines = block.break_lines(WIDTH)
block.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP / 2.0
reference = hqf_pdf.RichText(
overlong=hqf_pdf.Overlong.Break, cut_mark="-", break_after="/"
).span(REFERENCE, regular)
lines = reference.break_lines(NARROW)
reference.draw(content, lines, LEFT, top, NARROW)
top -= hqf_pdf.RichText.height(lines) + GAP
content.save_state()
content.set_stroke(hqf_pdf.Rgb(0.7, 0.7, 0.7))
content.set_line_width(0.5)
content.rect(LEFT, top - BOX_HEIGHT, WIDTH, BOX_HEIGHT)
content.stroke()
content.restore_state()
centred = hqf_pdf.RichText(align=hqf_pdf.Align.Center).span(words.centred, regular)
inside = WIDTH - 40.0
lines = centred.break_lines(inside)
start = hqf_pdf.RichText.top_for(lines, top, BOX_HEIGHT, hqf_pdf.VAlign.Middle)
centred.draw(content, lines, LEFT + 20.0, start, inside)
top -= BOX_HEIGHT + 14.0
count = sum(1 for index in range(len(lines)) if not lines.is_empty(index))
tall = sum(lines.height(index) for index in range(len(lines)))
wide = max((lines.natural_width(index) for index in range(len(lines))), default=0.0)
said = (
words.measured.replace("{count}", str(count))
.replace("{tall}", f"{tall:.0f}")
.replace("{wide}", f"{wide:.0f}")
)
caption = hqf_pdf.RichText().span(said, small)
lines = caption.break_lines(WIDTH)
caption.draw(content, lines, LEFT, top, WIDTH)
return top - hqf_pdf.RichText.height(lines)
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("rich.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
content = hqf_pdf.Content()
content.draw_text(font, 14.0, LEFT, TOP + 24.0, words.title)
paragraphs = blocks(font, words)
top = TOP
for block in paragraphs:
lines = block.break_lines(WIDTH)
block.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP
top = more(content, font, words, top)
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
written = document.write(out)
print(f"wrote {out}: {written} bytes, {len(paragraphs)} blocks")
if __name__ == "__main__":
main()
|