write_rich_text.rs

Die Rust-Datei des Beispiels „Den Stil mitten im Absatz ändern“. Ein Absatz, dessen Stil sich darin ändert — Größe, Unterstreichung, Farbe —, dann eine hohl gelassene oder verstärkte Überschrift, eine durch die Buchstaben gezogene Linie, eine lange Webadresse, nach ihren Schrägstrichen umbrochen, und ein in seinem Kasten zentrierter Absatz.

Rust 662 Zeilen

Wofür dieses Beispiel da ist

Der meiste Text in einem echten Dokument hat nicht von Anfang bis Ende einen Stil. Ein Satz hat einen fetten Begriff, eine Summe ist unterstrichen, ein Fußnotenzeichen ist kleiner als die Wörter darum herum. Der übliche Behelf ist, den Satz in Stücke zu schneiden und jedes hinter das letzte zu setzen — was hält, bis der Text übersetzt wird und die Stücke nicht mehr dieselbe Breite ergeben.

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
//! Sets paragraphs whose style changes inside them: sizes that shift mid-line,
//! a total that is underlined, and a word that turns underlined halfway
//! through. Under them, a heading set hollow and thickened, rules set where
//! they are told rather than where the font puts them, a long reference broken
//! after its slashes and cut where nothing else will do, and a paragraph
//! centred in a box, with what its lines measure said under it.
//!
//! Each block is laid out in the same box, so a line is as tall as the tallest
//! style standing on it, and an underline is drawn where each font says one
//! goes.
//!
//! The paragraphs are held in `Words`, once per language, and `HQF_PDF_LANG`
//! picks which set is set. Each is cut around the run whose style changes, so
//! that a language says what it has to say around the same three pieces.
//!
//! Usage: `cargo run --example write_rich_text -- tmp/rich.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_rich_text -- tmp/riche.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::layout::{Overlong, RichLine, RichText, Style, VAlign};
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 when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The left edge of every box, in points.
const LEFT: f64 = 56.0;
/// The width every paragraph is broken to.
const WIDTH: f64 = 420.0;
/// The top of the first box.
const TOP: f64 = 760.0;
/// The gap between one block and the next.
const GAP: f64 = 26.0;

/// The sum the first paragraph is about. A total is not language.
const AMOUNT: &str = "1 240.00 EUR";

/// The reference broken in a narrow box: an address that breaks after its
/// slashes, and a code with nowhere to break but where the box cuts it.
const REFERENCE: &str =
    "hqf-pdf.com/examples/rich-text/overlong/ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";

/// How wide the box the reference is broken in is, in points.
const NARROW: f64 = 150.0;

/// How tall the box the centred paragraph sits in is, in points.
const BOX_HEIGHT: f64 = 60.0;

/// The words the page is set in, one set per language.
///
/// Every paragraph is cut around the run that carries the style being shown, so
/// the piece that is underlined, enlarged or coloured is a piece of the
/// sentence rather than a sentence of its own.
#[derive(Debug)]
struct Words {
    /// The line at the head of the page.
    title: &'static str,
    /// The first paragraph, cut around the amount it names.
    due: [&'static str; 2],
    /// The second, cut around the run set in the largest type.
    tallest: [&'static str; 3],
    /// The third, cut around the run that carries its own colour.
    coloured: [&'static str; 3],
    /// The fourth, cut in the middle of a word: the second piece turns
    /// underlined without the word being broken at the join.
    joined: [&'static str; 3],
    /// The fifth, cut around the run named by the alignment it is set to.
    small: [&'static str; 3],
    /// A heading cut around its hollow run and its thickened one.
    hollow: [&'static str; 5],
    /// A sentence cut around its heavy underline and its thin strikeout.
    rules: [&'static str; 5],
    /// What stands over the reference broken in a narrow box.
    wrapped: &'static str,
    /// The paragraph centred in a box.
    centred: &'static str,
    /// What the centred paragraph's lines measure; `{count}`, `{tall}` and
    /// `{wide}` stand for how many hold words, how tall they are together and
    /// how wide the widest runs.
    measured: &'static str,
}

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

/// The page in English.
const ENGLISH: Words = Words {
    title: "Rich text: styles, sizes, underlining, colour",
    due: [
        "The amount due is ",
        ", payable within thirty days. The balance carries interest at the \
         statutory rate from the day it falls due, and no reminder has to be \
         sent for it to do so.",
    ],
    tallest: [
        "A line is as tall as ",
        "the largest",
        " of the styles standing on it, and no taller.",
    ],
    coloured: [
        "A run can carry its own ",
        "colour",
        ", set apart from the black around it.",
    ],
    joined: [
        "A word may change style in the middle: under",
        "lined",
        " is still one word, and is never broken at the join.",
    ],
    small: [
        "The small print sits in small type, ",
        "flush right",
        ", below the body of the text.",
    ],
    hollow: [
        "A heading set ",
        "hollow",
        ", or ",
        "thickened",
        " without a bolder font",
    ],
    rules: [
        "A rule can sit where it is told: ",
        "a heavy underline",
        " clear of the descenders, or ",
        "a hairline",
        " through the letters.",
    ],
    wrapped: "A reference broken after its slashes, and cut where nothing else will do:",
    centred: "This paragraph is centred, across and down, in the box drawn around it.",
    measured: "{count} lines, {tall} pt tall together, the widest {wide} pt wide.",
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Texte enrichi : styles, tailles, soulignement, couleur",
    due: [
        "Le montant dû est de ",
        ", payable sous trente jours. Le solde produit des intérêts au taux légal à \
compter du jour de son échéance, sans qu’aucun rappel n’ait à être envoyé.",
    ],
    tallest: [
        "Une ligne est aussi haute que ",
        "le plus grand",
        " des styles qu’elle contient, et pas davantage.",
    ],
    coloured: [
        "Un passage peut avoir sa propre ",
        "couleur",
        ", distincte du noir qui l’entoure.",
    ],
    joined: [
        "Un mot peut changer de style en son milieu : souli",
        "gné",
        " reste un seul mot, et n’est jamais coupé à la jointure.",
    ],
    small: [
        "Les mentions légales sont en petits caractères, ",
        "alignées à droite",
        ", sous le corps du texte.",
    ],
    hollow: [
        "Un titre ",
        "évidé",
        ", ou ",
        "épaissi",
        " sans police plus grasse",
    ],
    rules: [
        "Un filet peut se placer où on le demande : ",
        "un soulignement épais",
        " sous les jambages, ou ",
        "un trait fin",
        " à travers les lettres.",
    ],
    wrapped: "Une référence coupée après ses barres obliques, et tranchée là où il n’y a \
pas d’autre choix :",
    centred: "Ce paragraphe est centré, en largeur et en hauteur, dans le cadre tracé autour de lui.",
    measured: "{count} lignes, {tall} pt de haut ensemble, la plus large de {wide} pt.",
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Opgemaakte tekst: stijlen, groottes, onderstreping, kleur",
    due: [
        "Het verschuldigde bedrag is",
        ", te betalen binnen dertig dagen. Over het saldo is vanaf de vervaldag wettelijke rente verschuldigd, zonder dat daarvoor een herinnering hoeft te worden gestuurd.",
    ],
    tallest: [
        "Een regel is zo hoog als",
        "de grootste",
        " van de stijlen die erop staan, en niet hoger.",
    ],
    coloured: [
        "Een stuk kan een eigen",
        "kleur",
        " hebben, los van het zwart eromheen.",
    ],
    joined: [
        "Een woord kan halverwege van stijl veranderen: onder",
        "streept",
        " is nog steeds één woord, en wordt nooit bij de naad gebroken.",
    ],
    small: [
        "De kleine lettertjes staan in kleine letter,",
        "rechts uitgelijnd",
        ", onder de hoofdtekst.",
    ],
    hollow: [
        "Een kop gezet",
        "hol",
        ", of",
        "verdikt",
        " zonder een vettere letter",
    ],
    rules: [
        "Een lijn kan staan waar ze moet:",
        "een zware onderstreping",
        " vrij van de onderstokken, of",
        "een haarlijn",
        " door de letters.",
    ],
    wrapped: "Een kenmerk afgebroken na zijn schuine strepen, en gesneden waar niets anders kan:",
    centred: "Deze alinea is gecentreerd, in de breedte en de hoogte, in het kader eromheen.",
    measured: "{count} regels, samen {tall} pt hoog, de breedste {wide} pt breed.",
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Texto rico: estilos, tamanhos, sublinhado, cor",
    due: [
        "O montante em dívida é",
        ", pagável no prazo de trinta dias. O saldo vence juros à taxa legal desde o vencimento, sem necessidade de enviar qualquer aviso.",
    ],
    tallest: [
        "Uma linha é tão alta como",
        "o maior",
        " dos estilos que leva, e não mais.",
    ],
    coloured: [
        "Um troço pode levar a sua própria",
        "cor",
        ", separada do preto à volta.",
    ],
    joined: [
        "Uma palavra pode mudar de estilo a meio: sub",
        "linhado",
        " continua a ser uma palavra, e nunca se parte na junção.",
    ],
    small: [
        "As letras miudinhas vão em corpo pequeno,",
        "alinhadas à direita",
        ", por baixo do corpo do texto.",
    ],
    hollow: [
        "Um título composto",
        "oco",
        ", ou",
        "engrossado",
        " sem um tipo de letra mais negro",
    ],
    rules: [
        "Um filete pode ficar onde se lhe diz:",
        "um sublinhado grosso",
        " livre das descendentes, ou",
        "um filete fino",
        " através das letras.",
    ],
    wrapped: "Uma referência partida depois das barras, e cortada onde não há outra forma:",
    centred: "Este parágrafo está centrado, na largura e na altura, na caixa desenhada à sua volta.",
    measured: "{count} linhas, {tall} pt de altura no total, a mais larga com {wide} pt.",
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Testo ricco: stili, corpi, sottolineatura, colore",
    due: [
        "L’importo dovuto è",
        ", pagabile entro trenta giorni. Il saldo produce interessi al tasso legale dalla scadenza, senza bisogno di alcun sollecito.",
    ],
    tallest: [
        "Una riga è alta quanto",
        "il più grande",
        " degli stili che porta, e non di più.",
    ],
    coloured: [
        "Un tratto può portare il proprio",
        "colore",
        ", separato dal nero che lo circonda.",
    ],
    joined: [
        "Una parola può cambiare stile a metà: sotto",
        "lineato",
        " resta una parola, e non si spezza mai alla giunzione.",
    ],
    small: [
        "Le clausole minori stanno in corpo piccolo,",
        "allineate a destra",
        ", sotto il corpo del testo.",
    ],
    hollow: [
        "Un titolo composto",
        "vuoto",
        ", o",
        "ispessito",
        " senza un font più nero",
    ],
    rules: [
        "Un filetto può stare dove gli si dice:",
        "una sottolineatura spessa",
        " libera dai discendenti, o",
        "un filetto sottile",
        " attraverso le lettere.",
    ],
    wrapped: "Un riferimento spezzato dopo le barre, e tagliato dove non c’è altro modo:",
    centred: "Questo paragrafo è centrato, in larghezza e in altezza, nel riquadro disegnato intorno.",
    measured: "{count} righe, alte {tall} pt in tutto, la più larga di {wide} pt.",
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Texto enriquecido: estilos, tamaños, subrayado, color",
    due: [
        "El importe a pagar es ",
        ", pagadero en treinta días. El saldo devenga intereses al tipo legal desde su vencimiento, sin necesidad de enviar ningún recordatorio.",
    ],
    tallest: [
        "Una línea es tan alta como ",
        "el mayor",
        " de los estilos que lleva, y no más.",
    ],
    coloured: [
        "Un tramo puede llevar su propio ",
        "color",
        ", separado del negro que lo rodea.",
    ],
    joined: [
        "Una palabra puede cambiar de estilo a mitad: sub",
        "rayado",
        " sigue siendo una palabra, y nunca se corta en la unión.",
    ],
    small: [
        "La letra pequeña va en cuerpo pequeño, ",
        "alineada a la derecha",
        ", bajo el cuerpo del texto.",
    ],
    hollow: [
        "Un título compuesto ",
        "hueco",
        ", o ",
        "engrosado",
        " sin una fuente más negra",
    ],
    rules: [
        "Una raya puede ir donde se le diga: ",
        "un subrayado grueso",
        " libre de los descendentes, o ",
        "un filete",
        " a través de las letras.",
    ],
    wrapped: "Una referencia cortada tras sus barras, y partida donde no queda otra:",
    centred: "Este párrafo está centrado, a lo ancho y a lo alto, en la caja dibujada a su alrededor.",
    measured: "{count} líneas, {tall} pt de alto en total, la más ancha de {wide} pt.",
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Formatierter Text: Stile, Größen, Unterstreichung, Farbe",
    due: [
        "Der fällige Betrag ist ",
        ", zahlbar binnen dreißig Tagen. Der Restbetrag wird ab Fälligkeit zum gesetzlichen Zinssatz verzinst, ohne dass dafür eine Mahnung nötig ist.",
    ],
    tallest: [
        "Eine Zeile ist so hoch wie ",
        "der größte",
        " der Stile, die auf ihr stehen, und nicht höher.",
    ],
    coloured: [
        "Ein Abschnitt kann seine eigene ",
        "Farbe",
        " tragen, abgesetzt vom Schwarz ringsum.",
    ],
    joined: [
        "Ein Wort darf mitten im Wort den Stil wechseln: unter",
        "strichen",
        " bleibt ein Wort und wird an der Naht nie getrennt.",
    ],
    small: [
        "Das Kleingedruckte steht in kleiner Schrift, ",
        "rechtsbündig",
        ", unter dem Haupttext.",
    ],
    hollow: [
        "Eine Überschrift, ",
        "hohl",
        " gesetzt oder ",
        "verstärkt",
        " ohne fettere Schrift",
    ],
    rules: [
        "Eine Linie kann stehen, wo man sie hinstellt: ",
        "eine kräftige Unterstreichung",
        " frei von den Unterlängen, oder ",
        "eine Haarlinie",
        " durch die Buchstaben.",
    ],
    wrapped: "Eine Referenz, nach ihren Schrägstrichen umbrochen und dort getrennt, wo nichts anderes geht:",
    centred: "Dieser Absatz ist in dem um ihn gezeichneten Rahmen waagrecht und senkrecht zentriert.",
    measured: "{count} Zeilen, zusammen {tall} pt hoch, die breiteste {wide} pt breit.",
};

/// 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),
];

/// Sets the blocks under the first five from `top` down: the hollow and
/// thickened heading, the rules set where they are told, the reference broken
/// in a narrow box, and the paragraph centred in a box with what its lines
/// measure; hands back where the last of them ends.
fn more(
    content: &mut Content,
    text: &FontHandle,
    words: &Words,
    mut top: f64,
) -> Result<f64, hqf_pdf::Error> {
    let regular = Style::new(text, 11.0);
    let small = Style::new(text, 8.0);
    let ink = Rgb::new(0.0, 0.0, 0.0);
    let hollow = Style::new(text, 17.0).outline(0.6, ink);
    let thickened = Style::new(text, 17.0)
        .color(Rgb::new(0.0, 0.35, 0.7))
        .filled_outline(0.8, Rgb::new(0.0, 0.2, 0.45));
    let heading = Style::new(text, 17.0);
    // A heavy underline four points under the baseline, and a hairline three
    // points over it.
    let heavy = Style::new(text, 11.0).underline_at(-4.0, 1.5);
    let hairline = Style::new(text, 11.0).strikethrough_at(3.0, 0.4);
    let blocks_under = [
        RichText::new()
            .span(words.hollow[0], &heading)
            .span(words.hollow[1], &hollow)
            .span(words.hollow[2], &heading)
            .span(words.hollow[3], &thickened)
            .span(words.hollow[4], &heading),
        RichText::new()
            .span(words.rules[0], &regular)
            .span(words.rules[1], &heavy)
            .span(words.rules[2], &regular)
            .span(words.rules[3], &hairline)
            .span(words.rules[4], &regular),
        RichText::new().span(words.wrapped, &regular),
    ];
    for block in &blocks_under {
        let lines = block.break_lines(WIDTH);
        block.draw(content, &lines, LEFT, top, WIDTH)?;
        top -= RichText::height(&lines) + GAP / 2.0;
    }

    let reference = RichText::new()
        .overlong(Overlong::Break)
        .cut_mark(Some('-'))
        .break_after("/")
        .span(REFERENCE, &regular);
    let lines = reference.break_lines(NARROW);
    reference.draw(content, &lines, LEFT, top, NARROW)?;
    top -= RichText::height(&lines) + GAP;

    content.save_state();
    content
        .set_stroke_rgb(0.7, 0.7, 0.7)?
        .set_line_width(0.5)?
        .rect(LEFT, top - BOX_HEIGHT, WIDTH, BOX_HEIGHT)?
        .stroke();
    content.restore_state();
    let centred = RichText::new()
        .align(Align::Center)
        .span(words.centred, &regular);
    let inside = WIDTH - 40.0;
    let lines = centred.break_lines(inside);
    let from = RichText::top_for(&lines, top, BOX_HEIGHT, VAlign::Middle);
    centred.draw(content, &lines, LEFT + 20.0, from, inside)?;
    top -= BOX_HEIGHT + 14.0;

    let holding = lines.iter().filter(|line| !line.is_empty()).count();
    let together: f64 = lines.iter().map(RichLine::height).sum();
    let widest = lines
        .iter()
        .map(RichLine::natural_width)
        .fold(0.0, f64::max);
    let said = words
        .measured
        .replace("{count}", &holding.to_string())
        .replace("{tall}", &format!("{together:.0}"))
        .replace("{wide}", &format!("{widest:.0}"));
    let caption = RichText::new().span(&said, &small);
    let lines = caption.break_lines(WIDTH);
    caption.draw(content, &lines, LEFT, top, WIDTH)?;
    Ok(top - RichText::height(&lines))
}

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("rich")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let font = Font::parse(fs::read(&font_path)?)?;
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let text = doc.add_font(font);

    let regular = Style::new(&text, 11.0);
    let small = Style::new(&text, 8.0);
    let large = Style::new(&text, 17.0);
    let marked = Style::new(&text, 11.0).underline();
    let accent = Style::new(&text, 11.0).color(Rgb::new(0.0, 0.35, 0.7));

    let blocks = vec![
        RichText::new()
            .align(Align::Justify)
            .span(words.due[0], &regular)
            .span(AMOUNT, &marked)
            .span(words.due[1], &regular),
        RichText::new()
            .span(words.tallest[0], &regular)
            .span(words.tallest[1], &large)
            .span(words.tallest[2], &regular),
        RichText::new()
            .span(words.coloured[0], &regular)
            .span(words.coloured[1], &accent)
            .span(words.coloured[2], &regular),
        RichText::new()
            .span(words.joined[0], &regular)
            .span(words.joined[1], &marked)
            .span(words.joined[2], &regular),
        RichText::new()
            .align(Align::Right)
            .span(words.small[0], &small)
            .span(words.small[1], &small)
            .span(words.small[2], &small),
    ];

    let mut content = Content::new();
    content.begin_text();
    content.set_font(&text, 14.0)?;
    content.text_origin(LEFT, TOP + 24.0)?;
    content.show_glyphs(&text.glyphs(words.title));
    content.end_text();

    let mut top = TOP;
    for block in &blocks {
        let lines = block.break_lines(WIDTH);
        block.draw(&mut content, &lines, LEFT, top, WIDTH)?;
        top -= RichText::height(&lines) + GAP;
    }

    more(&mut content, &text, words, top)?;

    let mut page = Page::a4();
    page.content = content.into_bytes();
    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, {} blocks",
        bytes.len(),
        blocks.len()
    );
    Ok(())
}

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

    /// The lines two languages are allowed to write the same way. Every
    /// paragraph here is a sentence, and no two languages write one alike.
    const SPARED: [&str; 0] = [];

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

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

    /// The fourth paragraph exists to show that a word whose halves are set in
    /// two styles is still one word. A language that gives the underlined run a
    /// word of its own shows nothing, and the page reads as if the run had been
    /// emphasised in the ordinary way.
    #[test]
    fn every_language_turns_a_word_underlined_halfway_through() {
        for (language, words) in WORDS {
            let [before, run, after] = words.joined;
            let code = language.code();
            assert!(
                !before.ends_with(' '),
                "{code} starts the underlined run on a word of its own"
            );
            assert!(
                !run.starts_with(' ') && !run.ends_with(' '),
                "{code} pads the underlined run with spaces"
            );
            assert!(
                after.starts_with(' '),
                "{code} carries the word on past the underlining"
            );
        }
    }
}