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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816 | """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.
Last, two prices in two styles lined up on their decimal points by a tab stop, and a
justified paragraph whose closing line goes flush right. A second page sets a table of
contents whose dots lead from each title to its page number in the title's own size,
and the same three lines of figures twice: as tall as the largest style on them, then
as tall as the style each opens in.
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"
# The two prices lined up on their decimal points. A price is not language.
PRICES = ("18.50", "1240.05")
# Where the decimal points of the prices stand, from the left edge of the box.
PRICE_STOP = 300.0
# 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
# The page numbers the table of contents leads to. A page number is not language.
PAGES = ("3", "8", "15")
# The amounts set beside the labels whose lines take their height two ways. An amount is
# not language.
FIGURES = ("1 240.00", "248.00", "1 488.00")
# How wide each of the two columns of figures is, in points.
COLUMN = 200.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
# What stands over the prices.
lined_up: str
# What each of the two prices is for.
priced: tuple[str, str]
# The justified paragraph whose closing line goes flush right.
closing: str
# The line at the head of the second page.
second_title: str
# What stands over the table of contents.
contents_intro: str
# The titles of the table of contents: a chapter, one of its sections, and a second
# chapter.
contents: tuple[str, str, str]
# What stands over the two columns of figures.
line_height_intro: str
# What each of the three figures is for.
labels: tuple[str, str, 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.",
lined_up="Prices set in two styles, lined up on their decimal points:",
priced=("Binding", "Cover, two colours"),
closing="A justified paragraph can choose how its closing line is set: this one fills every line but the last to both edges, and sends the last one flush right.",
second_title="Leaders and line height",
contents_intro="A table of contents: dots lead from each title to its page number, set in the size of the title they follow.",
contents=("Styles within a paragraph", "Rules, outlines and colour", "Tab stops and leaders"),
line_height_intro="The same three lines twice. On the left, each line is as tall as the largest figure on it; on the right, as tall as the label it opens with.",
labels=("Goods", "Delivery", "Amount due"),
)
# 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.",
lined_up="Prix en deux styles, alignés sur leur séparateur décimal :",
priced=("Reliure", "Couverture en deux couleurs"),
closing="Dans un paragraphe justifié, la composition de la dernière ligne se choisit : ici, toutes les lignes vont d’un bord à l’autre, sauf la dernière, alignée à droite.",
second_title="Points de conduite et hauteur de ligne",
contents_intro="Dans une table des matières, des points de conduite relient chaque titre à son numéro de page ; ils ont la taille de caractères du titre qu’ils prolongent.",
contents=("Styles dans un paragraphe", "Filets, contours et couleur", "Taquets de tabulation et points de conduite"),
line_height_intro="Les trois mêmes lignes, présentées deux fois. À gauche, chaque ligne prend la hauteur du chiffre le plus gros qu’elle contient ; à droite, celle du libellé par lequel elle commence.",
labels=("Marchandises", "Livraison", "Montant dû"),
)
# 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.",
lined_up="Prijzen in twee stijlen, uitgelijnd op hun decimale punt:",
priced=("Inbinden", "Omslag, twee kleuren"),
closing="Een uitgevulde alinea kan kiezen hoe haar laatste regel staat: deze vult alle andere regels van rand tot rand en zet de laatste rechts uitgelijnd.",
second_title="Opvultekens en regelhoogte",
contents_intro="Een inhoudsopgave: puntjes leiden van elke titel naar het paginanummer, in de grootte van de titel die ze volgen.",
contents=("Stijlen binnen een alinea", "Lijnen, contouren en kleur", "Tabstops en opvultekens"),
line_height_intro="Twee keer dezelfde drie regels. Links is elke regel zo hoog als het grootste bedrag erop, rechts zo hoog als de omschrijving waarmee hij begint.",
labels=("Goederen", "Levering", "Te betalen"),
)
# 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.",
lined_up="Preços em dois estilos, alinhados pelo ponto decimal:",
priced=("Encadernação", "Capa, duas cores"),
closing="Um parágrafo justificado pode escolher como fica a sua última linha: este enche todas as outras de margem a margem e encosta a última à margem direita.",
second_title="Caracteres de preenchimento e altura da linha",
contents_intro="Um índice: os pontos levam de cada título ao seu número de página, no tamanho do título que prolongam.",
contents=("Estilos dentro de um parágrafo", "Filetes, contornos e cor", "Tabulações e caracteres de preenchimento"),
line_height_intro="As mesmas três linhas, duas vezes. À esquerda, cada linha é tão alta como o maior montante que leva; à direita, como a designação com que começa.",
labels=("Mercadorias", "Entrega", "Montante em dívida"),
)
# 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.",
lined_up="Prezzi in due stili, allineati sul punto decimale:",
priced=("Rilegatura", "Copertina, due colori"),
closing="Un paragrafo giustificato può scegliere come disporre l’ultima riga: questo riempie tutte le altre da un margine all’altro e manda l’ultima contro il margine destro.",
second_title="Caratteri di riempimento e altezza di riga",
contents_intro="Un indice: i puntini guidano da ogni titolo al suo numero di pagina, nel corpo del titolo che seguono.",
contents=("Stili all’interno di un paragrafo", "Filetti, contorni e colore", "Tabulazioni e caratteri di riempimento"),
line_height_intro="Le stesse tre righe, due volte. A sinistra ogni riga è alta quanto l’importo più grande che porta; a destra, quanto la voce con cui si apre.",
labels=("Merci", "Consegna", "Importo dovuto"),
)
# 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.",
lined_up="Precios en dos estilos, alineados en su punto decimal:",
priced=("Encuadernación", "Cubierta, dos colores"),
closing="Un párrafo justificado puede elegir cómo se coloca su última línea: este llena todas las demás de borde a borde y envía la última contra el margen derecho.",
second_title="Caracteres de relleno y altura de línea",
contents_intro="Un índice: los puntos guían de cada título a su número de página, al tamaño del título al que siguen.",
contents=("Estilos dentro de un párrafo", "Filetes, contornos y color", "Tabuladores y caracteres de relleno"),
line_height_intro="Las mismas tres líneas, dos veces. A la izquierda, cada línea mide lo que el mayor importe que lleva; a la derecha, lo que la etiqueta con que empieza.",
labels=("Mercancías", "Envío", "Importe a pagar"),
)
# 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.",
lined_up="Preise in zwei Stilen, an ihrem Dezimalpunkt ausgerichtet:",
priced=("Bindung", "Umschlag, zweifarbig"),
closing="Ein Absatz im Blocksatz kann wählen, wie seine letzte Zeile steht: Dieser füllt alle übrigen Zeilen bis an beide Ränder und setzt die letzte rechtsbündig.",
second_title="Füllpunkte und Zeilenhöhe",
contents_intro="Ein Inhaltsverzeichnis: Von jedem Titel führen Füllpunkte zu seiner Seitenzahl. Die Punkte haben die Schriftgröße des Titels, hinter dem sie stehen.",
contents=("Schriftstile innerhalb eines Absatzes", "Linien, Konturen und Farbe", "Tabstopps und Füllpunkte"),
line_height_intro="Dieselben drei Zeilen zweimal. Links ist jede Zeile so hoch wie der Betrag in der größten Schrift, rechts so hoch wie die Bezeichnung am Zeilenanfang.",
labels=("Warenwert", "Versand", "Zahlbetrag"),
)
# 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 settings(content, font, words, top) -> None:
"""Set the prices lined up on their decimal points from `top` down, and under them
the justified paragraph whose closing line goes flush right."""
regular = hqf_pdf.Style(font, 11.0)
price = hqf_pdf.Style(font, 13.0, color=hqf_pdf.Rgb(0.0, 0.35, 0.7))
over = hqf_pdf.RichText().span(words.lined_up, regular)
lines = over.break_lines(WIDTH)
over.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP / 4.0
prices = (
hqf_pdf.RichText(
tab_method=hqf_pdf.TabMethod.Ruler,
tab_ruler=[PRICE_STOP],
tab_alignments=[hqf_pdf.TabAlign.Decimal],
)
.span(words.priced[0], regular)
.span("\t", regular)
.span(PRICES[0], price)
.span("\n", regular)
.span(words.priced[1], regular)
.span("\t", regular)
.span(PRICES[1], price)
)
lines = prices.break_lines(WIDTH)
prices.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP / 2.0
closing = hqf_pdf.RichText(
align=hqf_pdf.Align.Justify, last_align=hqf_pdf.Align.Right
).span(words.closing, regular)
lines = closing.break_lines(WIDTH)
closing.draw(content, lines, LEFT, top, WIDTH)
def leaders(content, font, words) -> None:
"""Set the second page under its heading: a table of contents whose dots lead from
each title to its page number, and the same three lines of figures twice, as tall
as their largest style on the left and as the style each opens in on the right."""
regular = hqf_pdf.Style(font, 11.0)
chapter = hqf_pdf.Style(font, 12.0)
section = hqf_pdf.Style(font, 10.0)
number = hqf_pdf.Style(font, 10.0, color=hqf_pdf.Rgb(0.0, 0.35, 0.7))
top = TOP
over = hqf_pdf.RichText().span(words.contents_intro, regular)
lines = over.break_lines(WIDTH)
over.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP / 4.0
# Each break is set in the smallest style, so that it makes no line taller whichever
# line it is counted on.
contents = (
hqf_pdf.RichText(
tab_method=hqf_pdf.TabMethod.Ruler,
tab_ruler=[WIDTH],
tab_alignments=[hqf_pdf.TabAlign.Right],
leader=".",
)
.span(words.contents[0], chapter)
.span("\t", chapter)
.span(PAGES[0], number)
.span("\n", section)
.span(words.contents[1], section)
.span("\t", section)
.span(PAGES[1], number)
.span("\n", section)
.span(words.contents[2], chapter)
.span("\t", chapter)
.span(PAGES[2], number)
)
lines = contents.break_lines(WIDTH)
contents.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP
over = hqf_pdf.RichText().span(words.line_height_intro, regular)
lines = over.break_lines(WIDTH)
over.draw(content, lines, LEFT, top, WIDTH)
top -= hqf_pdf.RichText.height(lines) + GAP / 2.0
by_tallest = figures(font, words, hqf_pdf.LeadingRule.Tallest)
lines = by_tallest.break_lines(COLUMN)
by_tallest.draw(content, lines, LEFT, top, COLUMN)
by_first = figures(font, words, hqf_pdf.LeadingRule.First)
lines = by_first.break_lines(COLUMN)
by_first.draw(content, lines, LEFT + WIDTH - COLUMN, top, COLUMN)
def figures(font, words, rule) -> hqf_pdf.RichText:
"""The three labels, each with its amount set larger and flush with the column's
right edge, every line as tall as `rule` says. The first baseline sits as far below
the top as the tallest ascender rises, whichever rule is set, so that two columns
drawn from the same top start on the same line."""
label = hqf_pdf.Style(font, 10.0)
figure = hqf_pdf.Style(font, 15.0, color=hqf_pdf.Rgb(0.0, 0.35, 0.7))
return (
hqf_pdf.RichText(
tab_method=hqf_pdf.TabMethod.Ruler,
tab_ruler=[COLUMN],
tab_alignments=[hqf_pdf.TabAlign.Right],
first_baseline=hqf_pdf.FirstBaseline.ascender(),
line_height=rule,
)
.span(words.labels[0], label)
.span("\t", label)
.span(FIGURES[0], figure)
.span("\n", label)
.span(words.labels[1], label)
.span("\t", label)
.span(FIGURES[1], figure)
.span("\n", label)
.span(words.labels[2], label)
.span("\t", label)
.span(FIGURES[2], figure)
)
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)
settings(content, font, words, top - GAP / 2.0)
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
second = hqf_pdf.Content()
second.draw_text(font, 14.0, LEFT, TOP + 24.0, words.second_title)
leaders(second, font, words)
page = hqf_pdf.Page.a4()
page.set_content(second)
document.add_page(page)
written = document.write(out)
print(f"wrote {out}: {written} bytes, {len(paragraphs)} blocks")
if __name__ == "__main__":
main()
|