write_table_paginated.rs

Die Rust-Datei des Beispiels „Eine Tabelle, die sich selbst umbricht“. Eine lange, als Ganzes übergebene Tabelle, die selbst entscheidet, wo die Seiten umbrechen: ihre Überschrift oben auf jeder Seite, ihre Fußnote unter jeder Seite, die Zelle eines Quartals über ihre Zeilen gespannt und oben auf der nächsten Seite erneut geschrieben, wenn eine Seite sie teilt, und eine Notiz, die Sie unter jede Seite genau an die Stelle zeichnen, die die Tabelle meldet.

Rust 797 Zeilen

Wofür dieses Beispiel da ist

Eine Rechnung mit dreihundert Positionen. Eine Bestandsliste. Ein Monat Kassenbons. Nichts davon passt auf eine Seite, und nichts davon hat eine Länge, auf die man sich verlassen kann: Derselbe Bericht umfasst einen Monat vier Seiten und den nächsten elf. Trotzdem muss jemand entscheiden, wo jede Seite endet — und an dieser Entscheidung entsteht aus dem Nichts eine leere Seite, wird eine Zeile halbiert oder bleibt eine Abschnittsüberschrift allein am Fuß einer Seite stehen, ohne etwas darunter.

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
//! Hands a long table over whole, and lets it decide how many pages it needs.
//!
//! This is the shape a document server wants: build the table, say what box it
//! gets on the first page and what box it gets on the ones after, and call
//! `paginate` once. It answers with one placement per page. The caller makes
//! each page — here, by stamping it onto an imported stationery template — and
//! draws the placement onto it. No loop to write, and no way to write it wrong:
//! a table that could not advance is an error, not another blank page.
//!
//! Five things the table does on its own, which is why the caller no longer can
//! get them wrong:
//!
//!   - the caption is set over the table on every page, its room taken off
//!     the box before a row is placed;
//!   - the heading row is drawn again at the top of every page;
//!   - the footnote row is drawn again under the last line of every page;
//!   - a section title is kept with the rows under it, so it is never stranded
//!     at the foot of a page away from what it introduces;
//!   - the cell naming a quarter covers every row of that quarter, and where a
//!     page ends inside the quarter it is cut there and drawn again at the top
//!     of the next page, over the rows left.
//!
//! Under each page the caller adds a note of its own, saying which of the
//! table's rows the page carried and hanging its page number on the grid line
//! before the amounts. The placement is asked for all of it: where its
//! rows ended, where that grid line fell, and which rows it took.
//!
//! Every word the statement draws is held in `Words`, once per language, and
//! `HQF_PDF_LANG` picks which one is drawn. The amounts are the same in both.
//!
//! Usage: `cargo run --example write_table_paginated -- tmp/paginated.pdf
//! [stationery.pdf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_table_paginated --
//! tmp/releve.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{
    Area, Border, Caption, Cell, ColumnWidth, Columns, FittedTable, Margin, Padding, Row, Rule,
    Stroke, Table, TableFrame, TextFlow, VAlign,
};
use hqf_pdf::read::Reader;
use hqf_pdf::{Align, Document, Font, FontHandle, Page, Rgb};

#[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 example draws with.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// A4's width, and the margins the table is laid out between.
const PAGE_WIDTH: f64 = 595.276;
const MARGIN: f64 = 56.0;
const TABLE_WIDTH: f64 = PAGE_WIDTH - 2.0 * MARGIN;

/// The table starts below the letterhead on the first page, and higher up on
/// every page after it: that is the whole reason `paginate` takes two boxes.
const FIRST_TOP: f64 = 700.0;
const NEXT_TOP: f64 = 800.0;
/// The lowest either may reach.
const BOTTOM: f64 = 64.0;

/// How many sections the statement has, and how many lines in all.
const SECTION_COUNT: usize = 4;
const LINE_COUNT: usize = 15;

/// The words the statement is written in, one set per language.
///
/// What is not language stays out of it: the amounts, the company's name and
/// its address read the same in every language.
#[derive(Debug)]
struct Words {
    /// The line the letterhead of the stationery carries.
    letterhead: &'static str,
    /// The three column headings.
    period: &'static str,
    description: &'static str,
    amount: &'static str,
    /// What the cell heading each quarter's rows says; `{n}` stands for its
    /// number.
    quarter: &'static str,
    /// What each section is called, in the order `SECTIONS` gives them.
    sections: [&'static str; SECTION_COUNT],
    /// What each billed line is called, section after section.
    lines: [&'static str; LINE_COUNT],
    /// The label of the boxed total.
    total: &'static str,
    /// The footnote repeated under the last line of every page.
    footnote: &'static str,
    /// The caption set over the table on every page.
    caption: &'static str,
    /// The caller's own note, cut where the row numbers go into it.
    rows_before: &'static str,
    rows_between: &'static str,
    rows_of: &'static str,
    /// The same for the page number.
    page_before: &'static str,
    page_of: &'static str,
}

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

/// The statement in English.
const ENGLISH: Words = Words {
    letterhead: "ACME Ltd — statement of services",
    period: "Quarter",
    quarter: "Q{n}",
    description: "Description",
    amount: "Amount",
    sections: [
        "Development",
        "Reworking what was there",
        "Support",
        "Audit",
    ],
    lines: [
        "Rendering engine",
        "Font engine",
        "Glyph subsetting",
        "Charstring interpreter",
        "Tables and layout",
        "Invoice template",
        "Data migration",
        "Acceptance testing and fixes",
        "Team training",
        "Standby cover for the release night",
        "First year of support",
        "Technical documentation",
        "Performance audit",
        "Security audit",
        "Architecture review",
    ],
    total: "Total due",
    footnote: "Amounts in euros, exclusive of value added tax. ACME Ltd, \
               Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Statement of services for the year, carried on from page to page",
    rows_before: "Rows ",
    rows_between: " to ",
    rows_of: " of ",
    page_before: "Page ",
    page_of: " of ",
};

/// The statement in French.
const FRENCH: Words = Words {
    letterhead: "ACME Ltd — relevé de prestations",
    period: "Trimestre",
    quarter: "T{n}",
    description: "Désignation",
    amount: "Montant",
    sections: [
        "Développement",
        "Reprise de l’existant",
        "Assistance",
        "Audit",
    ],
    lines: [
        "Moteur de rendu",
        "Moteur de polices",
        "Réduction des polices aux glyphes utilisés",
        "Interpréteur de contours de glyphes",
        "Tableaux et mise en page",
        "Modèle de facture",
        "Migration des données",
        "Recette et corrections",
        "Formation de l’équipe",
        "Astreinte la nuit de la mise en production",
        "Première année d’assistance",
        "Documentation technique",
        "Audit de performance",
        "Audit de sécurité",
        "Revue d’architecture",
    ],
    total: "Total dû",
    footnote: "Montants en euros, hors TVA. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Relevé des prestations de l’année, poursuivi de page en page",
    rows_before: "Lignes ",
    rows_between: " à ",
    rows_of: " sur ",
    page_before: "Page ",
    page_of: " sur ",
};

/// The statement in Dutch.
const DUTCH: Words = Words {
    letterhead: "ACME Ltd — overzicht van diensten",
    period: "Kwartaal",
    quarter: "K{n}",
    description: "Omschrijving",
    amount: "Bedrag",
    sections: [
        "Ontwikkeling",
        "Bestaand werk herzien",
        "Ondersteuning",
        "Audit",
    ],
    lines: [
        "Opmaakmotor",
        "Lettertypemotor",
        "Glyph-subsetting",
        "Charstring-interpreter",
        "Tabellen en opmaak",
        "Factuursjabloon",
        "Gegevensmigratie",
        "Acceptatietests en correcties",
        "Teamtraining",
        "Stand-by voor de lanceringsnacht",
        "Eerste jaar ondersteuning",
        "Technische documentatie",
        "Prestatieaudit",
        "Beveiligingsaudit",
        "Architectuurreview",
    ],
    total: "Te betalen",
    footnote: "Bedragen in euro, exclusief btw. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Overzicht van diensten over het jaar, doorgezet van pagina tot pagina",
    rows_before: "Rijen",
    rows_between: " tot",
    rows_of: " van",
    page_before: "Pagina",
    page_of: " van",
};

/// The statement in Portuguese.
const PORTUGUESE: Words = Words {
    letterhead: "ACME Ltd — relação de serviços",
    period: "Trimestre",
    quarter: "{n}.º trim.",
    description: "Descrição",
    amount: "Montante",
    sections: [
        "Desenvolvimento",
        "Refazer o que existia",
        "Suporte",
        "Auditoria",
    ],
    lines: [
        "Motor de paginação",
        "Motor de tipos de letra",
        "Subconjunto de glifos",
        "Intérprete de charstrings",
        "Tabelas e paginação",
        "Modelo de fatura",
        "Migração de dados",
        "Testes de aceitação e correções",
        "Formação da equipa",
        "Prevenção para a noite do lançamento",
        "Primeiro ano de suporte",
        "Documentação técnica",
        "Auditoria de desempenho",
        "Auditoria de segurança",
        "Revisão de arquitetura",
    ],
    total: "Total a pagar",
    footnote: "Montantes em euros, sem imposto sobre o valor acrescentado. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Relação de serviços do ano, transportada de página em página",
    rows_before: "Linhas",
    rows_between: " a",
    rows_of: " de",
    page_before: "Página",
    page_of: " de",
};

/// The statement in Italian.
const ITALIAN: Words = Words {
    letterhead: "ACME Ltd — prospetto dei servizi",
    period: "Trimestre",
    quarter: "{n}º trim.",
    description: "Descrizione",
    amount: "Importo",
    sections: [
        "Sviluppo",
        "Rifacimento dell’esistente",
        "Assistenza",
        "Verifica",
    ],
    lines: [
        "Motore di impaginazione",
        "Motore dei font",
        "Sottoinsieme dei glifi",
        "Interprete di charstring",
        "Tabelle e impaginazione",
        "Modello di fattura",
        "Migrazione dei dati",
        "Collaudo e correzioni",
        "Formazione del team",
        "Reperibilità per la notte del rilascio",
        "Primo anno di assistenza",
        "Documentazione tecnica",
        "Verifica delle prestazioni",
        "Verifica di sicurezza",
        "Revisione dell’architettura",
    ],
    total: "Totale dovuto",
    footnote: "Importi in euro, al netto dell’imposta sul valore aggiunto. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Prospetto dei servizi dell’anno, riportato di pagina in pagina",
    rows_before: "Righe",
    rows_between: " –",
    rows_of: " di",
    page_before: "Pagina",
    page_of: " di",
};

/// The statement in Spanish.
const SPANISH: Words = Words {
    letterhead: "ACME Ltd — relación de servicios",
    period: "Trimestre",
    quarter: "{n}T",
    description: "Descripción",
    amount: "Importe",
    sections: ["Desarrollo", "Rehacer lo existente", "Soporte", "Auditoría"],
    lines: [
        "Motor de maquetación",
        "Motor de fuentes",
        "Subconjunto de glifos",
        "Intérprete de charstrings",
        "Tablas y maquetación",
        "Plantilla de factura",
        "Migración de datos",
        "Pruebas de aceptación y correcciones",
        "Formación del equipo",
        "Guardia para la noche del lanzamiento",
        "Primer año de soporte",
        "Documentación técnica",
        "Auditoría de rendimiento",
        "Auditoría de seguridad",
        "Revisión de arquitectura",
    ],
    total: "Total a pagar",
    footnote: "Importes en euros, sin impuesto sobre el valor añadido. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Relación de servicios del año, continuada de página en página",
    rows_before: "Filas",
    rows_between: " a",
    rows_of: " de",
    page_before: "Página",
    page_of: " de",
};

/// The statement in German.
const GERMAN: Words = Words {
    letterhead: "ACME Ltd — Leistungsaufstellung",
    period: "Quartal",
    quarter: "Q{n}",
    description: "Beschreibung",
    amount: "Betrag",
    sections: [
        "Entwicklung",
        "Überarbeitung des Bestehenden",
        "Support",
        "Prüfung",
    ],
    lines: [
        "Rendering-Engine",
        "Font-Engine",
        "Glyphen-Teilmengen",
        "Charstring-Interpreter",
        "Tabellen und Layout",
        "Rechnungsvorlage",
        "Datenmigration",
        "Abnahmetests und Korrekturen",
        "Schulung des Teams",
        "Bereitschaft in der Nacht der Auslieferung",
        "Erstes Jahr Support",
        "Technische Dokumentation",
        "Leistungsprüfung",
        "Sicherheitsprüfung",
        "Architekturprüfung",
    ],
    total: "Zu zahlen",
    footnote: "Beträge in Euro, zuzüglich Mehrwertsteuer. ACME Ltd, Bureau 4, 12 rue des Fabriques, 59000 Lille.",
    caption: "Leistungsaufstellung für das Jahr, von Seite zu Seite fortgeführt",
    rows_before: "Zeilen ",
    rows_between: " bis ",
    rows_of: " von ",
    page_before: "Seite ",
    page_of: " von ",
};

/// 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 stationery every page is stamped onto, for when the caller has none.
fn a_stationery(
    font_path: &Path,
    words: &'static Words,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let font = doc.add_font(Font::parse(fs::read(font_path)?)?);

    let mut content = Content::new();
    content.save_state();
    content.set_fill_rgb(0.91, 0.94, 0.98)?;
    content.rect(0.0, 812.0, PAGE_WIDTH, 30.0)?;
    content.fill();
    content.set_fill_rgb(0.2, 0.35, 0.6)?;
    content.rect(0.0, 809.0, PAGE_WIDTH, 3.0)?;
    content.fill();
    content.restore_state();

    content.begin_text();
    content.set_font(&font, 13.0)?;
    content.text_origin(MARGIN, 820.0)?;
    content.show_glyphs(&font.glyphs(words.letterhead));
    content.end_text();

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;

    Ok(doc.to_bytes()?)
}

/// One section of the statement: what each of its lines is billed, in the order
/// `Words::lines` names them.
struct Section {
    lines: &'static [f64],
}

/// The statement's sections. Long enough to run over several pages.
const SECTIONS: [Section; SECTION_COUNT] = [
    Section {
        lines: &[7440.0, 4960.0, 2480.0, 3720.0, 5580.0],
    },
    Section {
        lines: &[1440.0, 2700.0, 2880.0],
    },
    Section {
        lines: &[1500.0, 1200.0, 4200.0, 1260.0],
    },
    Section {
        lines: &[2760.0, 3100.0, 1850.0],
    },
];

/// Pushes the rows of quarter `round`, counted from nought: each section's
/// title and each of its lines, the cell naming the quarter over all of them.
fn push_quarter<'a>(
    table: &mut Table<'a>,
    text: &'a FontHandle,
    words: &'static Words,
    round: usize,
    pad: Padding,
) {
    // Every quarter covers each section's title and each of its lines.
    let quarter_rows: usize = SECTIONS.iter().map(|section| 1 + section.lines.len()).sum();
    let mut line = 0;
    for (index, (section, title)) in SECTIONS.iter().zip(words.sections).enumerate() {
        // The cell naming the quarter begins on its first row and covers all of
        // them, drawn again at the top of a page that takes them up.
        let mut row = Row::new();
        if index == 0 {
            row = row.cell(
                Cell::new(
                    text,
                    9.5,
                    words.quarter.replace("{n}", &(round + 1).to_string()),
                )
                .padding(pad)
                .span_rows(quarter_rows)
                .repeated_when_cut(true),
            );
        }
        // The section title is kept with the first line under it: a title alone
        // at the foot of a page introduces nothing.
        table.push(
            row.cell(
                Cell::new(text, 9.5, format!("{title} ({})", round + 1))
                    .padding(pad)
                    .span(2)
                    .fill(Rgb::gray(0.93))
                    .border(Border::none().bottom(&Stroke::black(0.5))),
            )
            .min_height(18.0)
            .keep_with_next(),
        );

        for value in section.lines {
            let label = words.lines[line];
            line += 1;
            table.push(
                Row::new()
                    .cell(Cell::new(text, 9.0, label).padding(pad))
                    .cell(
                        Cell::new(text, 9.0, amount(*value))
                            .padding(pad)
                            .align(Align::Right),
                    )
                    .min_height(16.0),
            );
        }
    }
}

/// An amount, as a statement writes it: "4 250.00 EUR".
fn amount(value: f64) -> String {
    let fixed = format!("{value:.2}");
    let (units, hundredths) = fixed.split_once('.').unwrap_or((fixed.as_str(), "00"));

    let mut grouped = String::new();
    for (index, digit) in units.chars().enumerate() {
        if index > 0 && (units.len() - index) % 3 == 0 {
            grouped.push(' ');
        }
        grouped.push(digit);
    }
    format!("{grouped}.{hundredths} EUR")
}

/// The statement, as one table: a heading, then every section, four times over
/// so that it runs well past a single page.
fn statement<'a>(text: &'a FontHandle, words: &'static Words) -> Result<Table<'a>, hqf_pdf::Error> {
    let columns = Columns::new(
        vec![
            ColumnWidth::Points(64.0),
            ColumnWidth::Fraction(1.0),
            ColumnWidth::Points(110.0),
        ],
        TABLE_WIDTH,
    )?;

    let mut table = Table::new(columns);
    // A quarter's rows that a page cannot hold whole are cut between two of
    // them, rather than all moved to the next page.
    table.split_rows(true);
    // The heading row is drawn again at the top of every page, and the footnote
    // row under the last line of every page.
    table.header(1);
    table.footer(1);
    table.caption(Caption::above(TextFlow::new(text, 10.0), words.caption).gap(6.0));
    table
        .rule(Rule::Frame, Stroke::black(0.8))
        .rule(Rule::HorizontalOther, Stroke::new(0.25, Rgb::gray(0.75)))
        .rule(Rule::Horizontal(1), Stroke::black(0.8))
        .rule(Rule::Vertical(1), Stroke::new(0.25, Rgb::gray(0.75)));
    // The shading is said once, for the table, rather than cell by cell: every
    // other row faintly, and the heading over the top of that.
    table
        .fill(Area::EvenRows, Rgb::gray(0.97))
        .fill(Area::Header, Rgb::gray(0.88));

    let pad = Padding::symmetric(5.0, 4.0);
    let heading = |label: &str, align| {
        Cell::new(text, 9.0, label)
            .padding(pad)
            .align(align)
            .valign(VAlign::Middle)
    };
    table.push(
        Row::new()
            .cell(heading(words.period, Align::Left))
            .cell(heading(words.description, Align::Left))
            .cell(heading(words.amount, Align::Right))
            .min_height(20.0),
    );

    for round in 0..4 {
        push_quarter(&mut table, text, words, round, pad);
    }

    // The total, boxed, and kept with nothing: it ends the table.
    let total: f64 = SECTIONS.iter().flat_map(|s| s.lines.iter()).sum::<f64>() * 4.0;
    let rule = Stroke::black(0.8);
    table.push(
        Row::new()
            .cell(
                Cell::new(text, 10.0, words.total)
                    .padding(pad)
                    .span(2)
                    .align(Align::Right)
                    .margin(Margin::symmetric(0.0, 2.0))
                    .border(Border::none().top(&rule).bottom(&rule).left(&rule)),
            )
            .cell(
                Cell::new(text, 10.0, amount(total))
                    .padding(pad)
                    .align(Align::Right)
                    .margin(Margin::symmetric(0.0, 2.0))
                    .border(Border::none().top(&rule).bottom(&rule).right(&rule)),
            )
            .min_height(20.0),
    );

    // The footnote, repeated under the last line of every page.
    table.push(
        Row::new()
            .cell(
                Cell::new(text, 7.5, words.footnote)
                    .padding(pad)
                    .span(3)
                    .color(Rgb::gray(0.45)),
            )
            .space(6.0, 0.0),
    );

    Ok(table)
}

/// Draws the caller's own note under a page's table.
///
/// Everything it needs comes from the placement: where the rows ended, where
/// the table's left edge and the grid line before the amounts fell, and which
/// of the table's rows this page carried. Nothing here counts rows or adds
/// heights on the side, so the note cannot drift away from the table it
/// describes.
fn continuation_note(
    content: &mut Content,
    text: &FontHandle,
    words: &'static Words,
    placed: &FittedTable<'_>,
    page: usize,
    pages: usize,
    rows: usize,
) -> Result<(), hqf_pdf::Error> {
    let Some(body) = placed.body_rows() else {
        return Ok(());
    };
    let baseline = placed.bottom() - 12.0;

    content.save_state();
    content.set_fill_rgb(0.45, 0.45, 0.45)?;

    content.begin_text();
    content.set_font(text, 7.5)?;
    content.text_origin(placed.x(), baseline)?;
    content.show_glyphs(&text.glyphs(&format!(
        "{}{}{}{}{}{rows}",
        words.rows_before,
        body.start,
        words.rows_between,
        body.end - 1,
        words.rows_of
    )));
    content.end_text();

    if let Some(x) = placed.column_x(2) {
        content.begin_text();
        content.set_font(text, 7.5)?;
        content.text_origin(x, baseline)?;
        content.show_glyphs(&text.glyphs(&format!(
            "{}{}{}{pages}",
            words.page_before,
            page + 1,
            words.page_of
        )));
        content.end_text();
    }

    content.restore_state();
    Ok(())
}

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("paginated")));
    let font_path = default_font();

    // The stationery every page is stamped onto: the caller's, or one made
    // here.
    let stationery = match args.next() {
        Some(given) => fs::read(given)?,
        None => a_stationery(&font_path, words)?,
    };
    let reader = Reader::new(stationery)?;

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let template = doc.import_page(&reader, 0)?;
    let text = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let table = statement(&text, words)?;

    // The whole of pagination: one call, one placement per page.
    let pages = table.paginate(
        TableFrame::new(MARGIN, FIRST_TOP, FIRST_TOP - BOTTOM),
        TableFrame::new(MARGIN, NEXT_TOP, NEXT_TOP - BOTTOM),
    )?;

    for (index, placed) in pages.iter().enumerate() {
        let mut content = Content::new();
        // The stationery goes down first, and the table on top of it.
        content.draw_form(template.name(), 0.0, 0.0, 1.0)?;
        placed.draw(&mut content)?;
        continuation_note(
            &mut content,
            &text,
            words,
            placed,
            index,
            pages.len(),
            table.row_count(),
        )?;

        let mut page = Page::a4();
        page.content = content.into_bytes();
        // The stationery is a form, and a page may only draw what its resources
        // name.
        template.add_to(&mut page);
        doc.add_page(page)?;
    }

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!(
        "wrote {out}: {} bytes, {} pages, {} rows",
        bytes.len(),
        pages.len(),
        table.row_count()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{WORDS, language};

    /// The lines two languages are allowed to write the same way, each with
    /// what makes the two the same word.
    const SPARED: [&str; 14] = [
        "\"Audit\"",
        "\"Page \"",
        "page_before: \"Page \"",
        // Written the same way in German.
        r#""Support""#,
        // Written the same way in Portuguese.
        r#""Intérprete de charstrings""#,
        r#""Subconjunto de glifos""#,
        r#"page_before: "Página""#,
        r#"page_of: " de""#,
        r#"rows_between: " a""#,
        r#"rows_of: " de""#,
        r#"total: "Total a pagar""#,
        // Written the same way in Dutch.
        r#"page_before: "Pagina""#,
        // The quarter, in English and German.
        r#"quarter: "Q{n}""#,
        // The column heading, in French, Spanish, Italian and Portuguese.
        r#"period: "Trimestre""#,
    ];

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

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