write_document_parts.py

Die Python-Datei des Beispiels „Drei Kontoauszüge in einer Datei“. Vier Seiten mit drei Kontoauszügen für Kunden. Jeder Auszug gibt die Seiten an, die zu ihm gehören, den Kunden, für den er bestimmt ist, die Zahl der zu druckenden Exemplare und die angehängte Datei, die zu ihm gehört.

Python 681 Zeilen

Wofür dieses Beispiel da ist

Eine Druckerei erhält ein PDF mit vier Seiten. Nichts darauf Gezeichnetes sagt, dass es drei Kundenauszüge statt eines langen enthält, noch dass dem ersten Kunden zwei Exemplare zustehen und dem dritten drei. Das kommt normalerweise in einem Job-Ticket neben der Datei, und an dem Tag, an dem Ticket und Datei nicht mehr übereinstimmen, landet der falsche Auszug im falschen Umschlag.

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
"""Writes three customer statements into one file, and says in the file where each of
them starts.

The Python twin of the `write_document_parts` example in Rust. A print shop that
receives a single PDF of four sheets has no way of knowing that it holds three
statements rather than one long one, nor how many copies each recipient is owed. That
is what a job ticket beside the file is usually for. Here the file says it itself: a
hierarchy of document parts, one part per statement, each claiming its own run of
pages, stating what a press needs to know about it, and carrying the data file that
belongs to it.

What a part states takes every kind of value a part can hold: text, a whole number, a
real number, a date, a yes or no, a list, and a set of fields of its own. A flag that
only steers the preview is set while the part is put together and taken out before it
is written.

The foot of every sheet is a link to the part of the file its statement is: clicked,
it leads to that statement's first sheet.

Both sets of words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
which set is drawn.

Usage: python examples/write_document_parts.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_document_parts.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


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

    # What the file as a whole is called.
    title: str
    # What the file carries, said once at the top of the first sheet.
    lead: str
    # What the hierarchy says, said in grey at the foot of the first sheet.
    note: str
    # The word a statement is called by.
    statement: str
    # The word a customer number is introduced by.
    customer: str
    # The word a sheet is counted by.
    sheet: str
    # Who each of the three statements is for.
    recipients: tuple[str, str, str]
    # Where each of them is sent.
    towns: tuple[str, str, str]
    # The country every recipient is in.
    country: str
    # The two column headings of a statement.
    columns: tuple[str, str]
    # What the three lines of a statement are called.
    lines: tuple[str, str, str]
    # The label on the total row.
    total: str
    # The heading of the terms sheet.
    terms_title: str
    # What the terms sheet says.
    terms: str
    # What the file carried beside each statement holds.
    carried: str


# The pages in English.
ENGLISH = Words(
    title="Three statements, one file",
    lead=(
        "The four sheets below are three statements, not one. Nothing drawn on them "
        "says where one recipient ends and the next begins — the file says it, beside "
        "the pages rather than on them, so a press can print and cut this run without "
        "a second file explaining it."
    ),
    note=(
        "Each part claims its own run of sheets, states the customer it is for and "
        "the number of copies owed, and carries the data file that belongs to it and "
        "to no other part. Reading software shows one document; a press reads three."
    ),
    statement="Statement",
    customer="Customer",
    sheet="Sheet",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="United Kingdom",
    columns=("Description", "Amount"),
    lines=(
        "Goods delivered in July",
        "Carriage, four crates",
        "Storage, one month",
    ),
    total="Total",
    terms_title="Terms of payment",
    terms=(
        "Payment falls due thirty days from the date this statement was posted. An "
        "amount still owing after that date carries interest at three times the legal "
        "rate, and a fixed sum of forty euros towards the cost of recovering it. "
        "Payment is made to the account named on the statement, quoting the customer "
        "number."
    ),
    carried="The statement as a data file",
)

# The pages in French.
FRENCH = Words(
    title="Trois relevés, un seul fichier",
    lead=(
        ("Les quatre feuillets ci-dessous forment trois relevés, et non un seul. Rien "
         "de ce qui y est imprimé ne dit où finit un destinataire et où commence le "
         "suivant : c’est le fichier qui le dit, à côté des pages et non sur elles, si"
         " bien qu’un imprimeur peut tirer et couper ce lot sans un second fichier "
         "pour le lui expliquer.")
    ),
    note=(
        ("Chaque partie délimite sa propre suite de feuillets, indique le client "
         "auquel elle est destinée et le nombre d’exemplaires dus, et contient le "
         "fichier de données qui n’appartient qu’à elle. Un logiciel de lecture "
         "affiche un document ; un imprimeur en lit trois.")
    ),
    statement="Relevé",
    customer="Client",
    sheet="Feuillet",
    recipients=(
        "Boulangerie Petit",
        "Menuiserie Vallon",
        "Laiterie du Coteau",
    ),
    towns=("Aix-en-Provence", "Annecy", "Quimper"),
    country="France",
    columns=("Désignation", "Montant"),
    lines=(
        "Marchandises livrées en juillet",
        "Transport, quatre caisses",
        "Entreposage, un mois",
    ),
    total="Total",
    terms_title="Conditions de règlement",
    terms=(
        ("Le règlement est exigible trente jours après la date d’envoi du présent "
         "relevé. Toute somme encore due passé cette date donne lieu à des intérêts au"
         " triple du taux légal, ainsi qu’à une indemnité forfaitaire de quarante "
         "euros pour frais de recouvrement. Le règlement s’effectue sur le compte "
         "indiqué sur le relevé, en rappelant le numéro de client.")
    ),
    carried="Le relevé sous forme de fichier de données",
)

# The pages in Dutch.
DUTCH = Words(
    title="Drie afschriften, één bestand",
    lead=(
        "De vier bladen hieronder zijn drie afschriften, niet één. Niets wat erop "
        "getekend is, zegt waar de ene ontvanger ophoudt en de volgende begint: het "
        "bestand zegt het, naast de pagina’s in plaats van erop, zodat een drukkerij "
        "deze oplage kan drukken en snijden zonder een tweede bestand dat het uitlegt."
    ),
    note=(
        "Elk deel omvat zijn eigen reeks bladen, zegt voor welke klant het is en "
        "hoeveel exemplaren er nodig zijn, en bevat het gegevensbestand dat bij dat "
        "deel hoort en bij geen ander. Leessoftware toont één document; een drukkerij "
        "leest er drie."
    ),
    statement="Afschrift",
    customer="Klant",
    sheet="Blad",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Verenigd Koninkrijk",
    columns=("Omschrijving", "Bedrag"),
    lines=(
        "Goederen geleverd in juli",
        "Vervoer, vier kratten",
        "Opslag, één maand",
    ),
    total="Totaal",
    terms_title="Betalingsvoorwaarden",
    terms=(
        "Betaling vervalt dertig dagen na de verzenddatum van dit afschrift. Over een "
        "bedrag dat daarna nog openstaat, is driemaal de wettelijke rente "
        "verschuldigd, plus een vast bedrag van veertig euro voor de "
        "invorderingskosten. Betalingen worden gedaan op de rekening die op het "
        "afschrift staat, onder vermelding van het klantnummer."
    ),
    carried="Het afschrift als gegevensbestand",
)

# The pages in Portuguese.
PORTUGUESE = Words(
    title="Três extratos, um ficheiro",
    lead=(
        "As quatro folhas abaixo são três extratos, não um. Nada do que nelas está "
        "desenhado diz onde acaba um destinatário e começa o seguinte: di-lo o "
        "ficheiro, ao lado das páginas e não nelas, por isso uma gráfica pode "
        "imprimir e cortar esta tiragem sem um segundo ficheiro que a explique."
    ),
    note=(
        "Cada parte reclama a sua série de folhas, diz a que cliente se destina e "
        "quantas cópias lhe são devidas, e leva o ficheiro de dados que lhe pertence "
        "a ela e a mais nenhuma. Um programa de leitura mostra um documento; uma "
        "gráfica lê três."
    ),
    statement="Extrato",
    customer="Cliente",
    sheet="Folha",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Reino Unido",
    columns=("Descrição", "Montante"),
    lines=(
        "Mercadoria entregue em julho",
        "Transporte, quatro caixas",
        "Armazenagem, um mês",
    ),
    total="Total",
    terms_title="Condições de pagamento",
    terms=(
        "O pagamento vence trinta dias após a data de envio deste extrato. Um "
        "montante ainda em dívida depois dessa data vence juros ao triplo da taxa "
        "legal, mais uma quantia fixa de quarenta euros pelos custos de cobrança. O "
        "pagamento faz-se para a conta indicada no extrato, citando o número de "
        "cliente."
    ),
    carried="O extrato como ficheiro de dados",
)

# The pages in Italian.
ITALIAN = Words(
    title="Tre estratti, un file",
    lead=(
        "I quattro fogli qui sotto sono tre estratti, non uno. Niente di disegnato su "
        "di essi dice dove finisce un destinatario e comincia il successivo: lo dice "
        "il file, accanto alle pagine e non sopra, così una tipografia può stampare e "
        "tagliare questa tiratura senza un secondo file che la spieghi."
    ),
    note=(
        "Ogni parte rivendica la propria serie di fogli, dice a quale cliente è "
        "destinata e quante copie gli spettano, e porta il file di dati che "
        "appartiene a lei e a nessun’altra. Un programma di lettura mostra un "
        "documento; una tipografia ne legge tre."
    ),
    statement="Estratto",
    customer="Cliente",
    sheet="Foglio",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Regno Unito",
    columns=("Descrizione", "Importo"),
    lines=(
        "Merce consegnata a luglio",
        "Trasporto, quattro casse",
        "Deposito, un mese",
    ),
    total="Totale",
    terms_title="Condizioni di pagamento",
    terms=(
        "Il pagamento scade trenta giorni dopo la data di invio di questo estratto. "
        "Un importo ancora dovuto dopo tale data produce interessi al triplo del "
        "tasso legale, più una somma fissa di quaranta euro per le spese di recupero. "
        "Il pagamento si fa sul conto indicato nell’estratto, citando il numero "
        "cliente."
    ),
    carried="L’estratto come file di dati",
)

# The pages in Spanish.
SPANISH = Words(
    title="Tres extractos, un archivo",
    lead=(
        "Las cuatro hojas de abajo son tres extractos, no uno. Nada de lo dibujado en "
        "ellas dice dónde acaba un destinatario y empieza el siguiente: lo dice el "
        "archivo, junto a las páginas y no en ellas, así que una imprenta puede "
        "imprimir y cortar esta tirada sin un segundo archivo que la explique."
    ),
    note=(
        "Cada parte reclama su propia serie de hojas, dice a qué cliente va y cuántas "
        "copias se le deben, y lleva el archivo de datos que le pertenece a ella y a "
        "ninguna otra. Un programa de lectura muestra un documento; una imprenta lee "
        "tres."
    ),
    statement="Extracto",
    customer="Cliente",
    sheet="Hoja",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Reino Unido",
    columns=("Descripción", "Importe"),
    lines=(
        "Mercancía entregada en julio",
        "Porte, cuatro cajas",
        "Almacenaje, un mes",
    ),
    total="Total",
    terms_title="Condiciones de pago",
    terms=(
        "El pago vence treinta días después de la fecha de envío de este extracto. Un "
        "importe aún debido tras esa fecha devenga intereses al triple del tipo "
        "legal, más una suma fija de cuarenta euros por los gastos de cobro. El pago "
        "se hace a la cuenta indicada en el extracto, citando el número de cliente."
    ),
    carried="El extracto como archivo de datos",
)

# The pages in German.
GERMAN = Words(
    title="Drei Kontoauszüge, eine Datei",
    lead=(
        "Die vier Blätter unten sind drei Kontoauszüge, nicht einer. Nichts darauf "
        "Gezeichnetes sagt, wo ein Empfänger endet und der nächste beginnt — das sagt "
        "die Datei, neben den Seiten statt auf ihnen, sodass eine Druckmaschine "
        "diesen Lauf drucken und schneiden kann, ohne dass eine zweite Datei ihn "
        "erklärt."
    ),
    note=(
        "Jeder Teil beansprucht seine eigene Blattfolge, nennt den Kunden, für den er "
        "bestimmt ist, und die Zahl der zu liefernden Exemplare, und trägt die "
        "Datendatei, die zu ihm und zu keinem anderen Teil gehört. Eine Lesesoftware "
        "zeigt ein Dokument; eine Druckmaschine liest drei."
    ),
    statement="Kontoauszug",
    customer="Kunde",
    sheet="Blatt",
    recipients=("Baker and Sons", "Halden Joinery", "Westmill Dairy"),
    towns=("Bristol", "Kendal", "Truro"),
    country="Vereinigtes Königreich",
    columns=("Beschreibung", "Betrag"),
    lines=(
        "Im Juli gelieferte Waren",
        "Fracht, vier Kisten",
        "Lagerung, ein Monat",
    ),
    total="Summe",
    terms_title="Zahlungsbedingungen",
    terms=(
        "Die Zahlung ist dreißig Tage nach dem Versanddatum dieses Kontoauszugs "
        "fällig. Ein danach noch offener Betrag wird mit dem Dreifachen des "
        "gesetzlichen Zinssatzes verzinst, zuzüglich einer Pauschale von vierzig Euro "
        "für die Kosten der Beitreibung. Die Zahlung erfolgt auf das auf dem "
        "Kontoauszug genannte Konto unter Angabe der Kundennummer."
    ),
    carried="Der Kontoauszug als Datendatei",
)

# 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 left edge of everything on the pages.
LEFT = 72.0

# How wide a block of text, and a statement, are.
WIDTH = 451.0

# The space that keeps an amount's thousands from being read as a new number.
NO_BREAK = " "

# The number each customer is known by.
NUMBERS = ("4711", "4712", "4713")

# How many copies of each statement the run owes.
COPIES = (2, 1, 3)

# What each statement's envelope weighs, in kilograms.
WEIGHTS = [0.12, 0.08, 0.16]

# When each statement was posted.
POSTED = (
    "2026-08-03T09:15:00+02:00",
    "2026-08-03T09:16:00+02:00",
    "2026-08-03T09:17:00+02:00",
)

# What each statement charges, line by line, in cents.
AMOUNTS = (
    (125_000, 9_600, 21_025),
    (48_050, 4_800, 21_025),
    (312_400, 15_200, 42_050),
)

# The sheets each statement claims: the first, and the one after the last. The first
# statement runs to two sheets, its terms following it; the other two are a sheet each.
RUNS = ((0, 2), (2, 3), (3, 4))


def money(cents: int) -> str:
    """An amount of cents, its thousands parted by a no-break space and its decimals
    by a point, which is how every language this example is written in writes one."""
    whole, fraction = divmod(cents, 100)
    digits = str(whole)
    out = []
    for index, digit in enumerate(digits):
        if index > 0 and (len(digits) - index) % 3 == 0:
            out.append(NO_BREAK)
        out.append(digit)
    return f"{''.join(out)}.{fraction:02d}{NO_BREAK}EUR"


def block(
    content: hqf_pdf.Content,
    handle: hqf_pdf.FontHandle,
    size: float,
    top: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    flow = hqf_pdf.TextFlow(handle, size)
    lines = flow.break_lines(text, WIDTH)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, LEFT, top, WIDTH)
    return top - flow.height(lines)


def charges(words: Words, text: hqf_pdf.FontHandle, index: int) -> hqf_pdf.Table:
    """The lines and total of one statement."""
    columns = hqf_pdf.Columns(
        [hqf_pdf.ColumnWidth.fraction(1.0), hqf_pdf.ColumnWidth.points(110.0)],
        WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    hairline = hqf_pdf.Stroke(0.5, color=hqf_pdf.Rgb.gray(0.6))
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.75))
    table.rule(hqf_pdf.Rule.horizontal_other(), hairline)
    table.rule(hqf_pdf.Rule.vertical(1), hairline)

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)
    shade = hqf_pdf.Rgb(0.93, 0.94, 0.97)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(text, 9.5, words.columns[0], padding=pad, fill=shade),
                hqf_pdf.Cell(
                    text,
                    9.5,
                    words.columns[1],
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    fill=shade,
                ),
            ],
            min_height=19.0,
        )
    )

    for label, amount in zip(words.lines, AMOUNTS[index]):
        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(text, 9.0, label, padding=pad),
                    hqf_pdf.Cell(
                        text,
                        9.0,
                        money(amount),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                    ),
                ],
                min_height=16.0,
            )
        )

    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(text, 9.5, words.total, padding=pad),
                hqf_pdf.Cell(
                    text,
                    9.5,
                    money(sum(AMOUNTS[index])),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                ),
            ],
            min_height=19.0,
        )
    )
    return table


def foot(
    content: hqf_pdf.Content,
    words: Words,
    text: hqf_pdf.FontHandle,
    index: int,
    sheet: int,
) -> None:
    """Draws the foot of a sheet: who it is for, and where it stands in its
    statement."""
    first, after = RUNS[index]
    flow = hqf_pdf.TextFlow(text, 8.0)
    line = (
        f"{words.statement} {index + 1}/{len(RUNS)} — {words.recipients[index]}"
        f" — {words.sheet} {sheet + 1}/{after - first}"
    )
    content.set_fill(hqf_pdf.Rgb.gray(0.45))
    flow.draw(content, flow.break_lines(line, WIDTH), LEFT, 56.0, WIDTH)
    content.set_fill(hqf_pdf.Rgb.gray(0.0))


def charge_sheet(words: Words, text: hqf_pdf.FontHandle, index: int) -> hqf_pdf.Content:
    """Draws the sheet a statement is charged on."""
    content = hqf_pdf.Content()
    top = 782.0

    if index == 0:
        top = block(content, text, 17.0, top, words.title) - 12.0
        top = block(content, text, 9.5, top, words.lead) - 26.0

    top = block(content, text, 13.0, top, words.recipients[index]) - 6.0
    whereabouts = (
        f"{words.customer} {NUMBERS[index]} —"
        f" {words.towns[index]}, {words.country}"
    )
    top = block(content, text, 9.0, top, whereabouts) - 20.0

    placed = charges(words, text, index).fit(LEFT, top, 120.0)
    placed.draw(content)

    if index == 0:
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        block(content, text, 8.5, placed.bottom - 26.0, words.note)
        content.set_fill(hqf_pdf.Rgb.gray(0.0))

    foot(content, words, text, index, 0)
    return content


def terms_sheet(words: Words, text: hqf_pdf.FontHandle) -> hqf_pdf.Content:
    """Draws the terms sheet that follows the first statement."""
    content = hqf_pdf.Content()
    top = block(content, text, 13.0, 782.0, words.terms_title) - 14.0
    block(content, text, 9.5, top, words.terms)
    foot(content, words, text, 0, 1)
    return content


def carried(words: Words, index: int) -> hqf_pdf.Attachment:
    """The data file carried beside one statement."""
    total = sum(AMOUNTS[index])
    return hqf_pdf.Attachment(
        f"statement-{NUMBERS[index]}.xml",
        words.carried,
        "text/xml",
        hqf_pdf.Relationship.Data,
        POSTED[index],
        f'<statement customer="{NUMBERS[index]}" total="{total}"/>\n'.encode(),
    )


def stated(words: Words, index: int) -> hqf_pdf.PartData:
    """What one statement states about itself, for whatever prints it: text, a whole
    number, a real one, a date, a yes or no, a list and a set of fields of its own.

    A proof flag steers the preview while the part is put together and is not for the
    press: it is taken out again before the part is written.
    """
    address = hqf_pdf.PartData(
        entries=[("Town", words.towns[index]), ("Country", words.country)]
    )
    data = hqf_pdf.PartData(
        entries=[
            ("Recipient", words.recipients[index]),
            ("CustomerNumber", NUMBERS[index]),
            ("Copies", COPIES[index]),
            ("Posted", hqf_pdf.PartValue.date(POSTED[index])),
            ("Address", address),
            ("Weight", WEIGHTS[index]),
            ("Tracked", index == 0),
            ("Enclosures", [f"statement-{NUMBERS[index]}.xml"]),
            ("Proof", True),
        ]
    )
    data.unset("Proof")
    return data


def copies_stated(words: Words) -> tuple[int, int]:
    """How many copies every statement stated comes to, read back from what each
    states, and how many statements state anything at all."""
    copies = 0
    stating = 0
    for index in range(len(RUNS)):
        data = stated(words, index)
        if not data.is_empty():
            stating += 1
        value = data.get("Copies")
        if value is not None:
            copies += value.value
    return copies, stating


def hierarchy(
    words: Words, files: list[hqf_pdf.AttachmentHandle]
) -> hqf_pdf.DocumentParts:
    """The hierarchy: one part per statement, under the part that is the whole run."""
    statements = [
        hqf_pdf.DocumentPart(
            pages=RUNS[index],
            data=stated(words, index),
            associated_files=[file],
        )
        for index, file in enumerate(files)
    ]
    return hqf_pdf.DocumentParts(
        hqf_pdf.DocumentPart(children=statements),
        node_names=["Run", "Statement"],
        record_level=1,
    )


def to_statement(index: int) -> hqf_pdf.Link:
    """The foot of a sheet of statement `index`, as a link leading to the part that
    claims the statement's first sheet."""
    first, __ = RUNS[index]
    return hqf_pdf.Link.acting(LEFT, 52.0, WIDTH, 12.0, hqf_pdf.Action.to_part(first))


def build(words: Words, font: Path) -> bytes:
    """Draws the four sheets and says which of them belong to which statement."""
    doc = hqf_pdf.Document()
    doc.set_license(_licence.licensed())
    # The hierarchy of document parts is written on PDF 2.0 and on nothing earlier.
    doc.set_version(hqf_pdf.Version.V2_0)
    text = doc.add_font(hqf_pdf.Font.from_path(font))

    files = [doc.attach(carried(words, index)) for index in range(len(RUNS))]

    first = hqf_pdf.Page.a4()
    first.set_content(charge_sheet(words, text, 0))
    first.add_link(to_statement(0))
    doc.add_page(first)

    second = hqf_pdf.Page.a4()
    second.set_content(terms_sheet(words, text))
    second.add_link(to_statement(0))
    doc.add_page(second)

    for index in range(1, len(RUNS)):
        sheet = hqf_pdf.Page.a4()
        sheet.set_content(charge_sheet(words, text, index))
        sheet.add_link(to_statement(index))
        doc.add_page(sheet)

    doc.set_document_parts(hierarchy(words, files))
    return doc.to_bytes()


def main() -> None:
    """Writes the four sheets."""
    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("document_parts.pdf", language)).stem
    )

    data = build(words, _out.font_path())

    Path(out).parent.mkdir(parents=True, exist_ok=True)
    Path(out).write_bytes(data)
    copies, stating = copies_stated(words)
    print(
        f"wrote {out}: {len(data)} bytes, {stating} statements asking for "
        f"{copies} copies"
    )


if __name__ == "__main__":
    main()