write_true_to_scale.rs

Die Rust-Datei des Beispiels „Ein Blatt, das misst, was es angibt“. Drei Lineale — Zentimeter, Zoll und Punkt — auf einer Seite, die dem, was sie druckt, sagt, sie genau in der gezeichneten Größe auszugeben und nichts anderes anzubieten. Legen Sie ein Maßband an den gedruckten Bogen, und Sie können es selbst prüfen.

Rust 645 Zeilen

Wofür dieses Beispiel da ist

Drucken Sie etwas, das gemessen werden soll — ein Schnittmuster, einen Plan, eine maßstäbliche Zeichnung —, und das Druckfenster verkleinert es stillschweigend um einige Prozent, um die eigenen Ränder des Druckers freizuhalten. Niemand sieht es geschehen. Die Seite sieht richtig aus; das darauf gedruckte Lineal ist einfach falsch, und das Teil, das jemand nach diesem Maß schneidet, kommt in der falschen Größe zurück.

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
//! A sheet that measures what it says, and asks not to be resized.
//!
//! A drawing printed to be measured is worth nothing if the printer shrinks it
//! to fit its own margins. This page carries three rules — centimetres, inches
//! and points — and states, in the file itself, that it is to print at the size
//! it was drawn and that reading software is not to offer anything else. That
//! last part arrived with PDF 2.0, so the file declares 2.0: nothing is raised
//! on the caller's behalf, and a file that asked for it while declaring less
//! would be refused rather than written.
//!
//! It shows the two other things a caller decides about the file rather than
//! about its pages: how hard its streams are squeezed, and where the bytes go —
//! here straight into the file, a piece at a time, rather than into memory
//! first.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is captioned in. What a rule is called is not one of
//! them: the length is worked out from the rule itself and only the unit is a
//! word, so no language can name a rule a length it does not run. The entries
//! set beside what the file asks for are not words either — they are what the
//! file writes, spelled the same way whoever reads the page.
//!
//! Usage: `cargo run --example write_true_to_scale -- tmp/scale.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_true_to_scale --
//! tmp/echelle.pdf`

use std::env;
use std::fs::{self, File};
use std::io::BufWriter;
use std::path::{Path, PathBuf};

use hqf_pdf::content::Content;
use hqf_pdf::{
    Color, Compression, Document, Error, Font, FontHandle, OpenAction, Page, PageFit, Rgb, Version,
    ViewerPreferences,
};

#[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")
}

/// A4, in points.
const SHEET: (f64, f64) = (595.276, 841.890);

/// How far in from the edge of the sheet everything is set.
const MARGIN: f64 = 64.0;

/// How far in from the left edge the entries the file writes stand, leaving the
/// asking to their left.
const ENTRY: f64 = 290.0;

/// One centimetre, in points.
const CM: f64 = 72.0 / 2.54;

/// One inch, in points.
const INCH: f64 = 72.0;

/// A rule laid across the page.
struct Rule {
    /// How far apart the ticks stand, in points.
    step: f64,
    /// How many steps the rule runs for.
    steps: usize,
    /// Every so many ticks stands tall and carries a number.
    tall: usize,
    /// What one step is worth in the unit the rule is named for.
    worth: usize,
}

/// The three rules, from the top of the page down.
const RULES: [(f64, Rule); 3] = [
    (
        590.0,
        Rule {
            step: CM,
            steps: 16,
            tall: 1,
            worth: 1,
        },
    ),
    (
        500.0,
        Rule {
            step: INCH,
            steps: 6,
            tall: 1,
            worth: 1,
        },
    ),
    (
        410.0,
        Rule {
            step: 10.0,
            steps: 20,
            tall: 5,
            worth: 10,
        },
    ),
];

/// The entries the file writes to ask for what it asks. They are read off the
/// file rather than off the page, and stand the same way in every language.
const WRITTEN: [&str; 3] = [
    "/PrintScaling /None",
    "/Enforce [ /PrintScaling ]",
    "/OpenAction [ page /Fit ]",
];

/// The words the page is set in, one set per language.
#[derive(Debug)]
struct Words {
    /// The title in the band across the head of the page.
    title: &'static str,
    /// The three lines under the band.
    intro: [&'static str; 3],
    /// The unit each of the three rules measures in. The length itself is
    /// worked out from the rule, so a rule cannot be named a length it does not
    /// run.
    units: [&'static str; 3],
    /// The heading over what the file asks for.
    asks: &'static str,
    /// What the file asks for, one line per entry of [`WRITTEN`].
    asked: [&'static str; 3],
    /// The two closing paragraphs, set with a blank line between them.
    closing: ([&'static str; 3], [&'static str; 4]),
}

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

    /// What the rule at `index` is called: the length it runs, then the unit it
    /// runs in.
    fn rule_name(&self, index: usize, spec: &Rule) -> String {
        format!("{} {}", spec.steps * spec.worth, self.units[index])
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "True to scale",
    intro: [
        "Print this page at its own size and the three rules below measure what",
        "they say. Hold a ruler against them to see whether whatever printed it",
        "did as the file asked.",
    ],
    units: ["centimetres", "inches", "points, at 72 to the inch"],
    asks: "What this file asks for, and what it writes to ask",
    asked: [
        "Print every page at the size it was drawn.",
        "Do not offer to print it at any other size.",
        "Open on the whole sheet, rules and all.",
    ],
    closing: (
        [
            "The second of those entries arrived with PDF 2.0, so this file declares 2.0 on",
            "its first line. Nothing is raised on the caller's behalf: a file that asked for",
            "it while declaring less would be refused rather than quietly written.",
        ],
        [
            "Two more things were decided about the file rather than about its pages. Its",
            "streams were squeezed as small as the compressor goes, which costs time and",
            "saves bytes. And it went into the file a piece at a time as it was made, rather",
            "than being built whole in memory and written at the end.",
        ],
    ),
};

/// The page in French.
const FRENCH: Words = Words {
    title: "À l’échelle réelle",
    intro: [
        "Imprimez cette page à sa taille réelle : les trois règles ci-dessous",
        "mesurent ce qu’elles annoncent. Posez-y un double décimètre pour voir si",
        "l’impression a respecté ce que le fichier demandait.",
    ],
    units: ["centimètres", "pouces", "points, 72 au pouce"],
    asks: "Ce que ce fichier demande, et ce qu’il écrit pour le demander",
    asked: [
        "Imprimer chaque page à sa taille réelle.",
        "Ne proposer aucune autre taille d’impression.",
        "Ouvrir sur la feuille entière, règles comprises.",
    ],
    closing: (
        [
            "La deuxième de ces entrées est apparue avec PDF 2.0 : ce fichier déclare donc",
            "2.0 dès sa première ligne. Aucune version n’est relevée d’office : un",
            "fichier qui la demanderait en déclarant moins serait refusé, non écrit en silence.",
        ],
        [
            "Deux autres réglages concernent le fichier plutôt que ses pages.",
            "Ses flux ont été compressés au niveau le plus fort, ce qui",
            "coûte du temps mais fait gagner des octets. Et le fichier a été écrit morceau",
            "par morceau, à mesure de sa production, au lieu d’être monté entier en mémoire.",
        ],
    ),
};

/// The page in Dutch.
const DUTCH: Words = Words {
    title: "Op ware grootte",
    intro: [
        "Druk deze pagina op haar eigen formaat af en de drie linialen hieronder meten wat",
        "ze zeggen. Leg er een liniaal naast om te zien of wat haar afdrukte,",
        "deed wat het bestand vroeg.",
    ],
    units: ["centimeter", "inch", "punten, 72 per inch"],
    asks: "Wat dit bestand vraagt, en wat het schrijft om het te vragen",
    asked: [
        "Elke pagina op ware grootte afdrukken.",
        "Geen ander afdrukformaat aanbieden.",
        "Openen op het hele blad, linialen en al.",
    ],
    closing: (
        [
            "De tweede van die gegevens kwam met PDF 2.0, dus verklaart dit bestand 2.0 op",
            "zijn eerste regel. Niets wordt stilzwijgend verhoogd: een bestand dat erom vroeg",
            "en minder verklaarde, zou geweigerd worden in plaats van stilletjes geschreven.",
        ],
        [
            "Nog twee dingen werden over het bestand beslist en niet over zijn pagina’s. Zijn",
            "stromen zijn zo klein gecomprimeerd als de compressor kan, wat tijd kost en",
            "bytes spaart. En het ging stukje voor stukje het bestand in terwijl het gemaakt werd,",
            "in plaats van in zijn geheel in het geheugen gebouwd en aan het einde geschreven.",
        ],
    ),
};

/// The page in Portuguese.
const PORTUGUESE: Words = Words {
    title: "À escala real",
    intro: [
        "Imprima esta página ao seu próprio tamanho e as três réguas abaixo medem o",
        "que dizem. Encoste-lhes uma régua para ver se o programa que a imprimiu",
        "fez o que o ficheiro pedia.",
    ],
    units: ["centímetros", "polegadas", "pontos, a 72 por polegada"],
    asks: "O que este ficheiro pede, e o que escreve para o pedir",
    asked: [
        "Imprimir cada página em tamanho real.",
        "Não propor imprimi-la a nenhum outro tamanho.",
        "Abrir na folha inteira, réguas incluídas.",
    ],
    closing: (
        [
            "A segunda destas entradas chegou com o PDF 2.0, por isso este ficheiro declara 2.0 na",
            "sua primeira linha. A biblioteca nunca sobe a versão por si: um ficheiro que o pedisse",
            "declarando menos seria recusado em vez de escrito em silêncio.",
        ],
        [
            "Decidiram-se mais duas coisas sobre o ficheiro e não sobre as suas páginas. Os seus",
            "fluxos foram comprimidos o mais que o compressor permite, o que custa tempo e",
            "poupa bytes. E foi escrito uma peça de cada vez, à medida que era feito, em vez",
            "de ser construído inteiro em memória e escrito no fim.",
        ],
    ),
};

/// The page in Italian.
const ITALIAN: Words = Words {
    title: "In scala reale",
    intro: [
        "Stampate questa pagina alla sua dimensione e i tre righelli qui sotto misurano ciò",
        "che dicono. Accostatele un righello per vedere se ciò che l’ha stampata",
        "ha fatto quanto chiedeva il file.",
    ],
    units: ["centimetri", "pollici", "punti, 72 per pollice"],
    asks: "Cosa chiede questo file, e cosa scrive per chiederlo",
    asked: [
        "Stampare ogni pagina a grandezza reale.",
        "Non proporre di stamparla a un’altra dimensione.",
        "Aprire sul foglio intero, righelli compresi.",
    ],
    closing: (
        [
            "La seconda di queste voci è arrivata con PDF 2.0, così questo file dichiara 2.0 nella",
            "sua prima riga. Niente è alzato per conto di chi chiama: un file che la chiedesse",
            "dichiarando meno sarebbe rifiutato anziché scritto in silenzio.",
        ],
        [
            "Altre due cose sono state decise sul file e non sulle sue pagine. I suoi",
            "flussi sono compressi al massimo consentito dal compressore, il che costa tempo e",
            "risparmia byte. Ed è entrato nel file un pezzo alla volta, mentre si faceva, anziché",
            "essere costruito intero in memoria e scritto alla fine.",
        ],
    ),
};

/// The page in Spanish.
const SPANISH: Words = Words {
    title: "A escala real",
    intro: [
        "Imprima esta página a su propio tamaño y las tres reglas de abajo miden lo",
        "que dicen. Póngales una regla al lado para ver si lo que la imprimió",
        "hizo lo que pedía el archivo.",
    ],
    units: ["centímetros", "pulgadas", "puntos, a 72 por pulgada"],
    asks: "Lo que pide este archivo, y lo que escribe para pedirlo",
    asked: [
        "Imprimir cada página al tamaño en que se dibujó.",
        "No ofrecer imprimirla a ningún otro tamaño.",
        "Abrir en la hoja entera, reglas incluidas.",
    ],
    closing: (
        [
            "La segunda de esas entradas llegó con PDF 2.0, así que este archivo declara 2.0 en",
            "su primera línea. La versión nunca se sube por su cuenta: un archivo que lo pidiera",
            "declarando menos se rechazaría en vez de escribirse en silencio.",
        ],
        [
            "Se decidieron dos cosas más sobre el archivo y no sobre sus páginas. Sus",
            "flujos se comprimieron tanto como da el compresor, lo que cuesta tiempo y",
            "ahorra bytes. Y se escribió pieza a pieza a medida que se hacía, en vez",
            "de construirse entero en memoria y escribirse al final.",
        ],
    ),
};

/// The page in German.
const GERMAN: Words = Words {
    title: "Maßstabsgetreu",
    intro: [
        "Diese Seite in ihrer eigenen Größe drucken, und die drei Linien unten",
        "messen, was sie angeben. Ein Lineal daneben zeigt, ob das, was sie",
        "gedruckt hat, getan hat, was die Datei verlangte.",
    ],
    units: ["Zentimeter", "Zoll", "Punkt, 72 pro Zoll"],
    asks: "Was diese Datei verlangt, und was sie dafür schreibt",
    asked: [
        "Jede Seite in Originalgröße drucken.",
        "Keine andere Druckgröße anbieten.",
        "Auf dem ganzen Bogen öffnen, samt Linien.",
    ],
    closing: (
        [
            "Der zweite dieser Einträge kam mit PDF 2.0, also gibt diese Datei in ihrer",
            "ersten Zeile 2.0 an. Nichts wird für den Aufrufer angehoben: Eine Datei, die",
            "es verlangte und weniger angäbe, würde abgelehnt, nicht still geschrieben.",
        ],
        [
            "Zwei weitere Dinge wurden über die Datei entschieden statt über ihre Seiten.",
            "Ihre Datenströme wurden so klein gepresst, wie es der Kompressor vermag, was Zeit",
            "kostet und Bytes spart. Und sie ging Stück für Stück in die Datei, wie sie",
            "entstand, statt ganz im Speicher gebaut und am Ende geschrieben zu werden.",
        ],
    ),
};

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

/// 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(())
}

/// How far along the page the tick at `index` stands.
#[expect(
    clippy::cast_precision_loss,
    reason = "a rule is twenty ticks long, not four thousand million"
)]
#[expect(
    clippy::suboptimal_flops,
    reason = "the Python twin multiplies and adds apart, and the two write one file"
)]
fn along(step: f64, index: usize) -> f64 {
    MARGIN + step * index as f64
}

/// Draws a rule: a baseline with a tick at every step, the tall ones numbered,
/// and the name of the rule set above it.
///
/// The ticks run up from the baseline and the numbers sit under it, so nothing
/// a ruler is laid against is covered.
fn rule(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    spec: &Rule,
    name: &str,
) -> Result<(), Error> {
    content.save_state();
    content.set_stroke(Color::Gray(0.1))?;
    content.set_line_width(0.6)?;
    content.move_to(MARGIN, y)?;
    content.line_to(along(spec.step, spec.steps), y)?;
    content.stroke();

    for index in 0..=spec.steps {
        let x = along(spec.step, index);
        let height = if index % spec.tall == 0 { 14.0 } else { 7.0 };
        content.move_to(x, y)?;
        content.line_to(x, y + height)?;
        content.stroke();
    }
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.35))?;
    for index in (0..=spec.steps).step_by(spec.tall) {
        let x = along(spec.step, index);
        let number = format!("{}", index * spec.worth);
        text(content, font, 8.0, x - 2.0, y - 12.0, &number)?;
    }
    content.set_fill(Color::Gray(0.1))?;
    text(content, font, 10.0, MARGIN, y + 22.0, name)?;
    content.restore_state();
    Ok(())
}

/// The band across the head of the page, and what stands under it.
fn head(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(Rgb::new(0.16, 0.20, 0.26))?;
    content.rect(0.0, SHEET.1 - 96.0, SHEET.0, 96.0)?.fill();
    content.set_fill(Rgb::new(1.0, 1.0, 1.0))?;
    text(content, font, 20.0, MARGIN, SHEET.1 - 58.0, words.title)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.25))?;
    let mut y = SHEET.1 - 140.0;
    for line in words.intro {
        text(content, font, 11.0, MARGIN, y, line)?;
        y -= 18.0;
    }
    content.restore_state();
    Ok(())
}

/// What the file asks of whatever shows and prints it, set beside the entries
/// it writes to ask.
fn asks(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_stroke(Color::Gray(0.82))?;
    content.set_line_width(0.4)?;
    content.move_to(MARGIN, 350.0)?;
    content.line_to(SHEET.0 - MARGIN, 350.0)?;
    content.stroke();
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.1))?;
    text(content, font, 13.0, MARGIN, 322.0, words.asks)?;
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.3))?;
    let mut y = 294.0;
    for (asked, written) in words.asked.iter().zip(WRITTEN) {
        text(content, font, 11.0, MARGIN, y, asked)?;
        text(content, font, 10.0, MARGIN + ENTRY, y, written)?;
        y -= 20.0;
    }
    content.restore_state();

    content.save_state();
    content.set_fill(Color::Gray(0.45))?;
    let mut y = 212.0;
    for paragraph in [words.closing.0.as_slice(), words.closing.1.as_slice()] {
        for line in paragraph {
            text(content, font, 10.5, MARGIN, y, line)?;
            y -= 17.0;
        }
        y -= 17.0;
    }
    content.restore_state();
    Ok(())
}

/// The page: the band across its head, the three rules, and what the file asks
/// of whatever prints it.
fn sheet(font: &FontHandle, words: &Words) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    head(&mut content, font, words)?;
    for (index, (y, spec)) in RULES.iter().enumerate() {
        rule(&mut content, font, *y, spec, &words.rule_name(index, spec))?;
    }
    asks(&mut content, font, words)?;

    content.save_state();
    content.set_fill(Color::Gray(0.5))?;
    text(&mut content, font, 8.0, MARGIN, 62.0, "HQF Development")?;
    content.restore_state();
    Ok(content.into_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("scale")));
    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 mut page = Page::new(SHEET.0, SHEET.1);
    page.content = sheet(&font, words)?;
    doc.add_page(page)?;

    // Asking for the size the pages print at is one entry; taking the choice
    // away from the reader is a second, which PDF 2.0 brought and which the
    // file must therefore declare itself as.
    doc.set_viewer_preferences(ViewerPreferences::new().lock_actual_size());
    doc.set_open_action(OpenAction::new(0).view(PageFit::WholePage));
    doc.set_version(Version::V2_0);
    doc.set_compression_level(Compression::SMALLEST);

    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    doc.write_to(BufWriter::new(File::create(&out)?))?;

    println!(
        "wrote {out}: {} bytes, one sheet that prints at the size it was drawn",
        fs::metadata(&out)?.len()
    );
    Ok(())
}

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

    use super::{ENTRY, MARGIN, RULES, SHEET, WORDS, default_font, language};

    /// The lines two languages are allowed to write the same way. Every line
    /// here is a title, a caption or a sentence, and two languages write one
    /// alike only where they spell it alike; the entries the file writes are
    /// not in `Words` at all.
    const SPARED: [&str; 1] = [
        // Written the same way in Portuguese.
        r#""centímetros""#,
    ];

    /// The room a line set from the left margin has before it reaches the
    /// margin on the other side.
    const PAPER: f64 = SHEET.0 - 2.0 * MARGIN;

    /// The room a line of asking has before it reaches the entry set beside it.
    const GUTTER: f64 = 10.0;

    #[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 line longer than the room it
    /// has runs on over whatever stands beside it, and the lines of asking have
    /// the least room of all, because the entry the file writes stands at a
    /// fixed distance from them.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        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((20.0, words.title.to_owned(), PAPER))
                .chain(words.intro.map(|line| (11.0, line.to_owned(), PAPER)))
                .chain(
                    RULES
                        .iter()
                        .enumerate()
                        .map(|(index, (_, spec))| (10.0, words.rule_name(index, spec), PAPER)),
                )
                .chain([(13.0, words.asks.to_owned(), PAPER)])
                .chain(
                    words
                        .asked
                        .map(|line| (11.0, line.to_owned(), ENTRY - GUTTER)),
                )
                .chain(words.closing.0.map(|line| (10.5, line.to_owned(), PAPER)))
                .chain(words.closing.1.map(|line| (10.5, line.to_owned(), PAPER)));

            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 has {room:.1}"
                );
            }
        }
    }
}