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 | """Writes a document whose pages link out of themselves and to each other.
The Python twin of the `write_links` example in Rust: the same document, through
the binding rather than through the library directly.
A link draws nothing, so nothing on the page proves it is there: only reading software
does, by following it. The first page carries a table of contents whose lines lead to
the pages after it, and an address that leaves the document; each of the pages after it
leads back. The navigation panel holds the same contents, and a last row that opens the
same address.
The chapter titles and the lines around them are held in `Words`, once per language,
and `HQF_PDF_LANG` picks which set is drawn. A chapter title is written once and read
twice: it is what the contents shows, and what the navigation panel shows.
Each chapter's page shows one side of a link. The first carries a link that covers two
lines and nothing between them, and one that goes to the contents by the name it is
filed under. The second carries five links, one per border a link can draw, each pressed
its own way, the border read back from the link, all on a layer of their own. The third
goes back to the contents eight times, each showing the page its own way, every link
carrying the same flags, read back beside them. The navigation panel sets the first
chapter before the others once they are listed, and ends on a separating line and a
bold blue italic row to the named contents.
Usage: python examples/write_links.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_links.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# The address the contents leaves the document by. It is not language.
ADDRESS = "https://example.org/hqf-pdf"
@dataclass(frozen=True)
class Words:
"""Every word the document draws and carries, in one language.
A chapter title is written once and read twice: the contents draws it, and the
navigation panel carries it. Both read the same field, so the two can never fall
out of step.
"""
# The line at the head of the contents, and the name its bookmark takes.
contents: str
# The line that says which text on the page can be clicked.
what_is_clickable: str
# The chapters the contents lists, in the order they are laid out.
chapters: tuple[str, str, str]
# The line each chapter page leads back by.
back: str
# The row of the navigation panel that opens the address.
online: str
# The title the document carries in its information dictionary.
document_title: str
# The two lines one link covers on the first chapter's page.
over: tuple[str, str]
# The line that reads back how many areas that link covers; `{n}` stands for the
# count.
covered: str
# The line leading back to the contents by the name it is filed under.
named: str
# The heading over the links of the second chapter's page.
borders: str
# What each style of border is called: solid, dashed, bevelled, inset, underlined.
styles: tuple[str, str, str, str, str]
# The heading over the links of the third chapter's page.
views: str
# How each of those links shows the contents page.
fits: tuple[str, ...]
# The line that reads back the flags those links carry; `{bits}` stands for them.
flags: str
# The name of the layer the second chapter's links belong to.
layer: str
# The line of the navigation panel that separates the chapters from the rest.
separator: str
# The document in English.
ENGLISH = Words(
contents="Contents",
what_is_clickable="Blue text is clickable; black text is not.",
chapters=(
"What a link is",
"What a link draws",
"Where a link goes",
),
back="Back to the contents",
online="The same, online",
document_title="A document that links to itself",
over=(
"One link covers this line",
"and this one, and nothing between them.",
),
covered="The link above covers {n} areas.",
named="Back to the contents, by the name it is filed under",
borders="Five borders a link can draw, each read back from the link:",
styles=(
"solid",
"dashed",
"bevelled",
"inset",
"underlined",
),
views="Back to the contents, the page shown eight ways:",
fits=(
"whole page",
"full width",
"full height",
"a rectangle",
"whole drawing",
"drawing width",
"drawing height",
"fixed place",
),
flags="Each of these links carries the flags {bits}.",
layer="Links",
separator="Elsewhere",
)
# The document in French.
FRENCH = Words(
contents="Sommaire",
what_is_clickable="Le texte bleu est cliquable, le noir ne l’est pas.",
chapters=(
"Ce qu’est un lien",
"Ce qu’un lien affiche",
"Où mène un lien",
),
back="Retour au sommaire",
online="La même chose, en ligne",
document_title="Un document qui renvoie à lui-même",
over=(
"Un même lien couvre cette ligne",
"et celle-ci, et rien entre elles.",
),
covered="Le lien ci-dessus couvre {n} zones.",
named="Retour au sommaire, par le nom sous lequel il est rangé",
borders="Cinq bordures qu’un lien peut tracer, chacune relue sur le lien :",
styles=(
"plein",
"tireté",
"biseauté",
"en creux",
"souligné",
),
views="Retour au sommaire, la page montrée de huit façons :",
fits=(
"page entière",
"pleine largeur",
"pleine hauteur",
"un rectangle",
"dessin entier",
"largeur du dessin",
"hauteur du dessin",
"position fixe",
),
flags="Chacun de ces liens porte les indicateurs {bits}.",
layer="Liens",
separator="Ailleurs",
)
# The document in Dutch.
DUTCH = Words(
contents="Inhoud",
what_is_clickable="Blauwe tekst is klikbaar; zwarte tekst niet.",
chapters=(
"Wat een link is",
"Wat een link tekent",
"Waar een link heen gaat",
),
back="Terug naar de inhoud",
online="Hetzelfde, online",
document_title="Een document dat naar zichzelf linkt",
over=(
"Eén link dekt deze regel",
"en deze, en niets ertussen.",
),
covered="De link hierboven dekt {n} gebieden.",
named="Terug naar de inhoud, via de naam waaronder die bewaard is",
borders="Vijf randen van een link, elk teruggelezen uit de link:",
styles=(
"doorgetrokken",
"gestreept",
"afgeschuind",
"verzonken",
"onderstreept",
),
views="Terug naar de inhoud, de pagina op acht manieren getoond:",
fits=(
"hele pagina",
"volle breedte",
"volle hoogte",
"een rechthoek",
"hele tekening",
"breedte van de tekening",
"hoogte van de tekening",
"vaste plek",
),
flags="Elk van deze links heeft de vlaggen {bits}.",
layer="Links",
separator="Elders",
)
# The document in Portuguese.
PORTUGUESE = Words(
contents="Índice",
what_is_clickable="O texto azul é clicável; o preto não.",
chapters=(
"O que é uma ligação",
"O que uma ligação desenha",
"Para onde vai uma ligação",
),
back="Voltar ao índice",
online="O mesmo, online",
document_title="Um documento que se liga a si próprio",
over=(
"Uma ligação cobre esta linha",
"e esta, e nada entre elas.",
),
covered="A ligação acima cobre {n} zonas.",
named="Voltar ao índice, pelo nome com que está arquivado",
borders="Cinco contornos de ligação, cada um relido da ligação:",
styles=(
"contínuo",
"tracejado",
"biselado",
"embutido",
"sublinhado",
),
views="Voltar ao índice, com a página mostrada de oito formas:",
fits=(
"página inteira",
"toda a largura",
"toda a altura",
"um retângulo",
"desenho inteiro",
"largura do desenho",
"altura do desenho",
"posição fixa",
),
flags="Cada uma destas ligações leva os indicadores {bits}.",
layer="Ligações",
separator="Noutro lado",
)
# The document in Italian.
ITALIAN = Words(
contents="Indice",
what_is_clickable="Il testo blu è cliccabile; quello nero no.",
chapters=(
"Che cos’è un collegamento",
"Che cosa disegna un collegamento",
"Dove porta un collegamento",
),
back="Torna all’indice",
online="Lo stesso, online",
document_title="Un documento che rimanda a sé stesso",
over=(
"Un collegamento copre questa riga",
"e questa, e niente in mezzo.",
),
covered="Il collegamento qui sopra copre {n} zone.",
named="Torna all’indice, col nome sotto cui è archiviato",
borders="Cinque bordi di link, ciascuno riletto dal link:",
styles=(
"continuo",
"tratteggiato",
"smussato",
"incassato",
"sottolineato",
),
views="Torna all’indice, con la pagina mostrata in otto modi:",
fits=(
"pagina intera",
"tutta la larghezza",
"tutta l’altezza",
"un rettangolo",
"disegno intero",
"larghezza del disegno",
"altezza del disegno",
"posizione fissa",
),
flags="Ognuno di questi collegamenti porta gli indicatori {bits}.",
layer="Collegamenti",
separator="Altrove",
)
# The document in Spanish.
SPANISH = Words(
contents="Índice",
what_is_clickable="El texto azul es clicable; el negro no.",
chapters=(
"Qué es un enlace",
"Qué dibuja un enlace",
"Adónde lleva un enlace",
),
back="Volver al índice",
online="Lo mismo, en línea",
document_title="Un documento que se enlaza a sí mismo",
over=(
"Un enlace cubre esta línea",
"y esta otra, y nada entre ellas.",
),
covered="El enlace de arriba cubre {n} zonas.",
named="Volver al índice, por el nombre con que está archivado",
borders="Cinco bordes de enlace, cada uno leído del enlace:",
styles=(
"continuo",
"discontinuo",
"biselado",
"hundido",
"subrayado",
),
views="Volver al índice, con la página mostrada de ocho formas:",
fits=(
"página entera",
"todo el ancho",
"toda la altura",
"un rectángulo",
"dibujo entero",
"ancho del dibujo",
"altura del dibujo",
"lugar fijo",
),
flags="Cada uno de estos enlaces lleva los indicadores {bits}.",
layer="Enlaces",
separator="En otro sitio",
)
# The document in German.
GERMAN = Words(
contents="Inhalt",
what_is_clickable="Blauer Text ist anklickbar; schwarzer Text nicht.",
chapters=(
"Was ein Link ist",
"Was ein Link zeichnet",
"Wohin ein Link führt",
),
back="Zurück zum Inhalt",
online="Dasselbe, online",
document_title="Ein Dokument, das auf sich selbst verweist",
over=(
"Ein Link deckt diese Zeile ab",
"und diese, und nichts dazwischen.",
),
covered="Der Link oben deckt {n} Bereiche ab.",
named="Zurück zum Inhalt, über ein benanntes Ziel",
borders="Fünf Linkrahmen, jeder aus dem Link zurückgelesen:",
styles=(
"durchgezogen",
"gestrichelt",
"abgeschrägt",
"vertieft",
"unterstrichen",
),
views="Zurück zum Inhalt, die Seite auf acht Arten gezeigt:",
fits=(
"ganze Seite",
"volle Breite",
"volle Höhe",
"ein Rechteck",
"ganze Zeichnung",
"Breite der Zeichnung",
"Höhe der Zeichnung",
"fester Ort",
),
flags="Jeder dieser Links trägt die Kennzeichen {bits}.",
layer="Links",
separator="Anderswo",
)
# 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}
# The size the contents and the chapter titles are set at.
SIZE = 14.0
def contents_page(handle: hqf_pdf.FontHandle, words: Words) -> hqf_pdf.Page:
"""The contents: one clickable line per chapter, and an address that leaves."""
content = hqf_pdf.Content()
page = hqf_pdf.Page.a4()
content.draw_text(handle, 20.0, 72.0, 760.0, words.contents)
# A black line that is not a link, beside the blue lines that are.
content.draw_text(handle, 10.0, 72.0, 735.0, words.what_is_clickable)
top = 700.0
for index, chapter in enumerate(words.chapters):
line = f"{index + 1}. {chapter}"
content.set_fill(hqf_pdf.Rgb(0.0, 0.2, 0.8))
content.draw_text(handle, SIZE, 72.0, top, line)
content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
# Chapter one is the page after this one, which is index 1.
page.add_link(
hqf_pdf.Link.to_page(72.0, top - 3.0, handle.measure(line, SIZE), SIZE, index + 1)
)
top -= SIZE * 2.0
content.set_fill(hqf_pdf.Rgb(0.0, 0.2, 0.8))
content.draw_text(handle, SIZE, 72.0, top - 20.0, ADDRESS)
content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
page.add_link(
hqf_pdf.Link.to_uri(72.0, top - 23.0, handle.measure(ADDRESS, SIZE), SIZE, ADDRESS)
)
page.set_content(content)
return page
def fits() -> list[hqf_pdf.PageFit]:
"""What each link of the third chapter's page shows the contents page as."""
return [
hqf_pdf.PageFit.whole_page(),
hqf_pdf.PageFit.full_width(780.0),
hqf_pdf.PageFit.full_height(72.0),
hqf_pdf.PageFit.rectangle(hqf_pdf.Rect(72.0, 600.0, 300.0, 180.0)),
hqf_pdf.PageFit.whole_drawing(),
hqf_pdf.PageFit.drawing_width(780.0),
hqf_pdf.PageFit.drawing_height(72.0),
hqf_pdf.PageFit.fixed(left=72.0, top=780.0, zoom=2.0),
]
def style_name(words: Words, style) -> str:
"""The words a link's border is described by, from the style it reads back."""
styles = (
hqf_pdf.BorderStyle.Solid,
hqf_pdf.BorderStyle.Dashed,
hqf_pdf.BorderStyle.Beveled,
hqf_pdf.BorderStyle.Inset,
hqf_pdf.BorderStyle.Underline,
)
for known, name in zip(styles, words.styles):
if style == known:
return name
return words.styles[0]
@dataclass(frozen=True)
class Shown:
"""What the chapter pages share: the layer their bordered links sit on, and the
flags their shown links carry."""
# The layer the bordered links of the second chapter belong to.
layer: hqf_pdf.LayerHandle
# The flags every link of the third chapter carries.
flags: hqf_pdf.AnnotationFlags
def chapter_links(content, page, handle, words, index, shown) -> None:
"""What each chapter's page shows under its title: one link over two lines and
one to a name, five borders, or eight ways of showing the contents."""
blue = hqf_pdf.Rgb(0.0, 0.2, 0.8)
if index == 0:
content.set_fill(blue)
content.draw_text(handle, SIZE, 72.0, 640.0, words.over[0])
content.draw_text(handle, SIZE, 72.0, 620.0, words.over[1])
content.draw_text(handle, SIZE, 72.0, 560.0, words.named)
content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
first = handle.measure(words.over[0], SIZE)
second = handle.measure(words.over[1], SIZE)
link = (
hqf_pdf.Link.to_page(72.0, 617.0, max(first, second), 37.0, 0)
.over(
[
hqf_pdf.Rect(72.0, 637.0, first, SIZE).quad(),
hqf_pdf.Rect(72.0, 617.0, second, SIZE).quad(),
]
)
.description(words.back)
)
covered = len(link.areas)
page.add_link(link)
content.draw_text(
handle, 9.0, 72.0, 600.0, words.covered.replace("{n}", str(covered))
)
page.add_link(
hqf_pdf.Link.to_destination(
72.0, 557.0, handle.measure(words.named, SIZE), SIZE, "contents"
)
)
elif index == 1:
content.draw_text(handle, SIZE, 72.0, 650.0, words.borders)
dash = hqf_pdf.Dash.on_off(3.0, 2.0)
borders = (
(hqf_pdf.LinkBorder.solid(blue, 1.0), hqf_pdf.PressHighlight.None_),
(hqf_pdf.LinkBorder.dashed(blue, 1.0, dash), hqf_pdf.PressHighlight.Invert),
(hqf_pdf.LinkBorder.beveled(blue, 2.0), hqf_pdf.PressHighlight.Outline),
(hqf_pdf.LinkBorder.inset(blue, 2.0), hqf_pdf.PressHighlight.Push),
(hqf_pdf.LinkBorder.underline(blue, 1.5), hqf_pdf.PressHighlight.Invert),
)
top = 620.0
for border, highlight in borders:
lengths = (
[]
if border.dash is None
else [f"{length:.0f}" for length in border.dash.lengths]
)
pattern = f" [{' '.join(lengths)}]" if lengths else ""
values = " ".join(f"{value:.1f}" for value in border.color.to_components())
line = (
f"{style_name(words, border.style)}, {border.width:g} pt{pattern}, "
f"{values}"
)
content.draw_text(handle, 10.0, 80.0, top, line)
page.add_link(
hqf_pdf.Link.to_page(72.0, top - 6.0, 300.0, 20.0, 0)
.border(border)
.highlight(highlight)
.layer(shown.layer)
)
top -= 30.0
else:
content.draw_text(handle, SIZE, 72.0, 650.0, words.views)
top = 620.0
for view, fit in zip(fits(), words.fits):
content.set_fill(blue)
content.draw_text(handle, 10.0, 80.0, top, fit)
content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
page.add_link(
hqf_pdf.Link.to_page(72.0, top - 4.0, 200.0, 16.0, 0)
.view(view)
.flags(shown.flags)
)
top -= 24.0
line = words.flags.replace("{bits}", str(shown.flags.bits))
content.draw_text(handle, 9.0, 72.0, top - 10.0, line)
# A link nobody sees, printed nowhere and never shown, which reading software
# still lists.
page.add_link(
hqf_pdf.Link.to_page(500.0, 40.0, 20.0, 20.0, 0).flags(
hqf_pdf.AnnotationFlags.none()
.invisible()
.hidden()
.no_view()
.toggle_no_view()
)
)
def chapter_page(
handle: hqf_pdf.FontHandle, words: Words, index: int, shown: Shown
) -> hqf_pdf.Page:
"""A chapter page, with a line leading back to the contents."""
content = hqf_pdf.Content()
page = hqf_pdf.Page.a4()
content.draw_text(handle, 20.0, 72.0, 760.0, f"{index + 1}. {words.chapters[index]}")
content.set_fill(hqf_pdf.Rgb(0.0, 0.2, 0.8))
content.draw_text(handle, SIZE, 72.0, 700.0, words.back)
content.set_fill(hqf_pdf.Rgb(0.0, 0.0, 0.0))
page.add_link(
hqf_pdf.Link.to_page(72.0, 697.0, handle.measure(words.back, SIZE), SIZE, 0)
)
chapter_links(content, page, handle, words, index, shown)
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("links.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
document.set_info("Title", words.document_title)
handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
document.add_page(contents_page(handle, words))
shown = Shown(
layer=document.add_layer(hqf_pdf.Layer(words.layer)),
flags=hqf_pdf.AnnotationFlags.from_bits(4)
.no_zoom()
.no_rotate()
.read_only()
.locked()
.locked_contents(),
)
for index in range(len(words.chapters)):
document.add_page(chapter_page(handle, words, index, shown))
document.add_destination("contents", 0, hqf_pdf.PageFit.full_width(780.0))
# The same contents again, as the panel a reader navigates by: the first chapter set
# before the others once they are listed, a line that only separates, and the row to
# the named contents in bold blue italics.
document.add_bookmark(
hqf_pdf.Bookmark(
words.contents,
0,
children=[
hqf_pdf.Bookmark(f"{index + 1}. {chapter}", index + 1).view(
hqf_pdf.PageFit.full_width(780.0)
)
for index, chapter in enumerate(words.chapters)
if index > 0
],
is_open=True,
).child_at(
0,
hqf_pdf.Bookmark(f"1. {words.chapters[0]}", 1).view(
hqf_pdf.PageFit.whole_page()
),
)
)
document.add_bookmark(hqf_pdf.Bookmark.separator(words.separator))
document.add_bookmark(
hqf_pdf.Bookmark.named(words.named, "contents")
.color(hqf_pdf.Rgb(0.0, 0.2, 0.8))
.bold()
.italic()
)
document.add_bookmark(
hqf_pdf.Bookmark.acting(words.online, hqf_pdf.Action.to_uri(ADDRESS))
)
written = document.write(out)
print(f"wrote {out} ({written} bytes)")
if __name__ == "__main__":
main()
|