write_stencil_pattern.rs

Die Rust-Datei des Beispiels „Eine Schraffur, in jeder gewünschten Farbe aufgetragen“. Ein Muster ohne eigene Farbe, in fünf Farben und in fünf Stärken einer Druckfarbe der Maschine aufgetragen: Die Füllung sagt, in welcher Farbe es aufgetragen wird. Daneben dieselbe Schraffur aus Mustern mit eigenen Farben, also ein Muster pro Farbe.

Rust 696 Zeilen

Wofür dieses Beispiel da ist

Eine technische Zeichnung schraffiert jedes Material anders; eine Karte füllt jede Zone mit einem Farbton. Beides läuft auf eine Handvoll Formen hinaus, tausendfach in einem Dutzend Farben wiederholt — und der gewöhnliche Weg legt für jede Farbe, in der die Form vorkommt, eine eigene Kopie davon in die Datei.

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
//! One hatch, drawn once, laid down in as many colours as the page asks for.
//!
//! A tiling pattern usually states its own colours, so a hatch in five colours
//! is five patterns. A pattern built with `uncolored` states none: the cell
//! says only what shape is laid down, and the colour comes from the fill. The
//! page below lays one such cell down in five colours and in five strengths of
//! one ink, and then shows what the ordinary kind costs beside it.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is written in. What a swatch is painted with is not
//! language: the numbers under the first row are the ones the stream states,
//! and the ink of the second row travels under the name a press knows it by.
//!
//! Usage: `cargo run --example write_stencil_pattern -- tmp/stencil.pdf
//! [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_stencil_pattern --
//! tmp/pochoir.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::{
    Cmyk, Color, ColorSpace, ColorSpaceHandle, DeviceSpace, Document, Error, Font, FontHandle,
    Page, PatternHandle, PatternSpace, Rect, Rgb, Separation, TilingPattern,
};

#[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 everything.
const LEFT: f64 = 70.0;

/// The side of one cell of the hatch.
const CELL: f64 = 10.0;

/// Half the height of one band of the hatch, measured up the page.
const BAND: f64 = 1.6;

/// How far behind the cell's box a band starts, and how far past it it runs:
/// the box is what cuts them, so the ends fall outside it.
const BEHIND: f64 = -CELL;
/// See [`BEHIND`].
const BEYOND: f64 = CELL + CELL;

/// The five colours the one stencil is laid down in, each under the numbers the
/// fill states it as: what is written under a swatch is what the stream says.
const COLORS: &[([f64; 3], &str)] = &[
    ([0.12, 0.28, 0.52], "0.12 0.28 0.52"),
    ([0.16, 0.45, 0.35], "0.16 0.45 0.35"),
    ([0.78, 0.30, 0.24], "0.78 0.3 0.24"),
    ([0.55, 0.35, 0.62], "0.55 0.35 0.62"),
    ([0.20, 0.20, 0.20], "0.2 0.2 0.2"),
];

/// The five strengths the one stencil is laid down in as an ink.
const TINTS: &[f64] = &[0.15, 0.35, 0.55, 0.75, 1.0];

/// The three colours the ordinary kind of pattern needs a cell of its own for.
const OWN: &[[f64; 3]] = &[[0.12, 0.28, 0.52], [0.78, 0.30, 0.24], [0.16, 0.45, 0.35]];

/// The ink the strengths of the second row are laid down in, which is a name a
/// press knows the ink by rather than a word a language writes.
const INK: &str = "Corporate Blue";

/// The words the page is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title over the page.
    title: &'static str,
    /// The two lines under the title.
    intro: [&'static str; 2],
    /// The heading of each of the three panels, and the line under it.
    panels: [[&'static str; 2]; 3],
    /// What stands in front of the strength on the label of a tinted swatch.
    tint_label: &'static str,
    /// What is written under each of the three swatches whose pattern carries
    /// its own colour.
    own: [&'static str; 3],
    /// The three lines of the closing note.
    closing: [&'static str; 3],
}

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

    /// What is written under the swatch laid down at `tint`.
    fn tint(&self, tint: f64) -> String {
        format!("{}{tint}", self.tint_label)
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "One hatch, laid down in as many colours as the page asks for",
    intro: [
        "The first ten swatches below are one cell. It states no colour: the fill says what colour \
         to lay",
        "it down in, and the space the fill is stated in says what those numbers mean.",
    ],
    panels: [
        [
            "Five colours, one cell",
            "The colour is {n} numbers in DeviceRGB, and the pattern is named beside them.",
        ],
        [
            "The same cell, through one ink",
            "The same pattern, through a space whose one number is how much ink the press lays \
             down.",
        ],
        [
            "What a cell that carries its own colours costs",
            "Nothing is said at the fill, so each colour of the hatch is a cell of its own in the \
             file.",
        ],
    ],
    tint_label: "tint ",
    own: ["one cell", "a second cell", "a third cell"],
    closing: [
        "Thirteen swatches, four cells: one for the ten above, and one apiece for the three that \
         carry",
        "their own colours. Changing the hatch itself is changing one cell in the first two rows \
         and",
        "three in the last.",
    ],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "Une hachure, dans autant de couleurs que la page en demande",
    intro: [
        "Les dix premières pastilles sont une seule case. Elle ne fixe aucune couleur : \
le remplissage dit",
        "dans quelle couleur la poser, et l’espace où il est exprimé donne le sens de ces nombres.",
    ],
    panels: [
        [
            "Cinq couleurs, une seule cellule",
            "La couleur tient en {n} nombres DeviceRGB, et le motif est nommé à côté.",
        ],
        [
            "La même cellule, avec une seule encre",
            "Le même motif, dans un espace dont l’unique nombre est la quantité d’encre que \
pose la presse.",
        ],
        [
            "Ce que coûte une cellule qui fixe ses propres couleurs",
            "Le remplissage ne dit rien : chaque couleur de la hachure est donc une \
cellule à part dans le fichier.",
        ],
    ],
    tint_label: "teinte ",
    own: ["une case", "une deuxième case", "une troisième case"],
    closing: [
        "Treize pastilles, quatre cases : une pour les dix du haut, et une pour chacune \
des trois qui",
        "fixent leurs propres couleurs. Changer la hachure, c’est changer une case dans \
les deux premières",
        "rangées et trois dans la dernière.",
    ],
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Eén arcering, neergelegd in zoveel kleuren als de pagina vraagt",
    intro: [
        "De eerste tien stalen hieronder zijn één cel. Ze noemt geen kleur: de vulling zegt in welke kleur ze",
        "neergelegd wordt, en de ruimte waarin de vulling gegeven wordt, zegt wat die getallen betekenen.",
    ],
    panels: [
        [
            "Vijf kleuren, één cel",
            "De kleur is {n} getallen in DeviceRGB, en het patroon wordt ernaast genoemd.",
        ],
        [
            "Dezelfde cel, via één inkt",
            "Hetzelfde patroon, via een ruimte waarvan het ene getal is hoeveel inkt de pers neerlegt.",
        ],
        [
            "Wat een cel kost die haar eigen kleuren bevat",
            "Bij de vulling wordt niets gezegd, dus elke kleur van de arcering is een eigen cel in het bestand.",
        ],
    ],
    tint_label: "tint",
    own: ["één cel", "een tweede cel", "een derde cel"],
    closing: [
        "Dertien stalen, vier cellen: één voor de tien hierboven, en één voor elk van de drie die hun",
        "eigen kleuren bevatten. De arcering zelf veranderen is één cel veranderen in de eerste twee rijen en",
        "drie in de laatste.",
    ],
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Um tracejado, posto em tantas cores quantas a página pedir",
    intro: [
        "As primeiras dez amostras abaixo são uma célula. Não indica cor: o preenchimento diz em que cor",
        "a pôr, e o espaço em que o preenchimento é dado diz o que esses números significam.",
    ],
    panels: [
        [
            "Cinco cores, uma célula",
            "A cor são {n} números em DeviceRGB, e o padrão é nomeado ao lado.",
        ],
        [
            "A mesma célula, através de uma tinta",
            "O mesmo padrão, num espaço cujo único número é quanta tinta a máquina põe.",
        ],
        [
            "O que custa uma célula que leva as suas próprias cores",
            "No preenchimento não se diz nada, por isso cada cor do tracejado é uma célula própria no ficheiro.",
        ],
    ],
    tint_label: "tom",
    own: ["uma célula", "uma segunda célula", "uma terceira célula"],
    closing: [
        "Treze amostras, quatro células: uma para as dez acima, e uma para cada uma das três que levam",
        "as suas próprias cores. Mudar o tracejado em si é mudar uma célula nas duas primeiras filas e",
        "três na última.",
    ],
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "Un tratteggio, steso in tanti colori quanti ne chiede la pagina",
    intro: [
        "I primi dieci campioni qui sotto sono una cella. Non indica colore: il riempimento dice in che colore",
        "stenderla, e lo spazio in cui è dato il riempimento dice cosa significano quei numeri.",
    ],
    panels: [
        [
            "Cinque colori, una cella",
            "Il colore sono {n} numeri in DeviceRGB, e il motivo è nominato accanto.",
        ],
        [
            "La stessa cella, attraverso un inchiostro",
            "Lo stesso motivo, in uno spazio il cui unico numero è quanto inchiostro stende la macchina.",
        ],
        [
            "Quanto costa una cella che porta i propri colori",
            "Nel riempimento non si dice nulla, così ogni colore del tratteggio è una cella propria nel file.",
        ],
    ],
    tint_label: "tinta",
    own: ["una cella", "una seconda cella", "una terza cella"],
    closing: [
        "Tredici campioni, quattro celle: una per i dieci qui sopra, e una per ciascuno dei tre che portano",
        "i propri colori. Cambiare il tratteggio stesso è cambiare una cella nelle prime due righe e",
        "tre nell’ultima.",
    ],
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "Un rayado, puesto en tantos colores como pida la página",
    intro: [
        "Las diez primeras muestras de abajo son una celda. No indica color: el relleno dice en qué color",
        "ponerla, y el espacio en que se da el relleno dice qué significan esos números.",
    ],
    panels: [
        [
            "Cinco colores, una celda",
            "El color son {n} números en DeviceRGB, y el patrón se nombra a su lado.",
        ],
        [
            "La misma celda, con una tinta",
            "El mismo patrón, en un espacio cuyo único número es cuánta tinta pone la prensa.",
        ],
        [
            "Lo que cuesta una celda que lleva sus propios colores",
            "En el relleno no se dice nada, así que cada color del rayado es una celda propia en el archivo.",
        ],
    ],
    tint_label: "tono",
    own: ["una celda", "una segunda celda", "una tercera celda"],
    closing: [
        "Trece muestras, cuatro celdas: una para las diez de arriba, y una por cada una de las tres que llevan",
        "sus propios colores. Cambiar el rayado mismo es cambiar una celda en las dos primeras filas y",
        "tres en la última.",
    ],
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Eine Schraffur, in so vielen Farben, wie die Seite verlangt",
    intro: [
        "Die ersten zehn Farbfelder unten sind eine einzige Zelle. Sie nennt keine Farbe: Die Füllung",
        "sagt, in welcher Farbe sie aufzutragen ist, und ihr Farbraum sagt, was diese Zahlen bedeuten.",
    ],
    panels: [
        [
            "Fünf Farben, eine Zelle",
            "Die Farbe sind {n} Zahlen in DeviceRGB, und das Muster ist daneben genannt.",
        ],
        [
            "Dieselbe Zelle, über eine Farbe",
            "Dasselbe Muster, in einem Farbraum, dessen eine Zahl die aufgetragene Farbmenge ist.",
        ],
        [
            "Was eine Zelle kostet, die ihre eigenen Farben trägt",
            "Die Füllung sagt nichts, also ist jede Farbe der Schraffur eine eigene Zelle der Datei.",
        ],
    ],
    tint_label: "Tonwert ",
    own: ["eine Zelle", "eine zweite Zelle", "eine dritte Zelle"],
    closing: [
        "Dreizehn Farbfelder, vier Zellen: eine für die zehn oben und je eine für die drei, die ihre",
        "eigenen Farben tragen. Die Schraffur selbst zu ändern heißt, eine Zelle in den ersten beiden",
        "Reihen zu ändern und drei in der letzten.",
    ],
};

/// 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 size of one swatch of the first two rows, and the gap to the next.
const SWATCH: (f64, f64) = (83.0, 105.0);
/// See [`SWATCH`].
const SWATCH_GAP: f64 = 10.0;

/// The width of one swatch of the last row, which holds three rather than five.
const WIDE: f64 = 145.0;

/// Draws one line of text with its baseline at `(x, y)`.
fn text(
    content: &mut Content,
    font: &FontHandle,
    size: f64,
    x: f64,
    y: f64,
    line: &str,
) -> Result<(), Error> {
    content.begin_text();
    content.set_font(font, size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// Lays the bands of the hatch into `cell`, three of them so that the corners
/// carry the halves the middle band leaves out and the plane runs unbroken.
fn hatch(cell: &mut Content) -> Result<(), Error> {
    for offset in [-CELL, 0.0, CELL] {
        let near = BEHIND + offset;
        let far = BEYOND + offset;
        cell.move_to(BEHIND, near - BAND)?;
        cell.line_to(BEYOND, far - BAND)?;
        cell.line_to(BEYOND, far + BAND)?;
        cell.line_to(BEHIND, near + BAND)?;
        cell.close_path().fill();
    }
    Ok(())
}

/// The hatch as a cell that states no colour of its own.
fn stencil() -> Result<TilingPattern, Error> {
    let mut cell = Content::new();
    hatch(&mut cell)?;
    Ok(TilingPattern::new(cell, Rect::new(0.0, 0.0, CELL, CELL), (CELL, CELL))?.uncolored())
}

/// The same hatch as a cell that carries `color`.
fn carried(color: [f64; 3]) -> Result<TilingPattern, Error> {
    let mut cell = Content::new();
    cell.set_fill(Rgb::new(color[0], color[1], color[2]))?;
    hatch(&mut cell)?;
    TilingPattern::new(cell, Rect::new(0.0, 0.0, CELL, CELL), (CELL, CELL))
}

/// Lays the paper of a swatch down and frames it once whatever fills it has
/// been painted.
fn paper(content: &mut Content, x: f64, y: f64, width: f64) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.97))?;
    content.rect(x, y, width, SWATCH.1)?.fill();
    content.restore_state();
    Ok(())
}

/// Frames a swatch and writes what is under it.
fn frame(
    content: &mut Content,
    font: &FontHandle,
    corner: (f64, f64),
    width: f64,
    label: &str,
) -> Result<(), Error> {
    let (x, y) = corner;
    content.save_state();
    content.set_stroke(Color::Gray(0.55))?;
    content.set_line_width(0.6)?;
    content.rect(x, y, width, SWATCH.1)?.stroke();
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, 8.0, x, y - 12.0, label)?;
    content.restore_state();
    Ok(())
}

/// Draws one panel's heading, with the line under it.
fn panel_heading(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    title: &str,
    under: &str,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.2))?;
    text(content, font, 11.0, LEFT, y, title)?;
    content.set_fill(Color::Gray(0.45))?;
    text(content, font, 8.0, LEFT, y - 15.0, under)?;
    content.restore_state();
    Ok(())
}

/// Lays the one stencil down five times across, each swatch in the colour
/// beside it.
fn in_colors(
    content: &mut Content,
    font: &FontHandle,
    space: &ColorSpaceHandle,
    stencil: &PatternHandle,
) -> Result<(), Error> {
    let mut x = LEFT;
    for (color, label) in COLORS {
        paper(content, x, 570.0, SWATCH.0)?;
        content.save_state();
        content.set_fill_space(space);
        content.set_fill_pattern_components(color, stencil)?;
        content.set_stroke_space(space);
        content.set_stroke_pattern_components(color, stencil)?;
        content.set_line_width(4.0)?;
        content
            .rect(x, 570.0, SWATCH.0, SWATCH.1)?
            .fill_and_stroke();
        content.restore_state();
        frame(content, font, (x, 570.0), SWATCH.0, label)?;
        x += SWATCH.0 + SWATCH_GAP;
    }
    Ok(())
}

/// Lays the same stencil down five times across, each swatch a strength of the
/// one ink.
fn in_tints(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    space: &ColorSpaceHandle,
    stencil: &PatternHandle,
) -> Result<(), Error> {
    let mut x = LEFT;
    for tint in TINTS {
        paper(content, x, 379.0, SWATCH.0)?;
        content.save_state();
        content.set_fill_space(space);
        content.set_fill_pattern_components(&[*tint], stencil)?;
        content.rect(x, 379.0, SWATCH.0, SWATCH.1)?.fill();
        content.restore_state();
        frame(content, font, (x, 379.0), SWATCH.0, &words.tint(*tint))?;
        x += SWATCH.0 + SWATCH_GAP;
    }
    Ok(())
}

/// Lays down three patterns that carry their own colours, one swatch each.
fn in_their_own(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    patterns: &[PatternHandle],
) -> Result<(), Error> {
    let mut x = LEFT;
    for (pattern, label) in patterns.iter().zip(words.own) {
        paper(content, x, 188.0, WIDE)?;
        content.save_state();
        content.set_fill_pattern(pattern);
        content.rect(x, 188.0, WIDE, SWATCH.1)?.fill();
        content.restore_state();
        frame(content, font, (x, 188.0), WIDE, label)?;
        x += WIDE + SWATCH_GAP;
    }
    Ok(())
}

/// Draws the title and the two lines saying what the page is showing.
fn heading(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    text(content, font, 15.0, LEFT, 780.0, words.title)?;
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    text(content, font, 10.0, LEFT, 762.0, words.intro[0])?;
    text(content, font, 10.0, LEFT, 748.0, words.intro[1])?;
    content.restore_state();
    Ok(())
}

/// Draws the closing note.
fn closing(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    for (y, line) in [130.0, 116.0, 102.0].iter().zip(words.closing) {
        text(content, font, 9.0, LEFT, *y, line)?;
    }
    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("stencil")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

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

    let stencil = doc.add_tiling_pattern(stencil()?);
    let rgb_under = PatternSpace::new(ColorSpace::Device(DeviceSpace::Rgb))?;
    let under = rgb_under.base().components();
    let in_rgb = doc.add_color_space(ColorSpace::Pattern(rgb_under));
    let in_ink = doc.add_color_space(PatternSpace::new(Separation::ink(
        INK,
        Cmyk::new(0.9, 0.55, 0.0, 0.05),
    ))?);
    let own: Vec<PatternHandle> = OWN
        .iter()
        .map(|color| carried(*color).map(|pattern| doc.add_tiling_pattern(pattern)))
        .collect::<Result<_, _>>()?;

    let mut content = Content::new();
    heading(&mut content, &font, words)?;

    let [colors, tints, their_own] = words.panels;
    panel_heading(
        &mut content,
        &font,
        706.0,
        colors[0],
        &colors[1].replace("{n}", &under.to_string()),
    )?;
    in_colors(&mut content, &font, &in_rgb, &stencil)?;

    panel_heading(&mut content, &font, 515.0, tints[0], tints[1])?;
    in_tints(&mut content, &font, words, &in_ink, &stencil)?;

    panel_heading(&mut content, &font, 324.0, their_own[0], their_own[1])?;
    in_their_own(&mut content, &font, words, &own)?;
    closing(&mut content, &font, words)?;

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

    let written = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &written)?;
    println!(
        "wrote {out}: {} bytes, {} swatches from {} cells",
        written.len(),
        COLORS.len() + TINTS.len() + OWN.len(),
        own.len() + 1
    );
    Ok(())
}

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

    use super::{
        COLORS, LEFT, OWN, SWATCH, SWATCH_GAP, TINTS, WIDE, WORDS, default_font, language,
    };

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

    /// A4's width, and the room a line that stands over the whole page has.
    const PAGE_WIDTH: f64 = 595.276;
    /// See [`PAGE_WIDTH`].
    const PAPER: f64 = PAGE_WIDTH - LEFT;

    /// The room a caption under one of the narrow swatches has: the swatch, and
    /// the gap to the one beside it.
    const NARROW_ROOM: f64 = SWATCH.0 + SWATCH_GAP;
    /// The same, under one of the wide swatches of the last row.
    const WIDE_ROOM: f64 = WIDE + SWATCH_GAP;

    /// How many swatches the page lays down, and out of how many cells: the
    /// closing note spells both out in words, and no language can work them out
    /// from the page.
    const SWATCHES: usize = 13;
    /// See [`SWATCHES`].
    const CELLS: usize = 4;

    #[test]
    fn every_language_draws_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:?}"
        );
    }

    /// Nothing on the page is broken to a width: a caption longer than the
    /// swatch it stands under runs into the one beside it, and a line that
    /// stands over nothing runs off the sheet.
    #[test]
    fn every_language_writes_lines_no_wider_than_the_room_they_are_given() {
        let mut doc = Document::new();
        let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
            .expect("the committed font parses");
        let text = doc.add_font(font);

        for (named, words) in WORDS {
            let code = named.code();
            let lines = std::iter::once((15.0, words.title.to_owned(), PAPER))
                .chain(words.intro.map(|line| (10.0, line.to_owned(), PAPER)))
                .chain(words.panels.map(|panel| (11.0, panel[0].to_owned(), PAPER)))
                .chain(words.panels.map(|panel| (8.0, panel[1].to_owned(), PAPER)))
                .chain(words.closing.map(|line| (9.0, line.to_owned(), PAPER)))
                .chain(
                    TINTS
                        .iter()
                        .map(|tint| (8.0, words.tint(*tint), NARROW_ROOM)),
                )
                .chain(words.own.map(|line| (8.0, line.to_owned(), WIDE_ROOM)));

            for (size, line, room) in lines {
                let measured = text.measure(&line, size);
                assert!(
                    measured <= room,
                    "the {code} page draws {line:?} over {measured:.1} points, \
                     and it is given {room:.1}"
                );
            }
        }
    }

    /// The closing note counts the swatches and the cells in words, which no
    /// language reads off the page: a row added or dropped leaves every one of
    /// them saying a number the page no longer shows.
    #[test]
    fn the_page_lays_down_the_swatches_its_closing_note_counts() {
        assert_eq!(COLORS.len() + TINTS.len() + OWN.len(), SWATCHES);
        assert_eq!(OWN.len() + 1, CELLS);
    }
}