write_tagged_structure.py

Die Python-Datei des Beispiels „Eine getaggte Anzeige, die sagt, was jeder Teil ist“. Eine Lieferanzeige, deren verborgene Struktur angibt, wo jedes Element steht, wofür eine Abkürzung steht und zu welchen Überschriften jede Tabellenzelle gehört, mit Kolumnentitel, Seitenzahl und Zeilennummern als Seitenbeiwerk markiert; dann jede Listennummerierung und jede Rolle, die ein Element erhalten kann.

Python 1212 Zeilen

Wofür dieses Beispiel da ist

Eine Person, die die Seite nicht sehen kann, hört sie von einem Screenreader vorgelesen, und der Screenreader kann nur sagen, was die Datei ihm mitteilt. Hier ist eine Anzeige einer Papierlieferung bis in ihren kleinsten Teil getaggt: Der Baum hinter der Seite sagt, wo jedes Element in der Zeile steht, wofür es da ist, wofür eine Abkürzung steht und unter welchen Spalten- und Zeilenüberschriften jede Zahl der Tabelle steht, auch dort, wo eine Überschrift mehrere Zeilen oder Spalten überspannt.

Was dieses Beispiel zeigt

   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
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
"""Writes a tagged notice whose structure tree says more than what each run is, and
whose furniture says what kind of furniture it is.

The Python twin of the `write_tagged_structure` example in Rust. The first page is the
notice. Its tree says where each element stands in the flow — a heading set as a block,
a word inline, a caption before the table, a label at the start of the lines, an aside
floated to their end — what an element is for in the web's vocabulary, what an
abbreviation stands for, and which header cells each cell of its table sits under, the
headers spanning rows and columns and each stating what it heads. Its furniture is
marked as furniture of every kind a page carries: a background, a watermark, a running
head, line numbers, a page number, a Bates number, a redaction and the marks a trimmer
cuts to. The running head carries its own facts on runs no element of the tree owns: an
abbreviation written out, a ligature read as its two letters, a tick drawn as a path
described in words, a phrase in another language.

The second page sets a list for each numbering a list can state, labelled the way that
numbering reads. The third names every role an element can be given, as the tree writes
it.

The file is written as PDF 2.0, which the placements, the roles and most of the kinds of
furniture belong to. It claims no standard.

One bookmark leads to the header cell over the two seasons, tied to the element by its
identifier rather than to a place on the page.

Every sentence is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set
is drawn. The names of the numberings and of the roles are not words: they are what the
file writes.

Usage: python examples/write_tagged_structure.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_tagged_structure.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 the text of the notice lines up on.
LEFT = 100.0

# How wide the text of the notice runs.
WIDTH = 330.0

# The size and the leading of the notice's running text.
BODY = (10.5, 15.0)

# The Bates number the first page carries; each page after it carries the next.
FIRST_BATES = 101

# What the table counts: paper in spring and in autumn, then ink.
COUNTS = (("120", "80"), ("15", "22"))

# Every numbering a list can state, and the two labels each one reads as.
NUMBERINGS = (
    (hqf_pdf.ListNumbering.NoNumbering, ("", "")),
    (hqf_pdf.ListNumbering.Unordered, ("–", "–")),
    (hqf_pdf.ListNumbering.Description, ("", "")),
    (hqf_pdf.ListNumbering.Disc, ("•", "•")),
    (hqf_pdf.ListNumbering.Circle, ("◦", "◦")),
    (hqf_pdf.ListNumbering.Square, ("▪", "▪")),
    (hqf_pdf.ListNumbering.Ordered, ("1)", "2)")),
    (hqf_pdf.ListNumbering.Decimal, ("1.", "2.")),
    (hqf_pdf.ListNumbering.UpperRoman, ("I.", "II.")),
    (hqf_pdf.ListNumbering.LowerRoman, ("i.", "ii.")),
    (hqf_pdf.ListNumbering.UpperAlpha, ("A.", "B.")),
    (hqf_pdf.ListNumbering.LowerAlpha, ("a.", "b.")),
)

# Every role an element of the tree can be given.
ROLES = (
    hqf_pdf.AriaRole.Alert,
    hqf_pdf.AriaRole.AlertDialog,
    hqf_pdf.AriaRole.Application,
    hqf_pdf.AriaRole.Article,
    hqf_pdf.AriaRole.Banner,
    hqf_pdf.AriaRole.Button,
    hqf_pdf.AriaRole.Cell,
    hqf_pdf.AriaRole.Checkbox,
    hqf_pdf.AriaRole.ColumnHeader,
    hqf_pdf.AriaRole.ComboBox,
    hqf_pdf.AriaRole.Complementary,
    hqf_pdf.AriaRole.ContentInfo,
    hqf_pdf.AriaRole.Definition,
    hqf_pdf.AriaRole.Dialog,
    hqf_pdf.AriaRole.Directory,
    hqf_pdf.AriaRole.Document,
    hqf_pdf.AriaRole.Feed,
    hqf_pdf.AriaRole.Figure,
    hqf_pdf.AriaRole.Form,
    hqf_pdf.AriaRole.Grid,
    hqf_pdf.AriaRole.GridCell,
    hqf_pdf.AriaRole.Group,
    hqf_pdf.AriaRole.Heading,
    hqf_pdf.AriaRole.Img,
    hqf_pdf.AriaRole.Link,
    hqf_pdf.AriaRole.List,
    hqf_pdf.AriaRole.ListBox,
    hqf_pdf.AriaRole.ListItem,
    hqf_pdf.AriaRole.Log,
    hqf_pdf.AriaRole.Main,
    hqf_pdf.AriaRole.Marquee,
    hqf_pdf.AriaRole.Math,
    hqf_pdf.AriaRole.Menu,
    hqf_pdf.AriaRole.MenuBar,
    hqf_pdf.AriaRole.MenuItem,
    hqf_pdf.AriaRole.MenuItemCheckbox,
    hqf_pdf.AriaRole.MenuItemRadio,
    hqf_pdf.AriaRole.Navigation,
    hqf_pdf.AriaRole.Note,
    hqf_pdf.AriaRole.Option,
    hqf_pdf.AriaRole.Presentation,
    hqf_pdf.AriaRole.ProgressBar,
    hqf_pdf.AriaRole.Radio,
    hqf_pdf.AriaRole.RadioGroup,
    hqf_pdf.AriaRole.Region,
    hqf_pdf.AriaRole.Row,
    hqf_pdf.AriaRole.RowGroup,
    hqf_pdf.AriaRole.RowHeader,
    hqf_pdf.AriaRole.ScrollBar,
    hqf_pdf.AriaRole.Search,
    hqf_pdf.AriaRole.SearchBox,
    hqf_pdf.AriaRole.Separator,
    hqf_pdf.AriaRole.Slider,
    hqf_pdf.AriaRole.SpinButton,
    hqf_pdf.AriaRole.Status,
    hqf_pdf.AriaRole.Switch,
    hqf_pdf.AriaRole.Tab,
    hqf_pdf.AriaRole.Table,
    hqf_pdf.AriaRole.TabList,
    hqf_pdf.AriaRole.TabPanel,
    hqf_pdf.AriaRole.Term,
    hqf_pdf.AriaRole.TextBox,
    hqf_pdf.AriaRole.Timer,
    hqf_pdf.AriaRole.ToolBar,
    hqf_pdf.AriaRole.ToolTip,
    hqf_pdf.AriaRole.Tree,
    hqf_pdf.AriaRole.TreeGrid,
    hqf_pdf.AriaRole.TreeItem,
    hqf_pdf.AriaRole.DocAbstract,
    hqf_pdf.AriaRole.DocAcknowledgments,
    hqf_pdf.AriaRole.DocAfterword,
    hqf_pdf.AriaRole.DocAppendix,
    hqf_pdf.AriaRole.DocBackLink,
    hqf_pdf.AriaRole.DocBiblioEntry,
    hqf_pdf.AriaRole.DocBibliography,
    hqf_pdf.AriaRole.DocBiblioRef,
    hqf_pdf.AriaRole.DocChapter,
    hqf_pdf.AriaRole.DocColophon,
    hqf_pdf.AriaRole.DocConclusion,
    hqf_pdf.AriaRole.DocCover,
    hqf_pdf.AriaRole.DocCredit,
    hqf_pdf.AriaRole.DocCredits,
    hqf_pdf.AriaRole.DocDedication,
    hqf_pdf.AriaRole.DocEndnote,
    hqf_pdf.AriaRole.DocEndnotes,
    hqf_pdf.AriaRole.DocEpigraph,
    hqf_pdf.AriaRole.DocEpilogue,
    hqf_pdf.AriaRole.DocErrata,
    hqf_pdf.AriaRole.DocExample,
    hqf_pdf.AriaRole.DocFootnote,
    hqf_pdf.AriaRole.DocForeword,
    hqf_pdf.AriaRole.DocGlossary,
    hqf_pdf.AriaRole.DocGlossRef,
    hqf_pdf.AriaRole.DocIndex,
    hqf_pdf.AriaRole.DocIntroduction,
    hqf_pdf.AriaRole.DocNoteRef,
    hqf_pdf.AriaRole.DocNotice,
    hqf_pdf.AriaRole.DocPageBreak,
    hqf_pdf.AriaRole.DocPageList,
    hqf_pdf.AriaRole.DocPart,
    hqf_pdf.AriaRole.DocPreface,
    hqf_pdf.AriaRole.DocPrologue,
    hqf_pdf.AriaRole.DocPullQuote,
    hqf_pdf.AriaRole.DocQna,
    hqf_pdf.AriaRole.DocSubtitle,
    hqf_pdf.AriaRole.DocTip,
    hqf_pdf.AriaRole.DocToc,
)


@dataclass(frozen=True)
class Words:
    """Every word the document draws, in one language.

    What is not language stays out of it: the counts in the table, the Bates numbers,
    the list labels, and the names of the numberings and of the roles.
    """

    # The language the tree declares the document is written in.
    lang: str
    # The notice's heading.
    title: str
    # The bookmark that leads to the heading over the seasons.
    bookmark: str
    # The paragraph under it, which the line numbers count.
    lead: str
    # The line that holds the abbreviation: what comes before it, the abbreviation, what
    # it stands for, and what comes after it.
    delivery: tuple[str, str, str, str]
    # The label set at the start of the lines, beside the aside.
    margin: str
    # The aside floated to the end of the lines.
    aside: str
    # The caption set before the table.
    caption: str
    # The table's header cells: the corner, the year, the two seasons.
    headers: tuple[str, str, str, str]
    # The table's two row headers.
    rows: tuple[str, str]
    # What stands before the redacted account number.
    account: str
    # The running head: the abbreviation, what it stands for, and the rest of the head's
    # title.
    head: tuple[str, str, str]
    # The word the ligature opens, after the ligature itself.
    ligature_rest: str
    # What the drawn tick is, in words.
    tick: str
    # A phrase in another language, and the code of that language.
    foreign: tuple[str, str]
    # The watermark across the first page.
    watermark: str
    # The page number, `{n}` standing for the page's own.
    page_number: str
    # The second page's title.
    lists_title: str
    # What an ordered list and an unordered one are called.
    ordered: tuple[str, str]
    # The two items every list holds.
    items: tuple[str, str]
    # What the description list's two terms mean.
    defined: tuple[str, str]
    # The third page's title, and the line under it.
    roles: tuple[str, str]


# The document in English.
ENGLISH = Words(
    lang="en",
    title="Notice of a paper delivery",
    bookmark="The deliveries, season by season",
    lead=(
        "This notice is a tagged document. The tree behind it says where each element "
        "stands, what it is for and what its abbreviations stand for, and every piece "
        "of furniture on the page says what kind of furniture it is, so that reading "
        "the notice aloud reads the notice and nothing else."
    ),
    delivery=(
        "Delivery in ",
        "approx.",
        "approximately",
        " three weeks.",
    ),
    margin="Note",
    aside="Prices hold until the end of the month.",
    caption="Quantities ordered, by season",
    headers=(
        "Item",
        "2026",
        "Spring",
        "Autumn",
    ),
    rows=(
        "Paper",
        "Ink",
    ),
    account="Account number:",
    head=(
        "Dept.",
        "Department",
        " of supplies ",
    ),
    ligature_rest="le 42",
    tick="A tick",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="COPY",
    page_number="Page {n} of 3",
    lists_title="The numbering a list can state",
    ordered=(
        "ordered",
        "unordered",
    ),
    items=(
        "Paper",
        "Ink",
    ),
    defined=(
        "sheets of 80 grams",
        "cartridges of one litre",
    ),
    roles=(
        "The roles an element can be given",
        (
            "Each name is written as the tree writes it, from the web's vocabulary and "
            "its publishing module."
        ),
    ),
)

# The document in French.
FRENCH = Words(
    lang="fr",
    title="Avis de livraison de papier",
    bookmark="Les livraisons, saison par saison",
    lead=(
        "Cet avis est un document balisé. L’arbre qui le décrit dit où se place chaque "
        "élément, à quoi il sert et ce que ses abréviations veulent dire, et chaque "
        "élément de décor de la page dit de quelle sorte il est : une lecture à voix "
        "haute restitue l’avis, et rien d’autre."
    ),
    delivery=(
        "Livraison sous ",
        "env.",
        "environ",
        " trois semaines.",
    ),
    margin="Note",
    aside="Les prix sont valables jusqu’à la fin du mois.",
    caption="Quantités commandées, par saison",
    headers=(
        "Article",
        "2026",
        "Printemps",
        "Automne",
    ),
    rows=(
        "Papier",
        "Encre",
    ),
    account="Numéro de compte :",
    head=(
        "Serv.",
        "Service",
        " des fournitures ",
    ),
    ligature_rest="chier 42",
    tick="Une coche",
    foreign=(
        "just in time",
        "en",
    ),
    watermark="COPIE",
    page_number="Page {n} sur 3",
    lists_title="La numérotation qu’une liste peut déclarer",
    ordered=(
        "ordonnée",
        "non ordonnée",
    ),
    items=(
        "Papier",
        "Encre",
    ),
    defined=(
        "feuilles de 80 grammes",
        "cartouches d’un litre",
    ),
    roles=(
        "Les rôles qu’un élément peut recevoir",
        (
            "Chaque nom est écrit comme l’arbre l’écrit, tiré du vocabulaire du web et "
            "de son module d’édition."
        ),
    ),
)

# The document in Dutch.
DUTCH = Words(
    lang="nl",
    title="Bericht van een papierlevering",
    bookmark="De leveringen, seizoen per seizoen",
    lead=(
        "Dit bericht is een getagd document. De boom erachter zegt waar elk element "
        "staat, waarvoor het dient en waar zijn afkortingen voor staan, en elk stuk "
        "meubilair op de pagina zegt wat voor meubilair het is, zodat het voorlezen "
        "van het bericht het bericht voorleest en niets anders."
    ),
    delivery=(
        "Levering over",
        "ong.",
        "ongeveer",
        " drie weken.",
    ),
    margin="Notitie",
    aside="De prijzen gelden tot het einde van de maand.",
    caption="Bestelde hoeveelheden, per seizoen",
    headers=(
        "Artikel",
        "2026",
        "Voorjaar",
        "Najaar",
    ),
    rows=(
        "Papier",
        "Inkt",
    ),
    account="Rekeningnummer:",
    head=(
        "Afd.",
        "Afdeling",
        " inkoop",
    ),
    ligature_rest="liaal 42",
    tick="Een vinkje",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="KOPIE",
    page_number="Pagina {n} van 3",
    lists_title="De nummering die een lijst kan noemen",
    ordered=(
        "genummerd",
        "ongenummerd",
    ),
    items=(
        "Papier",
        "Inkt",
    ),
    defined=(
        "vellen van 80 gram",
        "patronen van één liter",
    ),
    roles=(
        "De rollen die een element kan krijgen",
        (
            "Elke naam is geschreven zoals de boom hem schrijft, uit de woordenschat "
            "van het web en zijn publicatiemodule."
        ),
    ),
)

# The document in Portuguese.
PORTUGUESE = Words(
    lang="pt",
    title="Aviso de entrega de papel",
    bookmark="As entregas, estação a estação",
    lead=(
        "Este aviso é um documento etiquetado. A árvore por trás dele diz onde está "
        "cada elemento, para que serve e o que significam as suas abreviaturas, e "
        "cada peça de mobília da página diz que tipo de mobília é, para que ler o "
        "aviso em voz alta leia o aviso e nada mais."
    ),
    delivery=(
        "Entrega em",
        "aprox.",
        "aproximadamente",
        " três semanas.",
    ),
    margin="Nota",
    aside="Os preços mantêm-se até ao fim do mês.",
    caption="Quantidades encomendadas, por estação",
    headers=(
        "Artigo",
        "2026",
        "Primavera",
        "Outono",
    ),
    rows=(
        "Papel",
        "Tinta",
    ),
    account="Número de conta:",
    head=(
        "Serv.",
        "Serviço",
        " de fornecimentos",
    ),
    ligature_rest="lial 42",
    tick="Um visto",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="CÓPIA",
    page_number="Página {n} de 3",
    lists_title="A numeração que uma lista pode indicar",
    ordered=(
        "ordenada",
        "não ordenada",
    ),
    items=(
        "Papel",
        "Tinta",
    ),
    defined=(
        "folhas de 80 gramas",
        "cartuchos de um litro",
    ),
    roles=(
        "Os papéis que se podem dar a um elemento",
        (
            "Cada nome é escrito como a árvore o escreve, a partir do vocabulário da "
            "web e do seu módulo de publicação."
        ),
    ),
)

# The document in Italian.
ITALIAN = Words(
    lang="it",
    title="Avviso di consegna della carta",
    bookmark="Le consegne, stagione per stagione",
    lead=(
        "Questo avviso è un documento marcato. L’albero dietro di esso dice dove sta "
        "ogni elemento, a cosa serve e cosa significano le sue abbreviazioni, e ogni "
        "ornamento della pagina dice di che tipo è, così leggere l’avviso ad alta "
        "voce legge l’avviso e nient’altro."
    ),
    delivery=(
        "Consegna in",
        "circa",
        "approssimativamente",
        " tre settimane.",
    ),
    margin="Nota",
    aside="I prezzi valgono fino a fine mese.",
    caption="Quantità ordinate, per stagione",
    headers=(
        "Articolo",
        "2026",
        "Primavera",
        "Autunno",
    ),
    rows=(
        "Carta",
        "Inchiostro",
    ),
    account="Numero di conto:",
    head=(
        "Uff.",
        "Ufficio",
        " forniture",
    ),
    ligature_rest="liale 42",
    tick="Una spunta",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="COPIA",
    page_number="Pagina {n} di 3",
    lists_title="La numerazione che un elenco può indicare",
    ordered=(
        "ordinato",
        "non ordinato",
    ),
    items=(
        "Carta",
        "Inchiostro",
    ),
    defined=(
        "fogli da 80 grammi",
        "cartucce da un litro",
    ),
    roles=(
        "I ruoli che si possono dare a un elemento",
        (
            "Ogni nome è scritto come lo scrive l’albero, con il vocabolario del web "
            "e il suo modulo di pubblicazione."
        ),
    ),
)

# The document in Spanish.
SPANISH = Words(
    lang="es",
    title="Aviso de entrega de papel",
    bookmark="Las entregas, temporada a temporada",
    lead=(
        "Este aviso es un documento etiquetado. El árbol que tiene detrás dice dónde "
        "está cada elemento, para qué sirve y qué significan sus abreviaturas, y cada "
        "elemento decorativo de la página dice de qué tipo es, para que leer el aviso "
        "en voz alta lea el aviso y nada más."
    ),
    delivery=(
        "Entrega en",
        "aprox.",
        "aproximadamente",
        " tres semanas.",
    ),
    margin="Nota",
    aside="Los precios se mantienen hasta final de mes.",
    caption="Cantidades pedidas, por temporada",
    headers=(
        "Artículo",
        "2026",
        "Primavera",
        "Otoño",
    ),
    rows=(
        "Papel",
        "Tinta",
    ),
    account="Número de cuenta:",
    head=(
        "Serv.",
        "Servicio",
        " de suministros",
    ),
    ligature_rest="chero 42",
    tick="Una marca de verificación",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="COPIA",
    page_number="Página {n} de 3",
    lists_title="La numeración que puede indicar una lista",
    ordered=(
        "ordenada",
        "sin ordenar",
    ),
    items=(
        "Papel",
        "Tinta",
    ),
    defined=(
        "hojas de 80 gramos",
        "cartuchos de un litro",
    ),
    roles=(
        "Los papeles que puede recibir un elemento",
        (
            "Cada nombre se escribe como lo escribe el árbol, con el vocabulario de "
            "la web y su módulo de publicación."
        ),
    ),
)

# The document in German.
GERMAN = Words(
    lang="de",
    title="Mitteilung über eine Papierlieferung",
    bookmark="Die Lieferungen, Saison für Saison",
    lead=(
        "Diese Mitteilung ist ein getaggtes Dokument. Der Baum dahinter sagt, wo "
        "jedes Element steht, wozu es dient und wofür seine Abkürzungen stehen, und "
        "jedes Stück Beiwerk auf der Seite sagt, welche Art von Beiwerk es ist, "
        "sodass beim Vorlesen die Mitteilung vorgelesen wird und sonst nichts."
    ),
    delivery=(
        "Lieferung in ",
        "ca.",
        "circa",
        " drei Wochen.",
    ),
    margin="Hinweis",
    aside="Die Preise gelten bis Monatsende.",
    caption="Bestellte Mengen, nach Saison",
    headers=(
        "Artikel",
        "2026",
        "Frühjahr",
        "Herbst",
    ),
    rows=(
        "Papier",
        "Tinte",
    ),
    account="Kontonummer:",
    head=(
        "Abt.",
        "Abteilung",
        " Beschaffung ",
    ),
    ligature_rest="liale 42",
    tick="Ein Häkchen",
    foreign=(
        "à la carte",
        "fr",
    ),
    watermark="KOPIE",
    page_number="Seite {n} von 3",
    lists_title="Die Nummerierung, die eine Liste angeben kann",
    ordered=(
        "geordnet",
        "ungeordnet",
    ),
    items=(
        "Papier",
        "Tinte",
    ),
    defined=(
        "Bögen zu 80 Gramm",
        "Patronen zu einem Liter",
    ),
    roles=(
        "Die Rollen, die ein Element erhalten kann",
        (
            "Jeder Name ist so geschrieben, wie der Baum ihn schreibt, aus dem "
            "Vokabular des Webs und seinem Publikationsmodul."
        ),
    ),
)

# 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, font, size, at, line):
    """Draw one line of text with its baseline at `at`."""
    content.draw_text(font, size, at[0], at[1], line)


def tagged(content, font, tag, mcid, at, line):
    """Draw one line of text as a run of content numbered `mcid` under `tag`."""
    content.begin_tagged(tag, mcid)
    text(content, font, BODY[0], at, line)
    content.end_marked()


def furniture(content, font, words, index):
    """Draw the furniture every page carries: a background, the running head, the
    trimmer's marks, the page number and the Bates number.

    The running head holds four runs that carry facts of their own rather than facts an
    element of the tree gives them.
    """
    page = hqf_pdf.Rect(0.0, 0.0, 595.0, 842.0)
    every_edge = [
        hqf_pdf.PageEdge.Top,
        hqf_pdf.PageEdge.Bottom,
        hqf_pdf.PageEdge.Left,
        hqf_pdf.PageEdge.Right,
    ]

    content.begin_artifact_placed(
        hqf_pdf.Artifact.Background, attached=every_edge, bbox=page
    )
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.99, 0.98, 0.95))
    content.rect(20.0, 20.0, 555.0, 802.0)
    content.fill()
    content.restore_state()
    content.end_marked()

    # The running head: a rule, and a line of runs each carrying its facts.
    content.begin_artifact_placed(
        hqf_pdf.Artifact.Pagination,
        attached=[hqf_pdf.PageEdge.Top],
        bbox=hqf_pdf.Rect(LEFT, 790.0, 395.0, 16.0),
    )
    content.rect(LEFT, 788.0, 395.0, 0.5)
    content.fill()
    size = 8.0
    x = LEFT
    pieces = (
        ({"expansion": words.head[1]}, words.head[0]),
        ({}, words.head[2]),
        ({"actual_text": "fi"}, "fi"),
    )
    for facts, piece in pieces:
        content.begin_described(**facts)
        text(content, font, size, (x, 794.0), piece)
        content.end_marked()
        x += font.measure(piece, size)
    text(content, font, size, (x, 794.0), words.ligature_rest)
    x += font.measure(words.ligature_rest, size) + 12.0

    # A tick drawn as two strokes, which no font says: its facts say what it is.
    content.begin_described(alternate=words.tick)
    content.save_state()
    content.set_line_width(1.2)
    content.move_to(x, 797.0)
    content.line_to(x + 3.0, 794.0)
    content.line_to(x + 9.0, 801.0)
    content.stroke()
    content.restore_state()
    content.end_marked()
    x += 22.0

    content.begin_described(language=words.foreign[1])
    text(content, font, size, (x, 794.0), words.foreign[0])
    content.end_marked()
    content.end_marked()

    # The marks a trimmer cuts to, marked as belonging to the sheet rather than to the
    # page's content, and grouped under a tag of their own.
    content.begin_artifact(hqf_pdf.Artifact.Page)
    content.begin_marked("TrimMarks")
    content.save_state()
    content.set_line_width(0.3)
    for mark_x, mark_y, dx, dy in (
        (10.0, 20.0, 8.0, 0.0),
        (20.0, 10.0, 0.0, 8.0),
        (577.0, 20.0, 8.0, 0.0),
        (575.0, 10.0, 0.0, 8.0),
        (10.0, 822.0, 8.0, 0.0),
        (20.0, 824.0, 0.0, 8.0),
        (577.0, 822.0, 8.0, 0.0),
        (575.0, 824.0, 0.0, 8.0),
    ):
        content.move_to(mark_x, mark_y)
        content.line_to(mark_x + dx, mark_y + dy)
        content.stroke()
    content.restore_state()
    content.end_marked()
    content.end_marked()

    number = words.page_number.replace("{n}", str(index + 1))
    content.begin_artifact_placed(
        hqf_pdf.Artifact.PageNumber, attached=[hqf_pdf.PageEdge.Bottom]
    )
    text(content, font, size, (270.0, 40.0), number)
    content.end_marked()

    bates = FIRST_BATES + index
    content.begin_artifact_placed(
        hqf_pdf.Artifact.Bates,
        attached=[hqf_pdf.PageEdge.Bottom, hqf_pdf.PageEdge.Right],
        bbox=hqf_pdf.Rect(470.0, 36.0, 80.0, 12.0),
    )
    text(content, font, size, (470.0, 40.0), f"HQF-{bates:06d}")
    content.end_marked()


def notice(content, font, words):
    """Draw the notice, and hand back the branch of the tree describing it."""
    marks = hqf_pdf.Marks()
    children = []

    # The watermark across the page.
    content.begin_artifact(hqf_pdf.Artifact.Watermark)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.9))
    content.rotate(0.6, 297.5, 421.0)
    text(content, font, 110.0, (110.0, 380.0), words.watermark)
    content.restore_state()
    content.end_marked()

    mcid = marks.next_id()
    content.begin_tagged("H1", mcid)
    text(content, font, 18.0, (LEFT, 740.0), words.title)
    content.end_marked()
    children.append(
        hqf_pdf.StructElement(
            "H1", placement=hqf_pdf.Placement.Block, children=[(0, mcid)]
        )
    )

    # The paragraph the line numbers count, one run for the whole of it. Its first
    # baseline stands one leading under the top, where the numbers beside it start.
    flow = hqf_pdf.TextFlow(
        font,
        BODY[0],
        leading=BODY[1],
        first_baseline=hqf_pdf.FirstBaseline.leading(),
    )
    lines = flow.break_lines(words.lead, WIDTH)
    mcid = marks.next_id()
    content.begin_tagged("P", mcid)
    flow.draw(content, lines, LEFT, 712.0, WIDTH)
    content.end_marked()
    children.append(hqf_pdf.StructElement("P", children=[(0, mcid)]))

    content.begin_artifact_placed(
        hqf_pdf.Artifact.LineNumber, attached=[hqf_pdf.PageEdge.Left]
    )
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.5))
    baseline = 712.0 - BODY[1]
    for number in range(1, len(lines) + 1):
        text(content, font, 7.0, (70.0, baseline), str(number))
        baseline -= BODY[1]
    content.restore_state()
    content.end_marked()

    # The line holding the abbreviation, the abbreviation an element of its own, set
    # inline, that says what it stands for.
    top = baseline - 10.0
    before, short, long, after = words.delivery
    first = marks.next_id()
    tagged(content, font, "P", first, (LEFT, top), before)
    x = LEFT + font.measure(before, BODY[0])
    abbreviation = marks.next_id()
    tagged(content, font, "Span", abbreviation, (x, top), short)
    x += font.measure(short, BODY[0])
    last = marks.next_id()
    tagged(content, font, "P", last, (x, top), after)
    children.append(
        hqf_pdf.StructElement(
            "P",
            children=[
                (0, first),
                hqf_pdf.StructElement(
                    "Span",
                    placement=hqf_pdf.Placement.Inline,
                    expansion=long,
                    children=[(0, abbreviation)],
                ),
                (0, last),
            ],
        )
    )

    # A label at the start of the lines and an aside at their end, both at the height of
    # the account line.
    account_at = top - 30.0
    mcid = marks.next_id()
    content.begin_tagged("Note", mcid)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    text(content, font, 8.0, (40.0, account_at), words.margin)
    content.restore_state()
    content.end_marked()
    children.append(
        hqf_pdf.StructElement(
            "Note",
            placement=hqf_pdf.Placement.Start,
            aria_role=hqf_pdf.AriaRole.Note,
            children=[(0, mcid)],
        )
    )

    mcid = marks.next_id()
    content.begin_tagged("Aside", mcid)
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.6))
    content.set_line_width(0.5)
    content.rect(450.0, account_at - 30.0, 110.0, 44.0)
    content.stroke()
    aside = hqf_pdf.TextFlow(font, 8.0, leading=11.0)
    aside_lines = aside.break_lines(words.aside, 100.0)
    aside.draw(content, aside_lines, 455.0, account_at, 100.0)
    content.restore_state()
    content.end_marked()
    children.append(
        hqf_pdf.StructElement(
            "Aside",
            placement=hqf_pdf.Placement.End,
            aria_role=hqf_pdf.AriaRole.Complementary,
            children=[(0, mcid)],
        )
    )

    # The account number, removed: what is left of it is a black box.
    mcid = marks.next_id()
    tagged(content, font, "P", mcid, (LEFT, account_at), words.account)
    children.append(hqf_pdf.StructElement("P", children=[(0, mcid)]))
    x = LEFT + font.measure(words.account, BODY[0]) + 6.0
    content.begin_artifact_placed(
        hqf_pdf.Artifact.Redaction,
        attached=[],
        bbox=hqf_pdf.Rect(x, account_at - 3.0, 120.0, 13.0),
    )
    content.rect(x, account_at - 3.0, 120.0, 13.0)
    content.fill()
    content.end_marked()

    # The caption before the table, then the table itself.
    caption_at = account_at - 60.0
    mcid = marks.next_id()
    tagged(content, font, "Caption", mcid, (LEFT, caption_at), words.caption)
    caption = hqf_pdf.StructElement(
        "Caption", placement=hqf_pdf.Placement.Before, children=[(0, mcid)]
    )
    drawn = table(content, font, words, marks, caption_at - 20.0)
    children += [caption, drawn]
    return hqf_pdf.StructElement(
        "Sect", aria_role=hqf_pdf.AriaRole.Main, children=children
    )


def table(content, font, words, marks, top):
    """Draw the table under `top`: a corner heading both its row and its column of
    headers, a year spanning two seasons, and two rows each under its own header.
    Every data cell names the headers it sits under."""
    columns = (LEFT, LEFT + 110.0, LEFT + 190.0, LEFT + 270.0)
    row_height = 20.0
    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.6))
    content.set_line_width(0.5)
    content.rect(
        LEFT - 4.0, top - 4.0 * row_height + 14.0, 270.0 + 80.0, 4.0 * row_height
    )
    content.stroke()
    content.restore_state()

    corner, year, spring, autumn = words.headers

    def cell(tag, at, line):
        mcid = marks.next_id()
        tagged(content, font, tag, mcid, at, line)
        return mcid

    corner_id = cell("TH", (columns[0], top), corner)
    year_id = cell("TH", (columns[1], top), year)
    spring_id = cell("TH", (columns[1], top - row_height), spring)
    autumn_id = cell("TH", (columns[2], top - row_height), autumn)
    header = hqf_pdf.StructElement(
        "THead",
        children=[
            hqf_pdf.StructElement(
                "TR",
                children=[
                    hqf_pdf.StructElement(
                        "TH",
                        id="corner",
                        scope=hqf_pdf.Scope.Both,
                        row_span=2,
                        children=[(0, corner_id)],
                    ),
                    hqf_pdf.StructElement(
                        "TH",
                        id="year",
                        scope=hqf_pdf.Scope.Column,
                        col_span=2,
                        children=[(0, year_id)],
                    ),
                ],
            ),
            hqf_pdf.StructElement(
                "TR",
                children=[
                    hqf_pdf.StructElement(
                        "TH",
                        id="spring",
                        scope=hqf_pdf.Scope.Column,
                        headers=["year"],
                        children=[(0, spring_id)],
                    ),
                    hqf_pdf.StructElement(
                        "TH",
                        id="autumn",
                        scope=hqf_pdf.Scope.Column,
                        headers=["year"],
                        children=[(0, autumn_id)],
                    ),
                ],
            ),
        ],
    )

    rows = []
    y = top - 2.0 * row_height
    for index, (name, counts) in enumerate(zip(words.rows, COUNTS)):
        row_id = f"row{index}"
        name_id = cell("TH", (columns[0], y), name)
        cells = [
            hqf_pdf.StructElement(
                "TH",
                id=row_id,
                scope=hqf_pdf.Scope.Row,
                headers=["corner"],
                children=[(0, name_id)],
            )
        ]
        for count, column, season in zip(counts, columns[1:], ("spring", "autumn")):
            mcid = cell("TD", (column, y), count)
            cells.append(
                hqf_pdf.StructElement(
                    "TD", headers=[row_id, season, "year"], children=[(0, mcid)]
                )
            )
        rows.append(hqf_pdf.StructElement("TR", children=cells))
        y -= row_height
    return hqf_pdf.StructElement(
        "Table",
        aria_role=hqf_pdf.AriaRole.Table,
        children=[header, hqf_pdf.StructElement("TBody", children=rows)],
    )


def lists(content, font, words):
    """Draw a list for each numbering a list can state, and hand back the branch of
    the tree describing them."""
    marks = hqf_pdf.Marks()
    mcid = marks.next_id()
    content.begin_tagged("H1", mcid)
    text(content, font, 18.0, (LEFT, 740.0), words.lists_title)
    content.end_marked()
    children = [hqf_pdf.StructElement("H1", children=[(1, mcid)])]

    for place, (numbering, labels) in enumerate(NUMBERINGS):
        column = LEFT if place % 2 == 0 else LEFT + 210.0
        top = 700.0 - (place // 2) * 100.0
        kind = words.ordered[0] if numbering.is_ordered() else words.ordered[1]
        mcid = marks.next_id()
        tagged(
            content,
            font,
            "Caption",
            mcid,
            (column, top),
            f"{numbering.as_str()}, {kind}",
        )
        entries = [hqf_pdf.StructElement("Caption", children=[(1, mcid)])]
        y = top - 18.0
        for item, defined, label in zip(words.items, words.defined, labels):
            if numbering == hqf_pdf.ListNumbering.Description:
                term = marks.next_id()
                tagged(content, font, "Lbl", term, (column + 12.0, y), item)
                meaning = marks.next_id()
                tagged(content, font, "LBody", meaning, (column + 60.0, y), defined)
                parts = [
                    hqf_pdf.StructElement("Lbl", children=[(1, term)]),
                    hqf_pdf.StructElement("LBody", children=[(1, meaning)]),
                ]
            else:
                parts = []
                if label:
                    numbered = marks.next_id()
                    tagged(content, font, "Lbl", numbered, (column + 12.0, y), label)
                    parts.append(hqf_pdf.StructElement("Lbl", children=[(1, numbered)]))
                said = marks.next_id()
                tagged(content, font, "LBody", said, (column + 36.0, y), item)
                parts.append(hqf_pdf.StructElement("LBody", children=[(1, said)]))
            entries.append(hqf_pdf.StructElement("LI", children=parts))
            y -= 16.0
        children.append(
            hqf_pdf.StructElement("L", list_numbering=numbering, children=entries)
        )
    return hqf_pdf.StructElement("Sect", children=children)


def roles(content, font, words):
    """Name every role an element can be given, four columns of them, and hand back
    the branch of the tree describing the page."""
    marks = hqf_pdf.Marks()
    heading = marks.next_id()
    content.begin_tagged("H1", heading)
    text(content, font, 18.0, (LEFT, 740.0), words.roles[0])
    content.end_marked()
    lead = marks.next_id()
    content.begin_tagged("P", lead)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    flow = hqf_pdf.TextFlow(font, 9.0, leading=12.0)
    lines = flow.break_lines(words.roles[1], 420.0)
    flow.draw(content, lines, LEFT, 718.0, 420.0)
    content.restore_state()
    content.end_marked()

    entries = []
    per_column = (len(ROLES) + 3) // 4
    for place, role in enumerate(ROLES):
        x = 60.0 + (place // per_column) * 115.0
        y = 660.0 - (place % per_column) * 21.0
        mcid = marks.next_id()
        content.begin_tagged("LBody", mcid)
        text(content, font, 7.5, (x, y), role.as_str())
        content.end_marked()
        entries.append(
            hqf_pdf.StructElement(
                "LI", children=[hqf_pdf.StructElement("LBody", children=[(2, mcid)])]
            )
        )
    return hqf_pdf.StructElement(
        "Sect",
        children=[
            hqf_pdf.StructElement("H1", children=[(2, heading)]),
            hqf_pdf.StructElement("P", children=[(2, lead)]),
            hqf_pdf.StructElement(
                "L",
                list_numbering=hqf_pdf.ListNumbering.NoNumbering,
                children=entries,
            ),
        ],
    )


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("tagged_structure.pdf", language)).stem
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_version(hqf_pdf.Version.V2_0)
    document.set_info("Title", words.title)
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    branches = []
    for index, build in enumerate((notice, lists, roles)):
        content = hqf_pdf.Content()
        furniture(content, font, words, index)
        branches.append(build(content, font, words))
        page = hqf_pdf.Page.a4()
        page.set_content(content)
        document.add_page(page)
    document.set_structure(
        hqf_pdf.StructureTree(
            lang=words.lang,
            children=[hqf_pdf.StructElement("Document", children=branches)],
        )
    )
    # The bookmark leads to the element that heads the seasons, not to a spot on the
    # page: a reader follows the element wherever it is laid out.
    document.add_bookmark(hqf_pdf.Bookmark(words.bookmark, 0).tied_to("year"))

    written = document.write(out)
    print(f"wrote {out}: {written} bytes")


if __name__ == "__main__":
    main()