A sheet a printing works runs without asking a question

One sheet larger than the finished page: the colour runs nine points past the blade, the corner marks stand outside it in an ink every plate carries, every colour is said in the four printing inks, and the page names the paper, the edge of the ink and the cut. Hand it the profile of a press and it claims PDF/X-4; without one it claims nothing, and says on the page why.

Rust write_print_ready.rs 852 lines
  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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! A sheet a printer can run without asking the sender a single question.
//!
//! The finished page is smaller than the paper it is drawn on: the ink runs
//! past the blade so that a cut a hair off still lands in colour, the marks
//! stand outside the ink so the blade takes them away, and every colour is said
//! in the four printing inks rather than in the light of a screen. The page
//! names the three boxes that say all of it.
//!
//! Hand a press profile on the command line and the file claims PDF/X-4.
//! Without one it claims nothing, and says on the page why.
//!
//! The sheet is written in the language `HQF_PDF_LANG` names. What the file
//! writes is not: `MediaBox`, `BleedBox`, `TrimBox`, `Title` and `Trapped` are
//! the entries a press looks up, `Custom` is the name ISO 32000-1 asks for
//! where the condition is not a registered one, and `sRGB IEC61966-2.1` is the
//! profile's own name. The page states each of them beside what it means.
//!
//! Usage: `cargo run --example write_print_ready -- tmp/print.pdf [font.ttf]
//! [press.icc]`
//!        `HQF_PDF_LANG=fr cargo run --example write_print_ready`

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

use hqf_pdf::color::icc;
use hqf_pdf::content::Content;
use hqf_pdf::metadata::xmp::{Metadata, PdfX, Trapped};
use hqf_pdf::{
    Cmyk, Document, Error, Font, FontHandle, IccBased, OutputIntent, Page, Rect, Version,
};

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

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

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

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 date the document says it was made on, so that two runs of the example
/// produce the same bytes.
const MADE: &str = "2026-07-25T10:00:00+02:00";

/// How far past the blade the ink runs.
const BLEED_OVER: f64 = 9.0;
/// How much paper is left outside the ink for the marks.
const MARK_ROOM: f64 = 27.0;
/// How long one arm of a corner mark is.
const MARK_LENGTH: f64 = 18.0;
/// How much paper stands outside the finished page on every side.
const MARGIN: f64 = BLEED_OVER + MARK_ROOM;

/// The finished page: where the blade falls, in the sheet's own coordinates.
const TRIM: (f64, f64, f64, f64) = (MARGIN, MARGIN, 400.0, 620.0);
/// The whole sheet: the finished page, the ink that runs past it, and the room
/// the marks stand in.
const SHEET: (f64, f64) = (TRIM.2 + MARGIN + MARGIN, TRIM.3 + MARGIN + MARGIN);

/// The left edge of everything drawn inside the finished page.
const LEFT: f64 = 56.0;
/// How far right of the left edge the second column of a stated pair starts.
const COLUMN: f64 = 112.0;

/// The band across the head of the sheet, and the bar across its foot.
const BAND: Cmyk = Cmyk::new(0.85, 0.55, 0.0, 0.25);
/// The line under the title, on the band.
const ON_BAND: Cmyk = Cmyk::new(0.22, 0.1, 0.0, 0.0);
/// A panel's heading.
const HEADING: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 1.0);
/// A panel's body.
const BODY: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.72);
/// What a stated pair is called.
const LABEL: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.5);
/// What it says.
const VALUE: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.85);
/// All four inks at once, which prints on every plate.
const REGISTRATION: Cmyk = Cmyk::new(1.0, 1.0, 1.0, 1.0);

/// The house sending the sheet, which the footer names before saying what the
/// sheet is.
const HOUSE: &str = "HQF Development";

/// The size the sheet's heading is set at, in points.
const HEADING_SIZE: f64 = 19.0;
/// The size the line under that heading is set at, in points.
const STRAPLINE: f64 = 9.0;
/// The size the line in the margin is set at, in points.
const SLUG: f64 = 6.0;
/// The size a panel's heading is set at, in points.
const PANEL: f64 = 10.5;
/// The size a panel's body is set at, in points.
const PANEL_BODY: f64 = 8.0;
/// The size a stated pair is set at, in points.
const PAIR: f64 = 8.5;
/// The size the name under a swatch is set at, in points.
const SWATCH_NAME: f64 = 7.5;

/// Where the first line of the closing note sits, and how far below one line
/// the next one does, in points.
const CLOSING_TOP: f64 = 104.0;
/// See [`CLOSING_TOP`].
const CLOSING_STEP: f64 = 12.0;

/// The head of the sheet: the flood, its title and the line under it.
const BAND_BOTTOM: f64 = 545.0;
/// The foot of the sheet: the bar the footer is written on.
const BAR_TOP: f64 = 52.0;

/// The width of one ink swatch, the gap to the next, their bottom edge and
/// their height.
const SWATCH: f64 = 64.0;
/// See [`SWATCH`].
const SWATCH_GAP: f64 = 10.0;
/// See [`SWATCH`].
const SWATCH_Y: f64 = 292.0;
/// See [`SWATCH`].
const SWATCH_HEIGHT: f64 = 42.0;

/// What each ink swatch is made of, in the order `Words::inks` names them.
const MIXES: [&str; 5] = [
    "100 0 0 0",
    "0 100 0 0",
    "0 0 100 0",
    "0 0 0 100",
    "100 100 100 100",
];

/// The colour each swatch is laid in, in the same order.
const INKS: [Cmyk; 5] = [
    Cmyk::new(1.0, 0.0, 0.0, 0.0),
    Cmyk::new(0.0, 1.0, 0.0, 0.0),
    Cmyk::new(0.0, 0.0, 1.0, 0.0),
    Cmyk::new(0.0, 0.0, 0.0, 1.0),
    REGISTRATION,
];

/// What the caller says the condition is called when a profile is handed over
/// on the command line.
///
/// ISO 32000-1 table 365 asks for `Custom` where the condition is not one of
/// the registered characterizations, which a profile read off a disk is not.
const CUSTOM: &str = "Custom";
/// What the condition is called when the library's own profile is used, and the
/// profile's own name, which is not a description of it.
const BUILT_IN: (&str, &str) = ("sRGB", "sRGB IEC61966-2.1");

/// What the file writes for each of the three boxes and each of the two entries
/// the page states, in the order they are set. These are the names a press
/// looks up, and they are the same in every language.
const BOXES: [&str; 3] = ["MediaBox", "BleedBox", "TrimBox"];
/// See [`BOXES`].
const ENTRIES: [&str; 2] = ["Title", "Trapped"];

/// What the file writes for the trapping entry, which the page states beside
/// what it means.
const TRAPPED: &str = "No";

/// The words the sheet is written in, one set per language.
///
/// What is not language stays out of it: the entries a press looks up, the
/// numbers the boxes measure, the four ink mixes, and the profile's own name.
#[derive(Debug)]
struct Words {
    /// What the job is called, on the page and in what the file says of itself.
    title: &'static str,
    /// What the sheet is headed by.
    heading: &'static str,
    /// The line under that heading.
    strapline: &'static str,
    /// What the footer says the sheet is, after the name of the house sending
    /// it.
    footer: &'static str,
    /// What the line in the margin calls the whole sheet, the finished page,
    /// the ink that runs past it, and the inks it is separated for.
    slug: [&'static str; 4],
    /// What each of the five panels is headed by.
    panels: [&'static str; 5],
    /// The line under the first panel.
    boxes_note: &'static str,
    /// What each of the three boxes is for, after the size it measures.
    boxes: [&'static str; BOXES.len()],
    /// The lines under the second panel.
    ink_stops: [&'static str; 3],
    /// The lines under the third panel.
    four_inks: [&'static str; 2],
    /// What each printing ink is called, in the order `INKS` lays them.
    inks: [&'static str; INKS.len()],
    /// The lines under the fourth panel.
    marks: [&'static str; 3],
    /// What the last two pairs the page states are called.
    stated_for: &'static str,
    /// See [`Words::stated_for`].
    claim: &'static str,
    /// What the trapping entry means, after the word the file writes.
    trapped: &'static str,
    /// What stands before and after the size of the profile the file is stated
    /// for.
    profile_of: &'static str,
    /// See [`Words::profile_of`].
    bytes: &'static str,
    /// What the claim says when the file makes none.
    no_claim: &'static str,
    /// What the condition a profile off the command line describes is called.
    custom_info: &'static str,
    /// The closing note of a file that claims the print standard.
    claimed: [&'static str; 5],
    /// The closing note of a file that claims nothing.
    unclaimed: [&'static str; 5],
}

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

/// The sheet in English.
const ENGLISH: Words = Words {
    title: "Spring catalogue, cover",
    heading: "Ready for the press",
    strapline: "One sheet, handed over with nothing left for the printer to ask about.",
    footer: "one sheet, ready to run",
    slug: ["sheet", "trim", "bleed", "CMYK"],
    panels: [
        "The three boxes this sheet states",
        "Where the ink stops",
        "Four inks, not three",
        "The marks stand outside the ink",
        "What the file says about itself",
    ],
    boxes_note: "The paper is larger than the finished page; the ink runs to a box in between.",
    boxes: [
        "the whole sheet, marks and all",
        "how far the ink runs",
        "where the blade falls",
    ],
    ink_stops: [
        "The band at the head of this page runs 9 points past the blade on three",
        "sides, and the bar at its foot does the same. A blade that falls a point",
        "wide still lands in ink, so the finished page carries no white edge.",
    ],
    four_inks: [
        "Every colour on this page is said in the four printing inks. A screen colour",
        "would have to be separated by somebody — and that somebody is the printer.",
    ],
    inks: ["Cyan", "Magenta", "Yellow", "Black", "Registration"],
    marks: [
        "The corner marks are drawn past the bleed, so the blade takes them away",
        "with the rest of the paper. They are laid in all four inks at once: a",
        "mark that prints on every plate is a mark the press lines its plates by.",
    ],
    stated_for: "Stated for",
    claim: "Claim",
    trapped: "said in the file, not left unknown",
    profile_of: "a profile of",
    bytes: "bytes",
    no_claim: "none — the note below says why",
    custom_info: "A press profile handed over on the command line",
    claimed: [
        "This file claims PDF/X-4, through the profile handed on the command line.",
        "The claim is written twice over: the output intent answers for it as",
        "GTS_PDFX, and the metadata names the part claimed. The library refuses the",
        "claim unless the file carries the press profile, a title, a word on",
        "trapping and a trim box on every page. All four are here.",
    ],
    unclaimed: [
        "This file makes no PDF/X-4 claim. That claim promises a press it can run",
        "the file without asking back, and the promise rests on the profile of the",
        "press the job was separated for. The library builds one profile, sRGB, and",
        "sRGB describes a screen: it is not allowed to stand in for a press. Hand a",
        "press profile on the command line and the same sheet claims PDF/X-4.",
    ],
};

/// The sheet in French.
const FRENCH: Words = Words {
    title: "Catalogue de printemps, couverture",
    heading: "Prête pour la presse",
    strapline: "Une feuille, remise sans rien laisser à demander à l'imprimeur.",
    footer: "une feuille, prête à tourner",
    slug: ["feuille", "coupe", "fond perdu", "CMJN"],
    panels: [
        "Les trois boîtes que cette feuille déclare",
        "Où l'encre s'arrête",
        "Quatre encres, pas trois",
        "Les repères se tiennent hors de l'encre",
        "Ce que le fichier dit de lui-même",
    ],
    boxes_note: "Le papier est plus grand que la page finie ; l'encre court jusqu'à une boîte entre les deux.",
    boxes: [
        "la feuille entière, repères compris",
        "jusqu'où court l'encre",
        "où tombe la lame",
    ],
    ink_stops: [
        "La bande en tête de page court 9 points au-delà de la lame sur trois côtés,",
        "et la barre au pied fait de même. Une lame qui tombe un point trop loin",
        "retombe encore dans l'encre : la page finie n'a aucun bord blanc.",
    ],
    four_inks: [
        "Chaque couleur de cette page est dite dans les quatre encres d'imprimerie. Une",
        "couleur d'écran devrait être séparée par quelqu'un — et ce quelqu'un est l'imprimeur.",
    ],
    inks: ["Cyan", "Magenta", "Jaune", "Noir", "Repérage"],
    marks: [
        "Les repères d'angle sont tracés au-delà du fond perdu, donc la lame les",
        "emporte avec le reste du papier. Ils sont posés dans les quatre encres à la",
        "fois : un repère qui s'imprime sur chaque plaque est un repère qui cale la presse.",
    ],
    stated_for: "Déclarée pour",
    claim: "Revendication",
    trapped: "dit dans le fichier, pas laissé inconnu",
    profile_of: "un profil de",
    bytes: "octets",
    no_claim: "aucune — la note ci-dessous dit pourquoi",
    custom_info: "Un profil de presse passé en ligne de commande",
    claimed: [
        "Ce fichier revendique PDF/X-4, par le profil passé en ligne de commande.",
        "La revendication est écrite deux fois : l'intention de sortie en répond sous",
        "le nom GTS_PDFX, et les métadonnées nomment la partie revendiquée. La",
        "bibliothèque refuse la revendication tant que le fichier ne porte pas le profil",
        "de presse, un titre, un mot sur le défonçage et une boîte de coupe par page.",
    ],
    unclaimed: [
        "Ce fichier ne revendique pas PDF/X-4. Cette revendication promet à une presse",
        "qu'elle peut tourner sans rien redemander, et elle tient au profil de la presse",
        "pour laquelle le travail a été séparé. La bibliothèque n'a qu'un profil, sRGB,",
        "qui décrit un écran : il ne peut pas tenir lieu de presse. Passez un profil de",
        "presse en ligne de commande et la même feuille revendique PDF/X-4.",
    ],
};

/// 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); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// A profile, what the condition it describes is called, whether that name is
/// the profile's own, and whether the file claims the print standard on it.
struct Stated {
    profile: Vec<u8>,
    identifier: &'static str,
    info: Option<&'static str>,
    claims: bool,
}

impl Stated {
    /// What the page and the output intent say the condition is.
    fn info(&self, words: &Words) -> &'static str {
        self.info.unwrap_or(words.custom_info)
    }
}

/// Where the blade falls.
const fn trim() -> Rect {
    Rect::new(TRIM.0, TRIM.1, TRIM.2, TRIM.3)
}

/// What the ink runs to.
const fn bleed() -> Rect {
    Rect::new(
        TRIM.0 - BLEED_OVER,
        TRIM.1 - BLEED_OVER,
        TRIM.2 + BLEED_OVER + BLEED_OVER,
        TRIM.3 + BLEED_OVER + BLEED_OVER,
    )
}

/// 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.name(), size)?;
    content.text_origin(x, y)?;
    content.show_glyphs(&font.glyphs(line));
    content.end_text();
    Ok(())
}

/// Draws the flood at the head of the sheet and the bar at its foot, both
/// running to the ink's own box and off the blade on three sides.
fn flood(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    let ink = bleed();
    let top = ink.y() + ink.height();

    content.save_state();
    content.set_fill(BAND)?;
    content
        .rect(ink.x(), BAND_BOTTOM, ink.width(), top - BAND_BOTTOM)?
        .fill();
    content
        .rect(ink.x(), ink.y(), ink.width(), BAR_TOP - ink.y())?
        .fill();
    content.restore_state();

    content.save_state();
    content.set_fill(Cmyk::WHITE)?;
    text(content, font, HEADING_SIZE, LEFT, 620.0, words.heading)?;
    text(
        content,
        font,
        7.0,
        LEFT,
        38.0,
        &format!("{HOUSE} — {}", words.footer),
    )?;
    content.set_fill(ON_BAND)?;
    text(content, font, STRAPLINE, LEFT, 600.0, words.strapline)?;
    content.restore_state();
    Ok(())
}

/// Draws the four corner marks, each pair of arms standing outside the ink and
/// pointing at a corner of the finished page.
///
/// They are laid in all four inks at once, so that each plate carries them.
fn corner_marks(content: &mut Content) -> Result<(), Error> {
    let (left, bottom, width, height) = TRIM;
    let right = left + width;
    let top = bottom + height;
    let near = BLEED_OVER;
    let far = BLEED_OVER + MARK_LENGTH;

    content.save_state();
    content.set_stroke(REGISTRATION)?;
    content.set_line_width(0.4)?;
    for (x, from_x, to_x) in [
        (left, left - near, left - far),
        (right, right + near, right + far),
    ] {
        for (y, from_y, to_y) in [
            (bottom, bottom - near, bottom - far),
            (top, top + near, top + far),
        ] {
            content.move_to(from_x, y)?;
            content.line_to(to_x, y)?;
            content.move_to(x, from_y)?;
            content.line_to(x, to_y)?;
        }
    }
    content.stroke();
    content.restore_state();
    Ok(())
}

/// What the line in the margin says: the job, then each box in the order the
/// paper takes them, read off the sizes the page is drawn to.
fn slug_line(words: &Words) -> String {
    let [sheet, trim, bleed, inks] = words.slug;
    format!(
        "{} — {} × {} {sheet} — {} × {} {trim} — {BLEED_OVER} pt {bleed} — {inks}",
        words.title, SHEET.0, SHEET.1, TRIM.2, TRIM.3
    )
}

/// Draws the line in the margin naming the job, which the blade takes away with
/// the rest of the paper outside the finished page.
fn slug(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.save_state();
    content.set_fill(REGISTRATION)?;
    text(content, font, SLUG, LEFT, 14.0, &slug_line(words))?;
    content.restore_state();
    Ok(())
}

/// Draws one panel: its heading, and the lines of body under it.
fn panel(
    content: &mut Content,
    font: &FontHandle,
    y: f64,
    title: &str,
    lines: &[&str],
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(HEADING)?;
    text(content, font, PANEL, LEFT, y, title)?;
    content.set_fill(BODY)?;
    let mut line_y = y - 15.0;
    for line in lines {
        text(content, font, PANEL_BODY, LEFT, line_y, line)?;
        line_y -= 12.0;
    }
    content.restore_state();
    Ok(())
}

/// Draws a run of stated pairs, one to a line, what each is called on the left
/// and what it says beside it.
fn stated(
    content: &mut Content,
    font: &FontHandle,
    top: f64,
    pairs: &[(&str, String)],
) -> Result<(), Error> {
    let mut y = top;
    for (label, value) in pairs {
        content.save_state();
        content.set_fill(LABEL)?;
        text(content, font, PAIR, LEFT, y, label)?;
        content.set_fill(VALUE)?;
        text(content, font, PAIR, LEFT + COLUMN, y, value)?;
        content.restore_state();
        y -= 14.0;
    }
    Ok(())
}

/// Draws one swatch per printing ink, each at full strength, under the name of
/// the ink and the four numbers that say it.
fn swatches(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    let mut x = LEFT;
    for ((name, mix), ink) in words.inks.iter().zip(MIXES).zip(INKS) {
        content.save_state();
        content.set_fill(ink)?;
        content.rect(x, SWATCH_Y, SWATCH, SWATCH_HEIGHT)?.fill();
        content.restore_state();

        content.save_state();
        content.set_fill(VALUE)?;
        text(content, font, SWATCH_NAME, x, SWATCH_Y - 10.0, name)?;
        content.set_fill(LABEL)?;
        text(content, font, 7.0, x, SWATCH_Y - 20.0, mix)?;
        content.restore_state();
        x += SWATCH + SWATCH_GAP;
    }
    Ok(())
}

/// Draws the closing note: what the file claims, or why it claims nothing.
fn closing(
    content: &mut Content,
    font: &FontHandle,
    words: &Words,
    claims: bool,
) -> Result<(), Error> {
    content.save_state();
    content.set_fill(BODY)?;
    let mut y = CLOSING_TOP;
    for line in if claims {
        words.claimed
    } else {
        words.unclaimed
    } {
        text(content, font, PANEL_BODY, LEFT, y, line)?;
        y -= CLOSING_STEP;
    }
    content.restore_state();
    Ok(())
}

/// The profile the document is stated for, what its condition is called, and
/// whether the print standard is claimed on it: the file named on the command
/// line, or the one the library builds.
fn stated_for(path: Option<String>) -> Result<Stated, Box<dyn std::error::Error>> {
    match path {
        Some(path) => Ok(Stated {
            profile: fs::read(path)?,
            identifier: CUSTOM,
            info: None,
            claims: true,
        }),
        None => Ok(Stated {
            profile: icc::srgb(),
            identifier: BUILT_IN.0,
            info: Some(BUILT_IN.1),
            claims: false,
        }),
    }
}

/// The size each of the three boxes measures, in points, in the order the page
/// states them.
const fn box_sizes() -> [(f64, f64); BOXES.len()] {
    let ink = bleed();
    [
        (SHEET.0, SHEET.1),
        (ink.width(), ink.height()),
        (TRIM.2, TRIM.3),
    ]
}

/// The whole sheet, drawn once.
fn sheet(font: &FontHandle, words: &Words, stated_as: &Stated) -> Result<Vec<u8>, Error> {
    let mut content = Content::new();
    flood(&mut content, font, words)?;
    corner_marks(&mut content)?;
    slug(&mut content, font, words)?;

    panel(
        &mut content,
        font,
        518.0,
        words.panels[0],
        &[words.boxes_note],
    )?;
    let boxes: Vec<(&str, String)> = BOXES
        .iter()
        .zip(box_sizes())
        .zip(words.boxes)
        .map(|((name, (width, height)), says)| (*name, format!("{width} × {height} pt — {says}")))
        .collect();
    stated(&mut content, font, 487.0, &boxes)?;

    panel(&mut content, font, 434.0, words.panels[1], &words.ink_stops)?;

    panel(&mut content, font, 371.0, words.panels[2], &words.four_inks)?;
    swatches(&mut content, font, words)?;

    panel(&mut content, font, 248.0, words.panels[3], &words.marks)?;

    panel(&mut content, font, 185.0, words.panels[4], &[])?;
    stated(
        &mut content,
        font,
        169.0,
        &[
            (ENTRIES[0], words.title.to_owned()),
            (ENTRIES[1], format!("{TRAPPED} — {}", words.trapped)),
            (
                words.stated_for,
                format!(
                    "{} — {} {} {}",
                    stated_as.identifier,
                    words.profile_of,
                    stated_as.profile.len(),
                    words.bytes
                ),
            ),
            (
                words.claim,
                if stated_as.claims {
                    "PDF/X-4".to_owned()
                } else {
                    words.no_claim.to_owned()
                },
            ),
        ],
    )?;

    closing(&mut content, font, words, stated_as.claims)?;
    Ok(content.into_bytes())
}

fn main() -> 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("print_ready")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);
    let stated_as = stated_for(args.next())?;

    let described = icc::space(&stated_as.profile)
        .ok_or("the profile must describe a grey, RGB or CMYK space")?;
    let intent = OutputIntent::new(
        IccBased::new(&stated_as.profile, described)?,
        stated_as.identifier,
        stated_as.info(words),
    )?;

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_metadata(Metadata {
        title: Some(words.title.to_owned()),
        producer: Some("hqf-pdf".to_owned()),
        created: Some(MADE.to_owned()),
        trapped: Some(Trapped::No),
        ..Metadata::default()
    });
    doc.set_output_intent(intent);
    if stated_as.claims {
        doc.set_print_conformance(PdfX::X4);
        doc.set_version(Version::V1_6);
    }

    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, &stated_as)?;
    page.bleed = Some(bleed());
    page.trim = Some(trim());
    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, a press sheet stated for {}, {}",
        written.len(),
        stated_as.identifier,
        if stated_as.claims {
            "claiming PDF/X-4"
        } else {
            "claiming nothing"
        }
    );
    Ok(())
}

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

    use super::{
        BAR_TOP, CLOSING_STEP, CLOSING_TOP, COLUMN, ENTRIES, HEADING_SIZE, LEFT, PAIR, PANEL,
        PANEL_BODY, SHEET, SLUG, STRAPLINE, SWATCH, SWATCH_GAP, SWATCH_NAME, TRAPPED, WORDS,
        default_font, language, slug_line,
    };

    /// The room a line set from the left edge of the finished page has before
    /// it reaches the same margin on the other side of the sheet.
    const ROOM: f64 = SHEET.0 - 2.0 * LEFT;

    /// The room the name under a swatch has before it reaches the next swatch.
    const UNDER_SWATCH: f64 = SWATCH + SWATCH_GAP;

    /// The lines two languages are allowed to write the same way. Two printing
    /// inks are called the same in English and in French; every other word on
    /// the sheet is one or the other, and the entries a press looks up are held
    /// outside the words altogether.
    const SPARED: [&str; 2] = ["\"Cyan\"", "\"Magenta\""];

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

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

    /// Nothing on the sheet is broken to a width. A line longer than the paper
    /// runs off the edge of it, a name longer than its swatch runs into the
    /// next one, and a stated pair whose two halves are both too long runs one
    /// over the other.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        for (named, words) in WORDS {
            let margin_line = slug_line(words);
            let across = [
                (HEADING_SIZE, words.heading),
                (STRAPLINE, words.strapline),
                (PANEL_BODY, words.boxes_note),
            ]
            .into_iter()
            .chain(std::iter::once((SLUG, margin_line.as_str())))
            .chain(words.panels.map(|line| (PANEL, line)))
            .chain(words.ink_stops.map(|line| (PANEL_BODY, line)))
            .chain(words.four_inks.map(|line| (PANEL_BODY, line)))
            .chain(words.marks.map(|line| (PANEL_BODY, line)))
            .chain(words.claimed.map(|line| (PANEL_BODY, line)))
            .chain(words.unclaimed.map(|line| (PANEL_BODY, line)));

            for (size, line) in across {
                let measured = font.measure(line, size);
                assert!(
                    measured <= ROOM,
                    "the {} sheet draws {line:?} over {measured:.1} points, \
                     and it has {ROOM:.1}",
                    named.code()
                );
            }

            for name in words.inks {
                let measured = font.measure(name, SWATCH_NAME);
                assert!(
                    measured <= UNDER_SWATCH,
                    "the {} sheet calls a swatch {name:?}, {measured:.1} points \
                     under a swatch {UNDER_SWATCH:.1} wide",
                    named.code()
                );
            }

            let labels = [ENTRIES[0], ENTRIES[1], words.stated_for, words.claim];
            for label in labels {
                let measured = font.measure(label, PAIR);
                assert!(
                    measured <= COLUMN,
                    "the {} sheet states {label:?} over {measured:.1} points, \
                     and the column is {COLUMN:.1}",
                    named.code()
                );
            }

            let values = [
                format!("{TRAPPED} — {}", words.trapped),
                words.no_claim.to_owned(),
            ];
            for value in values {
                let measured = font.measure(&value, PAIR);
                assert!(
                    measured <= ROOM - COLUMN,
                    "the {} sheet states {value:?} over {measured:.1} points, \
                     and it has {:.1}",
                    named.code(),
                    ROOM - COLUMN
                );
            }
        }
    }

    /// The closing note is set from a fixed baseline down, and the bar across
    /// the foot of the sheet is drawn under it: a line too many would be
    /// written on the bar, where it cannot be read.
    #[test]
    fn the_closing_note_stands_clear_of_the_bar_at_the_foot() {
        for (named, words) in WORDS {
            for note in [words.claimed, words.unclaimed] {
                let count = u32::try_from(note.len()).expect("a note has few lines");
                let last = CLOSING_STEP.mul_add(-f64::from(count - 1), CLOSING_TOP);
                assert!(
                    last >= BAR_TOP,
                    "the {} note ends on a line at {last:.1} points, and the bar \
                     reaches {BAR_TOP:.1}",
                    named.code()
                );
            }
        }
    }
}