write_document_parts.rs

Die Rust-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.

Rust 764 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
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
//! Writes three customer statements into one file, and says in the file where
//! each of them starts.
//!
//! 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: `cargo run --example write_document_parts -- tmp/parts.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_document_parts`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::action::Action;
use hqf_pdf::content::Content;
use hqf_pdf::layout::{Cell, ColumnWidth, Columns, Padding, Row, Rule, Stroke, Table, TableFrame};
use hqf_pdf::metadata::attachment::{Attachment, Relationship};
use hqf_pdf::{
    Align, AttachmentHandle, Document, DocumentPart, DocumentParts, Error, Font, FontHandle, Link,
    Page, PartData, PartValue, Rgb, TextFlow, Version,
};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the page is set in when the caller names none: the one committed
/// for the tests, so the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The words the pages are written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the file as a whole is called.
    title: &'static str,
    /// What the file carries, said once at the top of the first sheet.
    lead: &'static str,
    /// What the hierarchy says, said in grey at the foot of the first sheet.
    note: &'static str,
    /// The word a statement is called by.
    statement: &'static str,
    /// The word a customer number is introduced by.
    customer: &'static str,
    /// The word a sheet is counted by.
    sheet: &'static str,
    /// Who each of the three statements is for.
    recipients: [&'static str; 3],
    /// Where each of them is sent.
    towns: [&'static str; 3],
    /// The country every recipient is in.
    country: &'static str,
    /// The two column headings of a statement.
    columns: [&'static str; 2],
    /// What the three lines of a statement are called.
    lines: [&'static str; 3],
    /// The label on the total row.
    total: &'static str,
    /// The heading of the terms sheet.
    terms_title: &'static str,
    /// What the terms sheet says.
    terms: &'static str,
    /// What the file carried beside each statement holds.
    carried: &'static str,
}

impl Words {
    /// The words the pages are written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The pages in English.
const ENGLISH: Words = 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.
const FRENCH: Words = 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.
const DUTCH: Words = 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.
const PORTUGUESE: Words = 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.
const ITALIAN: Words = 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.
const SPANISH: Words = 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.
const GERMAN: Words = 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.
static WORDS: [(Language, &Words); 7] = [
    (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.
const LEFT: f64 = 72.0;

/// How wide a block of text, and a statement, are.
const WIDTH: f64 = 451.0;

/// The number each customer is known by.
const NUMBERS: [&str; 3] = ["4711", "4712", "4713"];

/// How many copies of each statement the run owes.
const COPIES: [i64; 3] = [2, 1, 3];

/// What each statement's envelope weighs, in kilograms.
const WEIGHTS: [f64; 3] = [0.12, 0.08, 0.16];

/// When each statement was posted.
const POSTED: [&str; 3] = [
    "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.
const AMOUNTS: [[i64; 3]; 3] = [
    [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.
const RUNS: [(usize, usize); 3] = [(0, 2), (2, 3), (3, 4)];

/// An amount, with a space between its thousands and a point before its cents.
fn money(cents: i64) -> String {
    let (whole, fraction) = (cents / 100, cents % 100);
    let digits = whole.to_string();
    let mut out = String::with_capacity(digits.len() + 8);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            out.push('\u{00A0}');
        }
        out.push(digit);
    }
    format!("{out}.{fraction:02}\u{00A0}EUR")
}

/// Sets a block of words with its first baseline at `top`, and hands back the
/// ordinate the block ends at.
fn block(
    c: &mut Content,
    handle: &FontHandle,
    size: f64,
    top: f64,
    text: &str,
) -> Result<f64, Error> {
    let flow = TextFlow::new(handle, size);
    let lines = flow.break_lines(text, WIDTH);
    c.begin_text();
    flow.draw(c, &lines, LEFT, top, WIDTH)?;
    c.end_text();
    Ok(top - flow.height(&lines))
}

/// The lines and total of one statement.
fn charges<'f>(words: &Words, text: &'f FontHandle, index: usize) -> Result<Table<'f>, Error> {
    let columns = Columns::new(
        vec![ColumnWidth::Fraction(1.0), ColumnWidth::Points(110.0)],
        WIDTH,
    )?;

    let mut table = Table::new(columns);
    table.header(1);
    table
        .rule(Rule::Frame, Stroke::black(0.75))
        .rule(Rule::HorizontalOther, Stroke::new(0.5, Rgb::gray(0.6)))
        .rule(Rule::Vertical(1), Stroke::new(0.5, Rgb::gray(0.6)));

    let pad = Padding::symmetric(5.0, 4.0);
    let heading = |label: &str, align| {
        Cell::new(text, 9.5, label)
            .padding(pad)
            .align(align)
            .fill(Rgb::new(0.93, 0.94, 0.97))
    };
    table.push(
        Row::new()
            .cell(heading(words.columns[0], Align::Left))
            .cell(heading(words.columns[1], Align::Right))
            .min_height(19.0),
    );

    for (label, amount) in words.lines.iter().zip(AMOUNTS[index]) {
        table.push(
            Row::new()
                .cell(Cell::new(text, 9.0, *label).padding(pad))
                .cell(
                    Cell::new(text, 9.0, money(amount))
                        .padding(pad)
                        .align(Align::Right),
                )
                .min_height(16.0),
        );
    }

    table.push(
        Row::new()
            .cell(Cell::new(text, 9.5, words.total).padding(pad))
            .cell(
                Cell::new(text, 9.5, money(AMOUNTS[index].iter().sum()))
                    .padding(pad)
                    .align(Align::Right),
            )
            .min_height(19.0),
    );
    Ok(table)
}

/// Draws the foot of a sheet: who it is for, and where it stands in its
/// statement.
fn foot(
    c: &mut Content,
    words: &Words,
    text: &FontHandle,
    index: usize,
    sheet: usize,
) -> Result<(), Error> {
    let (first, after) = RUNS[index];
    let flow = TextFlow::new(text, 8.0);
    let line = format!(
        "{} {}/{} \u{2014} {} \u{2014} {} {}/{}",
        words.statement,
        index + 1,
        RUNS.len(),
        words.recipients[index],
        words.sheet,
        sheet + 1,
        after - first
    );
    c.set_fill(Rgb::gray(0.45))?;
    c.begin_text();
    flow.draw(c, &flow.break_lines(&line, WIDTH), LEFT, 56.0, WIDTH)?;
    c.end_text();
    c.set_fill(Rgb::gray(0.0))?;
    Ok(())
}

/// Draws the sheet a statement is charged on.
fn charge_sheet(words: &Words, text: &FontHandle, index: usize) -> Result<Vec<u8>, Error> {
    let mut c = Content::new();
    let mut top = 782.0;

    if index == 0 {
        top = block(&mut c, text, 17.0, top, words.title)? - 12.0;
        top = block(&mut c, text, 9.5, top, words.lead)? - 26.0;
    }

    top = block(&mut c, text, 13.0, top, words.recipients[index])? - 6.0;
    let whereabouts = format!(
        "{} {} \u{2014} {}, {}",
        words.customer, NUMBERS[index], words.towns[index], words.country
    );
    top = block(&mut c, text, 9.0, top, &whereabouts)? - 20.0;

    let placed = charges(words, text, index)?.fit(TableFrame::new(LEFT, top, 120.0), 0)?;
    placed.draw(&mut c)?;

    if index == 0 {
        c.set_fill(Rgb::gray(0.35))?;
        block(&mut c, text, 8.5, placed.bottom() - 26.0, words.note)?;
        c.set_fill(Rgb::gray(0.0))?;
    }

    foot(&mut c, words, text, index, 0)?;
    Ok(c.into_bytes())
}

/// Draws the terms sheet that follows the first statement.
fn terms_sheet(words: &Words, text: &FontHandle) -> Result<Vec<u8>, Error> {
    let mut c = Content::new();
    let top = block(&mut c, text, 13.0, 782.0, words.terms_title)? - 14.0;
    block(&mut c, text, 9.5, top, words.terms)?;
    foot(&mut c, words, text, 0, 1)?;
    Ok(c.into_bytes())
}

/// The data file carried beside one statement.
fn carried(words: &Words, index: usize) -> Attachment {
    let total: i64 = AMOUNTS[index].iter().sum();
    Attachment::new(
        format!("statement-{}.xml", NUMBERS[index]),
        words.carried,
        "text/xml",
        Relationship::Data,
        POSTED[index],
        format!(
            "<statement customer=\"{}\" total=\"{total}\"/>\n",
            NUMBERS[index]
        )
        .into_bytes(),
    )
}

/// 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.
fn stated(words: &Words, index: usize) -> Result<PartData, Error> {
    let address = PartData::new()
        .set("Town", PartValue::Text(words.towns[index].to_owned()))?
        .set("Country", words.country)?;
    let mut stated = PartData::new()
        .set("Recipient", words.recipients[index])?
        .set("CustomerNumber", NUMBERS[index])?
        .set("Copies", PartValue::Integer(COPIES[index]))?
        .set("Posted", PartValue::date(POSTED[index]))?
        .set("Address", PartValue::Fields(address))?
        .set("Weight", PartValue::Real(WEIGHTS[index]))?
        .set("Tracked", PartValue::Boolean(index == 0))?
        .set(
            "Enclosures",
            PartValue::List(vec![PartValue::Text(format!(
                "statement-{}.xml",
                NUMBERS[index]
            ))]),
        )?
        .set("Proof", true)?;
    stated.unset("Proof");
    Ok(stated)
}

/// How many copies every statement stated comes to, read back from what each
/// states, and how many statements state anything at all.
fn copies_stated(words: &Words) -> Result<(i64, usize), Error> {
    let mut copies = 0;
    let mut stating = 0;
    for index in 0..RUNS.len() {
        let data = stated(words, index)?;
        if !data.is_empty() {
            stating += 1;
        }
        if let Some(PartValue::Integer(count)) = data.get("Copies") {
            copies += count;
        }
    }
    Ok((copies, stating))
}

/// The hierarchy: one part per statement, under the part that is the whole run.
fn hierarchy(words: &Words, files: [AttachmentHandle; 3]) -> Result<DocumentParts, Error> {
    let mut run = DocumentPart::new();
    for (index, file) in files.into_iter().enumerate() {
        let (first, after) = RUNS[index];
        run = run.child(
            DocumentPart::new()
                .pages(first..after)
                .data(stated(words, index)?)
                .associated_files(vec![file]),
        );
    }
    DocumentParts::new(run)
        .node_names(["Run", "Statement"])
        .map(|parts| parts.record_level(1))
}

/// The foot of a sheet of statement `index`, as a link leading to the part that
/// claims the statement's first sheet.
const fn to_statement(index: usize) -> Link {
    let (first, _) = RUNS[index];
    Link::acting(LEFT, 52.0, WIDTH, 12.0, Action::Part(first))
}

/// Draws the four sheets and says which of them belong to which statement.
fn build(words: &Words, font: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    // The hierarchy of document parts is written on PDF 2.0 and on nothing
    // earlier.
    doc.set_version(Version::V2_0);
    let text = doc.add_font(Font::parse(fs::read(font)?)?);

    let files = [
        doc.attach(carried(words, 0)),
        doc.attach(carried(words, 1)),
        doc.attach(carried(words, 2)),
    ];

    let mut first = Page::a4();
    first.content = charge_sheet(words, &text, 0)?;
    first.links.push(to_statement(0));
    doc.add_page(first)?;

    let mut second = Page::a4();
    second.content = terms_sheet(words, &text)?;
    second.links.push(to_statement(0));
    doc.add_page(second)?;

    for index in 1..3 {
        let mut sheet = Page::a4();
        sheet.content = charge_sheet(words, &text, index)?;
        sheet.links.push(to_statement(index));
        doc.add_page(sheet)?;
    }

    doc.set_document_parts(hierarchy(words, files)?);
    Ok(doc.to_bytes()?)
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the two languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("document_parts")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let bytes = build(words, &font_path)?;

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    let (copies, stating) = copies_stated(words)?;
    println!(
        "wrote {out}: {} bytes, {stating} statements asking for {copies} copies",
        bytes.len()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Font, FontHandle};

    use super::{AMOUNTS, COPIES, NUMBERS, RUNS, WIDTH, WORDS, default_font, language, money};

    /// The font the pages are set in, to measure what they draw.
    fn handle() -> FontHandle {
        let mut doc = hqf_pdf::Document::new();
        doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the test font")).expect("a font"),
        )
    }

    /// The lines two languages are allowed to write the same way: the label on
    /// the total row is the same word in English and in French.
    const SPARED: [&str; 9] = [
        "total: \"Total\"",
        // Written the same way in German.
        r#""Baker and Sons""#,
        r#""Bristol""#,
        r#""Halden Joinery""#,
        r#""Kendal""#,
        r#""Truro""#,
        r#""Westmill Dairy""#,
        // Written the same way in Italian.
        r#"customer: "Cliente""#,
        // Written the same way in Portuguese.
        r#"country: "Reino Unido""#,
    ];

    #[test]
    fn every_language_draws_the_pages_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the pages say these in more than one language: {untranslated:?}"
        );
    }

    #[test]
    fn the_statements_claim_every_sheet_of_the_run_exactly_once() {
        let sheets = RUNS.last().expect("three statements").1;
        let mut claims = vec![0_usize; sheets];
        for (first, after) in RUNS {
            assert!(first < after, "a statement claims no sheet at all");
            for claimed in claims.iter_mut().take(after).skip(first) {
                *claimed += 1;
            }
        }

        assert!(
            claims.iter().all(|&count| count == 1),
            "the sheets are claimed {claims:?} times"
        );
    }

    #[test]
    fn every_statement_has_a_customer_a_number_of_copies_and_a_run_of_sheets() {
        for (_, words) in &WORDS {
            assert_eq!(words.recipients.len(), RUNS.len());
            assert_eq!(words.towns.len(), RUNS.len());
        }
        assert_eq!(NUMBERS.len(), RUNS.len());
        assert_eq!(COPIES.len(), RUNS.len());
        assert_eq!(AMOUNTS.len(), RUNS.len());
    }

    #[test]
    fn every_line_of_a_statement_fits_the_column_it_is_set_in() {
        let font = handle();
        // The right column is 110 points wide and every cell is padded by five
        // points on each side.
        let labels = WIDTH - 110.0 - 10.0;
        for (_, words) in &WORDS {
            for label in words.lines {
                assert!(
                    font.measure(label, 9.0) <= labels,
                    "{label:?} needs {} of {labels}",
                    font.measure(label, 9.0)
                );
            }
            assert!(
                font.measure(words.columns[1], 9.5) <= 100.0,
                "{:?} needs {} of 100",
                words.columns[1],
                font.measure(words.columns[1], 9.5)
            );
        }
    }

    #[test]
    fn the_largest_amount_a_statement_draws_fits_its_column() {
        let font = handle();
        let largest = AMOUNTS
            .iter()
            .map(|lines| lines.iter().sum::<i64>())
            .max()
            .expect("three statements");

        assert!(
            font.measure(&money(largest), 9.5) <= 100.0,
            "{} needs {}",
            money(largest),
            font.measure(&money(largest), 9.5)
        );
    }

    #[test]
    fn an_amount_is_written_with_a_space_between_its_thousands() {
        assert_eq!(money(9_600), "96.00\u{00A0}EUR");
        assert_eq!(money(48_050), "480.50\u{00A0}EUR");
        assert_eq!(money(125_000), "1\u{00A0}250.00\u{00A0}EUR");
        assert_eq!(
            money(AMOUNTS[2].iter().sum()),
            "3\u{00A0}696.50\u{00A0}EUR",
            "the largest total the pages draw"
        );
    }
}