write_filled_frame.py

Die Python-Datei des Beispiels „Zwei Bestellungen, ein Rahmen, eine Unterkante“. Eine Bestellung mit vier Positionen und eine mit sieben, in Rahmen gleicher Höhe, beide an derselben Unterkante endend. Darunter zwei ungleich lange Notizen, deren Zeilen auseinandergerückt werden, bis jede den Fuß ihres Rahmens erreicht.

Python 672 Zeilen

Wofür dieses Beispiel da ist

Ein Block bedruckten Geschäftspapiers hat den Rahmen bereits auf dem Papier: einen Rahmen für die Positionen, eine Linie darunter, die Summe unter der Linie. Was in den Rahmen kommt, ist jedes Mal unterschiedlich lang. Eine Bestellung mit vier Positionen lässt eine Handbreit Weiß über der Linie, eine mit einem Dutzend füllt sie, sodass zwei Blätter vom selben Block wie zwei verschiedene Dokumente aussehen — und die übliche Antwort, die kurze mit leeren Zeilen aufzufüllen, ergibt eine Zeile, in die jemand nachträglich schreiben kann.

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
"""Prints two orders of unequal length side by side in frames of one height, and ends
both of them on the same bottom edge.

The Python twin of the `write_filled_frame` example in Rust. A pad of pre-printed
stationery has the frame already on the paper: a box for the lines, a rule under it,
and the total below that rule. What goes in the box is a different length every time.
Left alone, an order of four lines leaves a hand's breadth of white above the rule and
an order of seven fills it, and the pad looks like two different documents.

So the box is filled instead. The rows of the order share whatever room the frame has
left, in equal parts, once they have all been measured, and the last of them ends on
the bottom edge. The headings and the total are left exactly where the stationery puts
them.

The notes at the foot of the page do the same for words rather than rows: the lines of
each note are moved apart until they reach the bottom of their box, so two notes of
unequal length end on one line. A limit is given with the box, and a note far too short
for it keeps the spacing it came with rather than being stretched into a ladder.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The amounts are the same in both.

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

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# What the shorter order's lines cost, in euros.
SHORT_AMOUNTS = (420.0, 96.0, 158.0, 240.0)

# What the longer order's lines cost, in euros.
LONG_AMOUNTS = (180.0, 64.0, 112.0, 45.0, 320.0, 88.0, 150.0)


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

    title: str
    lead: str
    orders: str
    short_order: str
    long_order: str
    item: str
    amount: str
    short_items: tuple[str, ...]
    long_items: tuple[str, ...]
    total: str
    notes: str
    short_note: str
    long_note: str
    caveat: str


# The page in English.
ENGLISH = Words(
    title="Two orders, one frame, one bottom edge",
    lead=(
        "The two frames below are the same height, and the orders in them are not the "
        "same length. Each frame is filled: whatever room the lines leave is shared "
        "out among them in equal parts, once they have all been measured, so the last "
        "line of an order of four ends where the last line of an order of seven ends. "
        "The headings and the total stay where the stationery puts them, and only the "
        "billed lines grow."
    ),
    orders="Four lines and seven, ending together",
    short_order="Order 4412",
    long_order="Order 4413",
    item="Item",
    amount="Amount",
    short_items=("Site survey", "Cable, 40 m", "Wall boxes", "Fitting, one day"),
    long_items=(
        "Site survey",
        "Cable, 15 m",
        "Wall boxes",
        "Junction box",
        "Fitting, two days",
        "Cover plates",
        "Test and report",
    ),
    total="Total",
    notes="Two notes of unequal length, ending together",
    short_note=(
        "Goods stay ours until they are paid for in full. Anything found broken is to "
        "be written on the driver's sheet before it is signed, and told to us the same "
        "week. A pallet left with a neighbour is left at the buyer's own risk."
    ),
    long_note=(
        "Payment is due thirty days from the date of issue, by transfer to the account "
        "named at the foot of the invoice. A line queried in writing suspends nothing "
        "but the line itself, and the rest of the invoice falls due on the day it "
        "always did. Work already booked is held for a fortnight after that day and "
        "released afterwards."
    ),
    caveat=(
        "The lines of a note are moved apart, and nothing else: the room kept around a "
        "paragraph, the drop under the last line and the height of the words "
        "themselves stand where they are. A limit is given along with the box, so two "
        "lines in a tall box keep the spacing they came with rather than being "
        "stretched into a ladder."
    ),
)

# The page in French.
FRENCH = Words(
    title="Deux commandes, un seul cadre, un même bord inférieur",
    lead=(
        ("Les deux cadres ci-dessous ont la même hauteur, mais les commandes qu’ils "
         "contiennent n’ont pas la même longueur. Chaque cadre est rempli : la place "
         "que laissent les lignes est répartie entre elles à parts égales, une fois "
         "toutes mesurées, si bien que la dernière ligne d’une commande de quatre "
         "lignes finit au même niveau que celle d’une commande de sept. Les en-têtes "
         "et le total restent là où le modèle les place ; seules les lignes facturées "
         "s’agrandissent.")
    ),
    orders="Quatre lignes et sept, qui finissent ensemble",
    short_order="Commande 4412",
    long_order="Commande 4413",
    item="Poste",
    amount="Montant",
    short_items=(
        "Visite des lieux",
        "Câble, 40 m",
        "Boîtiers muraux",
        "Pose, une journée",
    ),
    long_items=(
        "Visite des lieux",
        "Câble, 15 m",
        "Boîtiers muraux",
        "Boîte de dérivation",
        "Pose, deux journées",
        "Plaques de finition",
        "Essais et rapport",
    ),
    total="Total",
    notes="Deux mentions de longueurs différentes, qui finissent ensemble",
    short_note=(
        ("La marchandise reste notre propriété jusqu’au paiement intégral. Tout "
         "élément trouvé cassé doit être inscrit sur la feuille du chauffeur avant "
         "signature, et nous être signalé dans la semaine. Une palette laissée chez un"
         " voisin l’est aux risques de l’acheteur.")
    ),
    long_note=(
        ("Le paiement est dû trente jours après la date d’émission, par virement au "
         "compte indiqué au bas de la facture. Une ligne contestée par écrit ne "
         "suspend que cette ligne ; le reste de la facture demeure exigible à la date "
         "prévue. Les travaux déjà planifiés restent réservés quinze jours après cette"
         " date, puis sont libérés.")
    ),
    caveat=(
        ("Seules les lignes d’une mention sont écartées : l’espace réservé autour d’un"
         " paragraphe, celui sous la dernière ligne et la hauteur des mots eux-mêmes "
         "ne bougent pas. Le cadre est donné avec une limite : deux lignes dans un "
         "grand cadre gardent ainsi leur interligne d’origine au lieu de s’étirer en "
         "échelle.")
    ),
)

# The page in Dutch.
DUTCH = Words(
    title="Twee bestellingen, één kader, één onderrand",
    lead=(
        "De twee kaders hieronder zijn even hoog, en de bestellingen erin zijn niet "
        "even lang. Elk kader wordt gevuld: de ruimte die de regels overlaten wordt "
        "in gelijke delen over de regels verdeeld, nadat ze allemaal gemeten zijn, "
        "dus de laatste regel van een bestelling van vier eindigt waar de laatste "
        "regel van een bestelling van zeven eindigt. De koppen en het totaal blijven "
        "waar het briefpapier ze zet, en alleen de gefactureerde regels groeien."
    ),
    orders="Vier regels en zeven, die samen eindigen",
    short_order="Bestelling 4412",
    long_order="Bestelling 4413",
    item="Artikel",
    amount="Bedrag",
    short_items=("Opname ter plaatse", "Kabel, 40 m", "Wanddozen", "Montage, één dag"),
    long_items=(
        "Opname ter plaatse",
        "Kabel, 15 m",
        "Wanddozen",
        "Aansluitdoos",
        "Montage, twee dagen",
        "Afdekplaten",
        "Test en rapport",
    ),
    total="Totaal",
    notes="Twee notities van ongelijke lengte, die samen eindigen",
    short_note=(
        "Goederen blijven van ons tot ze volledig betaald zijn. Wat kapot aankomt, "
        "wordt op het blad van de chauffeur genoteerd voordat het getekend wordt, en "
        "ons dezelfde week gemeld. Een pallet die bij de buren wordt achtergelaten, "
        "is voor risico van de koper."
    ),
    long_note=(
        "Betaling vervalt dertig dagen na de uitgiftedatum, per overschrijving naar "
        "de rekening onderaan de factuur. Een schriftelijk betwiste regel schort "
        "alleen die regel op, en de rest van de factuur vervalt op de gewone dag. Al "
        "geboekt werk blijft na die dag twee weken gereserveerd en komt daarna vrij."
    ),
    caveat=(
        "De regels van een notitie worden uit elkaar gezet, en verder niets: de "
        "ruimte rond een alinea, de ruimte onder de laatste regel en de hoogte van de "
        "woorden zelf blijven waar ze zijn. Samen met het kader wordt een grens "
        "gegeven, dus twee regels in een hoog kader houden hun regelafstand in plaats "
        "van tot een ladder uitgerekt te worden."
    ),
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Duas encomendas, uma moldura, uma mesma margem inferior",
    lead=(
        "As duas molduras abaixo têm a mesma altura, e as encomendas que contêm não "
        "têm o mesmo comprimento. Cada moldura é preenchida: o espaço que as linhas "
        "deixam reparte-se entre elas em partes iguais, depois de todas medidas, por "
        "isso a última linha de uma encomenda de quatro acaba onde acaba a última de "
        "uma encomenda de sete. Os títulos e o total ficam onde os põe o papel "
        "timbrado, e só crescem as linhas faturadas."
    ),
    orders="Quatro linhas e sete, a acabar juntas",
    short_order="Encomenda 4412",
    long_order="Encomenda 4413",
    item="Artigo",
    amount="Montante",
    short_items=("Visita técnica", "Cabo, 40 m", "Caixas de parede", "Montagem, um dia"),
    long_items=(
        "Visita técnica",
        "Cabo, 15 m",
        "Caixas de parede",
        "Caixa de derivação",
        "Montagem, dois dias",
        "Espelhos",
        "Ensaio e relatório",
    ),
    total="Total",
    notes="Duas notas de comprimento desigual, a acabar juntas",
    short_note=(
        "A mercadoria é nossa até ser paga por inteiro. O que chegar partido anota-se "
        "na folha do motorista antes de assinar e comunica-se-nos na mesma semana. "
        "Uma palete deixada a um vizinho fica por conta e risco do comprador."
    ),
    long_note=(
        "O pagamento vence a trinta dias da data de emissão, por transferência para a "
        "conta indicada no rodapé da fatura. Uma linha contestada por escrito só "
        "suspende essa linha, e o resto da fatura vence na data prevista. O trabalho "
        "já agendado é mantido até quinze dias após essa data e, depois, libertado."
    ),
    caveat=(
        "As linhas de uma nota afastam-se, e nada mais: o espaço à volta de um "
        "parágrafo, a queda sob a última linha e a altura das próprias palavras ficam "
        "onde estão. Com a caixa dá-se um limite, por isso duas linhas numa caixa "
        "alta mantêm o entrelinhamento em vez de se esticarem em escada."
    ),
)

# The page in Italian.
ITALIAN = Words(
    title="Due ordini, una cornice, un solo bordo inferiore",
    lead=(
        "Le due cornici qui sotto hanno la stessa altezza, e gli ordini che "
        "contengono non hanno la stessa lunghezza. Ogni cornice è riempita: lo spazio "
        "lasciato dalle righe si ripartisce tra loro in parti uguali, una volta "
        "misurate tutte, così l’ultima riga di un ordine di quattro finisce dove "
        "finisce l’ultima di un ordine di sette. I titoli e il totale restano dove li "
        "mette la carta intestata, e crescono solo le righe fatturate."
    ),
    orders="Quattro righe e sette, che finiscono insieme",
    short_order="Ordine 4412",
    long_order="Ordine 4413",
    item="Voce",
    amount="Importo",
    short_items=("Sopralluogo", "Cavo, 40 m", "Scatole a muro", "Posa, un giorno"),
    long_items=(
        "Sopralluogo",
        "Cavo, 15 m",
        "Scatole a muro",
        "Scatola di derivazione",
        "Posa, due giorni",
        "Placche",
        "Collaudo e rapporto",
    ),
    total="Totale",
    notes="Due note di lunghezza diversa, che finiscono insieme",
    short_note=(
        "La merce resta nostra finché non è pagata per intero. Ciò che arriva rotto "
        "va scritto sul foglio dell’autista prima di firmarlo e comunicato a noi "
        "nella stessa settimana. Un bancale lasciato a un vicino resta a rischio "
        "dell’acquirente."
    ),
    long_note=(
        "Il pagamento scade a trenta giorni dalla data di emissione, con bonifico sul "
        "conto indicato a piè di fattura. Una riga contestata per iscritto sospende "
        "solo quella riga, e il resto della fattura scade il giorno di sempre. Il "
        "lavoro già prenotato è tenuto quindici giorni dopo quel giorno e poi "
        "liberato."
    ),
    caveat=(
        "Le righe di una nota si allontanano, e nient’altro: lo spazio intorno a un "
        "paragrafo, la caduta sotto l’ultima riga e l’altezza delle parole stesse "
        "restano dove sono. Con la cornice si dà un limite, così due righe in una "
        "cornice alta tengono la loro interlinea anziché sparpagliarsi per tutta "
        "l’altezza."
    ),
)

# The page in Spanish.
SPANISH = Words(
    title="Dos pedidos, un marco, un mismo borde inferior",
    lead=(
        "Los dos marcos de abajo tienen la misma altura, y los pedidos que contienen "
        "no tienen la misma longitud. Cada marco se llena: el sitio que dejan las "
        "líneas se reparte entre ellas a partes iguales, una vez medidas todas, así "
        "que la última línea de un pedido de cuatro acaba donde acaba la última de un "
        "pedido de siete. Los títulos y el total se quedan donde los pone el papel, y "
        "solo crecen las líneas facturadas."
    ),
    orders="Cuatro líneas y siete, acabando juntas",
    short_order="Pedido 4412",
    long_order="Pedido 4413",
    item="Artículo",
    amount="Importe",
    short_items=("Visita técnica", "Cable, 40 m", "Cajas de pared", "Montaje, un día"),
    long_items=(
        "Visita técnica",
        "Cable, 15 m",
        "Cajas de pared",
        "Caja de empalmes",
        "Montaje, dos días",
        "Tapas",
        "Prueba e informe",
    ),
    total="Total",
    notes="Dos notas de distinta longitud, acabando juntas",
    short_note=(
        "La mercancía es nuestra hasta que se paga por completo. Lo que llegue roto "
        "se anota en la hoja del conductor antes de firmarla y se nos comunica la "
        "misma semana. Un palé dejado a un vecino queda a riesgo del comprador."
    ),
    long_note=(
        "El pago vence a treinta días de la fecha de emisión, por transferencia a la "
        "cuenta indicada al pie de la factura. Una línea impugnada por escrito solo "
        "suspende esa línea, y el resto de la factura vence en la fecha prevista. El "
        "trabajo ya reservado se mantiene quince días después de ese día y luego se "
        "libera."
    ),
    caveat=(
        "Las líneas de una nota se separan, y nada más: el espacio alrededor de un "
        "párrafo, el espacio bajo la última línea y la altura de las propias palabras "
        "se quedan como están. La caja fija un límite, así que dos líneas en una caja "
        "alta conservan su interlineado en vez de estirarse en escalera."
    ),
)

# The page in German.
GERMAN = Words(
    title="Zwei Bestellungen, ein Rahmen, eine Unterkante",
    lead=(
        "Die beiden Rahmen unten sind gleich hoch, und die Bestellungen darin sind "
        "nicht gleich lang. Jeder Rahmen wird gefüllt: Der Platz, den die Zeilen "
        "übrig lassen, wird zu gleichen Teilen unter ihnen verteilt, sobald alle "
        "gemessen sind, sodass die letzte Zeile einer Bestellung mit vier Posten dort "
        "endet, wo die letzte Zeile einer Bestellung mit sieben endet. Die "
        "Überschriften und die Summe bleiben, wo das Briefpapier sie vorsieht, und "
        "nur die berechneten Zeilen wachsen."
    ),
    orders="Vier Zeilen und sieben, die zusammen enden",
    short_order="Bestellung 4412",
    long_order="Bestellung 4413",
    item="Posten",
    amount="Betrag",
    short_items=("Ortsbesichtigung", "Kabel, 40 m", "Wanddosen", "Montage, ein Tag"),
    long_items=(
        "Ortsbesichtigung",
        "Kabel, 15 m",
        "Wanddosen",
        "Abzweigdose",
        "Montage, zwei Tage",
        "Abdeckplatten",
        "Prüfung und Bericht",
    ),
    total="Summe",
    notes="Zwei ungleich lange Hinweise, die zusammen enden",
    short_note=(
        "Die Ware bleibt unser Eigentum, bis sie vollständig bezahlt ist. Was "
        "beschädigt ankommt, ist auf dem Blatt des Fahrers zu vermerken, bevor es "
        "unterschrieben wird, und uns in derselben Woche mitzuteilen. Eine bei einem "
        "Nachbarn abgegebene Palette bleibt auf eigene Gefahr des Käufers dort."
    ),
    long_note=(
        "Die Zahlung ist dreißig Tage nach dem Ausstellungsdatum fällig, per "
        "Überweisung auf das im Fuß der Rechnung genannte Konto. Eine schriftlich "
        "beanstandete Zeile hält nur diese Zeile an, und der Rest der Rechnung wird "
        "an dem Tag fällig, an dem er ohnehin fällig geworden wäre. Bereits gebuchte "
        "Arbeit wird nach diesem Tag vierzehn Tage lang vorgehalten und danach "
        "freigegeben."
    ),
    caveat=(
        "Die Zeilen eines Hinweises werden auseinandergerückt, und sonst nichts: Der "
        "Raum um einen Absatz, der Abstand unter der letzten Zeile und die Höhe der "
        "Wörter selbst bleiben, wie sie sind. Mit dem Rahmen wird eine Grenze "
        "angegeben, sodass zwei Zeilen in einem hohen Rahmen ihren Abstand behalten, "
        "statt zu einer Leiter gestreckt zu werden."
    ),
)

# 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 page.
LEFT = 72.0

# How wide a block of text is, and how wide the two frames are together.
WIDTH = 451.0

# How wide one frame is.
FRAME_WIDTH = 216.0

# How far apart the two frames stand.
FRAME_GAP = WIDTH - 2 * FRAME_WIDTH

# How tall each of the two order frames is.
FRAME_HEIGHT = 200.0

# How tall each of the two note boxes is.
NOTE_HEIGHT = 110.0

# The size a note is set at.
NOTE_SIZE = 8.5

# The furthest apart the lines of a note are ever moved.
NOTE_LIMIT = 26.0

# The size an order is set at.
ORDER_SIZE = 8.5

# The least tall a billed line is before the frame is shared out.
ROW_HEIGHT = 16.0

# The grey the page draws its second-rank words in.
GREY = hqf_pdf.Rgb.gray(0.42)

# The grey a note's box is outlined in.
OUTLINE = hqf_pdf.Rgb.gray(0.72)


def block(
    content: hqf_pdf.Content,
    flow: hqf_pdf.TextFlow,
    x: float,
    top: float,
    width: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    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, x, top, width)
    return top - flow.height(lines)


def amount(value: float) -> str:
    """An amount, as an order writes it: "1 158.00"."""
    units, hundredths = f"{value:.2f}".split(".")
    grouped = []
    for index, digit in enumerate(units):
        if index > 0 and (len(units) - index) % 3 == 0:
            grouped.append(" ")
        grouped.append(digit)
    return f"{''.join(grouped)}.{hundredths}"


def order(
    font: hqf_pdf.FontHandle,
    words: Words,
    items: tuple[str, ...],
    amounts: tuple[float, ...],
) -> hqf_pdf.Table:
    """One of the two orders: a heading row, the billed lines, and the total."""
    columns = hqf_pdf.Columns(
        [hqf_pdf.ColumnWidth.fraction(1.0), hqf_pdf.ColumnWidth.points(62.0)],
        FRAME_WIDTH,
    )

    table = hqf_pdf.Table(columns)
    table.header(1)
    table.footer(1)
    # Every box the table is fitted into is filled to its bottom edge.
    table.fill_frame(True)
    table.rule(hqf_pdf.Rule.frame(), hqf_pdf.Stroke(0.7))
    table.rule(
        hqf_pdf.Rule.horizontal_other(),
        hqf_pdf.Stroke(0.25, color=hqf_pdf.Rgb.gray(0.78)),
    )
    table.rule(hqf_pdf.Rule.horizontal(1), hqf_pdf.Stroke(0.7))
    table.rule(hqf_pdf.Rule.horizontal_from_end(1), hqf_pdf.Stroke(0.7))

    pad = hqf_pdf.Padding.symmetric(5.0, 4.0)
    shade = hqf_pdf.Rgb.gray(0.9)
    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    words.item,
                    padding=pad,
                    fill=shade,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    words.amount,
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    fill=shade,
                    valign=hqf_pdf.VAlign.Middle,
                ),
            ],
            min_height=18.0,
        )
    )

    total = 0.0
    for label, value in zip(items, amounts):
        total += value
        table.push(
            hqf_pdf.Row(
                cells=[
                    hqf_pdf.Cell(
                        font,
                        ORDER_SIZE,
                        label,
                        padding=pad,
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                    hqf_pdf.Cell(
                        font,
                        ORDER_SIZE,
                        amount(value),
                        padding=pad,
                        align=hqf_pdf.Align.Right,
                        valign=hqf_pdf.VAlign.Middle,
                    ),
                ],
                min_height=ROW_HEIGHT,
            )
        )

    table.push(
        hqf_pdf.Row(
            cells=[
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    words.total,
                    padding=pad,
                    valign=hqf_pdf.VAlign.Middle,
                ),
                hqf_pdf.Cell(
                    font,
                    ORDER_SIZE,
                    amount(total),
                    padding=pad,
                    align=hqf_pdf.Align.Right,
                    valign=hqf_pdf.VAlign.Middle,
                ),
            ],
            min_height=18.0,
        )
    )

    return table


def note(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    x: float,
    top: float,
    text: str,
) -> None:
    """Draws one note in a box `NOTE_HEIGHT` points tall, its lines moved apart until
    the last of them reaches the bottom."""
    content.set_stroke(OUTLINE)
    content.set_line_width(0.4)
    content.rect(x, top - NOTE_HEIGHT, FRAME_WIDTH, NOTE_HEIGHT)
    content.stroke()

    # The box is filled from the top of the letters to the foot of them, so the block
    # the spread is measured against is the block a reader sees.
    flow = hqf_pdf.TextFlow(
        font,
        NOTE_SIZE,
        first_baseline=hqf_pdf.FirstBaseline.ascender(),
        last_baseline=hqf_pdf.LastBaseline.descender(),
    )
    lines = flow.break_lines(text, FRAME_WIDTH - 12.0)
    spread = flow.leading(flow.fill_leading(lines, NOTE_HEIGHT, NOTE_LIMIT))
    spread.draw(content, lines, x + 6.0, top, FRAME_WIDTH - 12.0)


def build(document: hqf_pdf.Document, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the whole page."""
    title = hqf_pdf.TextFlow(font, 18.0)
    lead = hqf_pdf.TextFlow(font, 10.0)
    label = hqf_pdf.TextFlow(font, 12.0)
    small = hqf_pdf.TextFlow(font, 8.5, color=GREY)

    content = hqf_pdf.Content()
    top = 790.0
    top = block(content, title, LEFT, top, WIDTH, words.title) - 12.0
    top = block(content, lead, LEFT, top, WIDTH, words.lead) - 22.0
    top = block(content, label, LEFT, top, WIDTH, words.orders) - 12.0

    right = LEFT + FRAME_WIDTH + FRAME_GAP
    block(content, small, LEFT, top, FRAME_WIDTH, words.short_order)
    top = block(content, small, right, top, FRAME_WIDTH, words.long_order) - 6.0

    for x, items, amounts in (
        (LEFT, words.short_items, SHORT_AMOUNTS),
        (right, words.long_items, LONG_AMOUNTS),
    ):
        placed = order(font, words, items, amounts).fit(x, top, FRAME_HEIGHT)
        placed.draw(content)
    top -= FRAME_HEIGHT + 26.0

    top = block(content, label, LEFT, top, WIDTH, words.notes) - 14.0
    note(content, font, LEFT, top, words.short_note)
    note(content, font, right, top, words.long_note)
    top -= NOTE_HEIGHT + 24.0

    closing = hqf_pdf.TextFlow(font, 9.0, color=GREY)
    block(content, closing, LEFT, top, WIDTH, words.caveat)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(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("filled_frame.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    build(document, font, words)

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


if __name__ == "__main__":
    main()