write_variable_print.rs

Le fichier Rust de l’exemple « Quatre lettres personnelles, un seul fichier pour la presse ». Quatre lettres de renouvellement d’une salle de concert dans un seul fichier : une seule mise en page, avec sur chacune un nom, une place et un montant différents, le tout écrit sous la forme qu’attend une presse d’impression de données variables.

Rust 967 lignes

À quoi sert cet exemple

Une salle de concert envoie ses lettres de renouvellement : des milliers de pages qui reprennent toutes la même lettre, dont seuls le nom, la place et le montant changent. Si on les envoie à la presse sous forme de milliers de fichiers séparés, ou d’un seul fichier qui ne contient que des pages, le tirage ralentit : la presse traite à nouveau le même en-tête pour chaque page, et rien ne lui indique où une lettre se termine et où commence la suivante.

Ce que montre cet exemple

  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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! Writes a mailing of four personal letters into one file made for
//! variable-data printing: the same layout four times, each copy with its own
//! recipient, seat and amount.
//!
//! The letterhead and the note at the foot of each page are one drawing, placed
//! on every page and marked for reuse (`GTS_XID`, `GTS_Scope File`) and written
//! self-contained, so a press renders it once and keeps it for the whole file.
//! Each letter is a document part of its own, stating its recipient, member
//! number, postcode and amount due, so a press knows where one letter ends and
//! the next begins.
//!
//! Hand a press profile on the command line and the file claims PDF/VT-1, on
//! PDF/X-4, written as PDF 1.6. Without one it claims nothing, is written as
//! PDF 2.0, and says on the page why.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the letters are written in. Names, addresses, seats, dates and
//! amounts are not language.
//!
//! Usage: `cargo run --example write_variable_print -- tmp/variable_print.pdf
//! [font.ttf] [press.icc]`
//!        `HQF_PDF_LANG=fr cargo run --example write_variable_print`

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

use hqf_pdf::color::icc;
use hqf_pdf::content::Content;
use hqf_pdf::layout::{Align, Rect};
use hqf_pdf::metadata::xmp::{Metadata, PdfVt, PdfX, Trapped};
use hqf_pdf::{
    Cmyk, Document, DocumentPart, DocumentParts, Drawing, Error, Font, FontHandle, IccBased,
    OutputIntent, Page, PartData, PartValue, ReuseHints, ReuseScope, TextFlow, Version,
};

#[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 letters are set in when none is given on the command line: the
/// one committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The A4 sheet, in points.
const SHEET: (f64, f64) = (595.0, 842.0);

/// How far in from the left and right edges of the sheet the text stands, in
/// points.
const MARGIN: f64 = 56.0;

/// How wide the text runs, in points: the sheet less both margins.
const WIDTH: f64 = SHEET.0 - 2.0 * MARGIN;

/// How wide the column of amounts is, in points, at the right of the text.
const AMOUNT_WIDTH: f64 = 110.0;

/// How wide the column of what each amount pays for is, in points.
const LABEL_WIDTH: f64 = WIDTH - AMOUNT_WIDTH;

/// How far one row of the amounts stands below the one above it, in points.
const ROW: f64 = 20.0;

/// Where the letterhead band starts, in points up from the foot of the sheet;
/// it runs to the top edge.
const HEAD_BOTTOM: f64 = 762.0;

/// Where the band holding the note starts and ends, in points up from the foot
/// of the sheet.
const NOTE_BAND: (f64, f64) = (36.0, 206.0);

/// How far the note's text stands in from the edges of its band, in points.
const NOTE_INSET: f64 = 12.0;

/// How wide the band holding the note is, in points: the text and an inset on
/// either side.
const NOTE_WIDTH: f64 = WIDTH + 2.0 * NOTE_INSET;

/// The flow the note is set in, by size and leading.
const NOTE_TYPE: (f64, f64) = (8.5, 11.5);

/// The colour of the letterhead band.
const BAND: Cmyk = Cmyk::new(0.85, 0.55, 0.0, 0.25);

/// The colour of the words set on the letterhead band.
const ON_BAND: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.0);

/// The colour of the band behind the note.
const NOTE_FILL: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.06);

/// The colour of the note's words.
const NOTE_INK: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.75);

/// The colour of the letter's words.
const INK: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 1.0);

/// The colour of the rule above the total.
const RULE: Cmyk = Cmyk::new(0.0, 0.0, 0.0, 0.4);

/// The concert hall that sends the letters, written the same way in every
/// language.
const SENDER: &str = "Aldermoor Hall";

/// The day the letters are sent.
const SENT: &str = "2026-11-02";

/// The day a seat is kept until.
const DEADLINE: &str = "2026-12-15";

/// When the file was made, which a press reads as the moment it was last
/// written.
const MADE: &str = "2026-11-02T08:30:00+01:00";

/// The name the output intent states when the profile is the one handed over on
/// the command line.
const CUSTOM: &str = "Custom";

/// What the drawing shared by every page is called among the objects that are
/// the same artwork.
const SHARED_IDENTITY: &str = "aldermoor-renewal-letterhead";

/// One recipient of the mailing: what changes from one letter to the next.
#[derive(Debug)]
struct Recipient {
    /// The name the letter is addressed to.
    name: &'static str,
    /// The street line of the address.
    street: &'static str,
    /// The postcode.
    postcode: &'static str,
    /// The member number.
    number: &'static str,
    /// The seat kept for the recipient.
    seat: &'static str,
    /// Which subscription the recipient holds, as an index into
    /// [`Words::tiers`].
    tier: usize,
    /// How many seasons the recipient has subscribed for.
    seasons: u32,
    /// What the subscription costs, in cents.
    price: i64,
    /// What the loyalty discount takes off, in cents.
    discount: i64,
}

impl Recipient {
    /// What the recipient has to pay, in cents.
    const fn due(&self) -> i64 {
        self.price - self.discount
    }
}

/// The town every recipient lives in.
const TOWN: &str = "Aldermoor";

/// The four recipients of the mailing, one letter each.
const RECIPIENTS: [Recipient; 4] = [
    Recipient {
        name: "Ana Ribeiro",
        street: "14 Quay Street",
        postcode: "AL1 4QD",
        number: "A-10482",
        seat: "F-12",
        tier: 0,
        seasons: 6,
        price: 42_000,
        discount: 4_200,
    },
    Recipient {
        name: "Tomasz Nowak",
        street: "3 Mill Lane",
        postcode: "AL2 7RB",
        number: "A-11937",
        seat: "K-03",
        tier: 1,
        seasons: 2,
        price: 23_000,
        discount: 1_150,
    },
    Recipient {
        name: "Mei Chen",
        street: "27 Orchard Rise",
        postcode: "AL3 9JT",
        number: "A-12260",
        seat: "R-21",
        tier: 2,
        seasons: 2,
        price: 9_000,
        discount: 450,
    },
    Recipient {
        name: "Pieter de Vries",
        street: "8 Bell Yard",
        postcode: "AL1 2HX",
        number: "A-08815",
        seat: "B-07",
        tier: 3,
        seasons: 12,
        price: 90_000,
        discount: 9_000,
    },
];

/// The words the letters are written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the file as a whole is called.
    title: &'static str,
    /// What the hall is, set under its name on the letterhead.
    tagline: &'static str,
    /// The words a member number is introduced by.
    member: &'static str,
    /// The words the day the letter is sent is introduced by.
    sent: &'static str,
    /// The heading of every letter.
    heading: &'static str,
    /// How a letter opens; `{name}` stands for the recipient's name.
    greeting: &'static str,
    /// What every letter says; `{seat}` stands for the seat and `{date}` for
    /// the day the seat is kept until.
    body: &'static str,
    /// What each of the four subscriptions is called, in the order of
    /// [`Recipient::tier`].
    tiers: [&'static str; 4],
    /// What the discount row is; `{seasons}` stands for how many seasons.
    discount: &'static str,
    /// What the total row is.
    total: &'static str,
    /// How a letter closes; `{date}` stands for the day the seat is kept until.
    closing: &'static str,
    /// Who signs the letters.
    signature: &'static str,
    /// The heading of the note at the foot of every page.
    note_title: &'static str,
    /// The note at the foot of every page, saying what the file tells a press.
    note: &'static str,
    /// The last line of the note when the file claims PDF/VT.
    claimed: &'static str,
    /// The last line of the note when the file claims nothing.
    unclaimed: &'static str,
    /// What the output intent says of the profile handed over on the command
    /// line.
    press: &'static str,
}

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

/// The letters in English.
const ENGLISH: Words = Words {
    title: "Season renewal letters, 2027",
    tagline: "Concert hall · 2027 season",
    member: "Member no.",
    sent: "sent on",
    heading: "Your seat for the 2027 season",
    greeting: "Dear {name},",
    body: "Your subscription ends with the last concert of this season. To keep seat \
{seat} for 2027, renew before {date}. The amount below already takes off your loyalty \
discount.",
    tiers: [
        "Full season subscription",
        "Half season subscription",
        "Student subscription",
        "Patron subscription",
    ],
    discount: "Loyalty discount, {seasons} seasons with us",
    total: "To pay",
    closing: "Reply to this letter or call the box office before {date}. We look forward \
to seeing you in the hall.",
    signature: "The box office",
    note_title: "Four letters, one layout, one file",
    note: "These four letters share one layout and differ only in who they are for, the \
seat and the amount. The file tells the press so. Each letter is a part of its own, \
stating the recipient, the member number, the postcode and the amount due. The \
letterhead and this note are a single drawing, placed on every page and marked to be \
rendered once and kept for the whole file. This is variable-data printing: a run of \
thousands of personal letters sent to the press as one file and printed at full speed.",
    claimed: "This file claims PDF/VT-1, on PDF/X-4, for the press profile it was given.",
    unclaimed: "This copy claims no standard: PDF/VT rests on PDF/X-4, which needs the \
profile of the press the run is printed on. Give one on the command line and the same \
file claims both.",
    press: "A press profile handed over on the command line",
};

/// The letters in French.
const FRENCH: Words = Words {
    title: "Lettres de réabonnement, saison 2027",
    tagline: "Salle de concert · saison 2027",
    member: "N° d’abonné",
    sent: "envoyée le",
    heading: "Votre place pour la saison 2027",
    greeting: "Bonjour {name},",
    body: "Votre abonnement prend fin avec le dernier concert de cette saison. Pour \
conserver la place {seat} en 2027, renouvelez-le avant le {date}. Le montant \
ci-dessous tient déjà compte de votre remise de fidélité.",
    tiers: [
        "Abonnement saison complète",
        "Abonnement demi-saison",
        "Abonnement étudiant",
        "Abonnement mécène",
    ],
    discount: "Remise de fidélité, {seasons} saisons à nos côtés",
    total: "Montant à régler",
    closing: "Répondez simplement à ce courrier ou appelez la billetterie avant le \
{date}. Nous nous réjouissons de vous retrouver dans la salle.",
    signature: "La billetterie",
    note_title: "Quatre lettres, une mise en page, un seul fichier",
    note: "Ces quatre lettres partagent la même mise en page ; seuls changent le \
destinataire, la place et le montant. Le fichier l’indique à la presse. \
Chaque lettre constitue une partie distincte du document, qui précise le \
destinataire, le numéro d’abonné, le code postal et le montant dû. L’en-tête \
et cette note sont un seul et même objet graphique, placé sur chaque page et \
marqué pour être traité une seule fois par le RIP, puis conservé pour tout \
le fichier. C’est de l’impression de données variables : un tirage de \
milliers de lettres personnalisées, envoyé à la presse en un seul fichier et \
imprimé à pleine vitesse.",
    claimed: "Ce fichier déclare la conformité à PDF/VT-1, sur une base PDF/X-4, pour \
le profil de presse qui lui a été fourni.",
    unclaimed: "Cet exemplaire ne déclare la conformité à aucune norme : PDF/VT repose \
sur PDF/X-4, qui exige le profil de la presse utilisée pour le tirage. \
Fournissez-en un en ligne de commande et le même fichier déclarera la \
conformité aux deux.",
    press: "Profil de presse fourni en ligne de commande",
};

/// The letters in German.
const GERMAN: Words = Words {
    title: "Verlängerungsschreiben zur Saison 2027",
    tagline: "Konzerthaus · Saison 2027",
    member: "Abonnenten-Nr.",
    sent: "versandt am",
    heading: "Ihr Platz in der Saison 2027",
    greeting: "Guten Tag {name},",
    body: "Ihr Abonnement endet mit dem letzten Konzert dieser Saison. Damit Ihnen \
Platz {seat} auch 2027 erhalten bleibt, verlängern Sie bitte bis zum {date}. \
Ihr Treuerabatt ist im unten stehenden Betrag bereits abgezogen.",
    tiers: [
        "Abonnement für die ganze Saison",
        "Abonnement für die halbe Saison",
        "Abonnement für Studierende",
        "Förderabonnement",
    ],
    discount: "Treuerabatt für {seasons} Saisons bei uns",
    total: "Zu zahlen",
    closing: "Antworten Sie auf dieses Schreiben oder rufen Sie bis zum {date} die \
Konzertkasse an. Wir freuen uns, Sie im Saal begrüßen zu dürfen.",
    signature: "Ihre Konzertkasse",
    note_title: "Vier Briefe, ein Layout, eine Datei",
    note: "Diese vier Briefe haben dasselbe Layout und unterscheiden sich nur in \
Empfänger, Sitzplatz und Betrag. Die Datei teilt das der Druckmaschine mit. \
Jeder Brief ist ein eigener Dokumentteil und nennt Empfänger, \
Abonnentennummer, Postleitzahl und fälligen Betrag. Briefkopf und dieser \
Hinweis sind ein einziges Grafikobjekt, das auf jeder Seite platziert und so \
gekennzeichnet ist, dass es ein einziges Mal gerastert und für die ganze \
Datei vorgehalten wird. Das ist variabler Datendruck: Eine Auflage von \
Tausenden persönlicher Briefe geht als eine einzige Datei an die \
Druckmaschine und wird mit voller Geschwindigkeit gedruckt.",
    claimed: "Diese Datei erklärt Konformität mit PDF/VT-1 auf Basis von PDF/X-4, \
bezogen auf das übergebene Farbprofil der Druckmaschine.",
    unclaimed: "Dieses Exemplar erklärt keine Normkonformität: PDF/VT baut auf PDF/X-4 \
auf, und PDF/X-4 verlangt das Farbprofil der Druckmaschine, auf der die \
Auflage gedruckt wird. Wird es auf der Kommandozeile übergeben, erklärt \
dieselbe Datei Konformität mit beiden Normen.",
    press: "Farbprofil der Druckmaschine, über die Kommandozeile übergeben",
};

/// The letters in Spanish.
const SPANISH: Words = Words {
    title: "Cartas de renovación del abono, 2027",
    tagline: "Sala de conciertos · temporada 2027",
    member: "N.º de abonado",
    sent: "enviada el",
    heading: "Su butaca para la temporada 2027",
    greeting: "Buenos días, {name}:",
    body: "Su abono termina con el último concierto de esta temporada. Para conservar \
la butaca {seat} en 2027, renuévelo antes del {date}. El importe que figura \
abajo ya lleva aplicado su descuento por fidelidad.",
    tiers: [
        "Abono de temporada completa",
        "Abono de media temporada",
        "Abono de estudiante",
        "Abono de mecenas",
    ],
    discount: "Descuento por fidelidad: {seasons} temporadas con nosotros",
    total: "Total a pagar",
    closing: "Responda a esta carta o llame a la taquilla antes del {date}. Será un \
placer volver a verle en la sala.",
    signature: "La taquilla",
    note_title: "Cuatro cartas, una maqueta, un solo archivo",
    note: "Estas cuatro cartas comparten la misma maqueta y solo se diferencian en el \
destinatario, la butaca y el importe. El archivo se lo comunica así a la \
máquina de impresión. Cada carta es una parte propia del documento, que \
indica el destinatario, el número de abonado, el código postal y el importe \
pendiente. El membrete y esta nota son un único objeto gráfico, colocado en \
todas las páginas y marcado para que el RIP lo rasterice una sola vez y lo \
conserve durante todo el archivo. Esto es impresión de datos variables: una \
tirada de miles de cartas personalizadas que llega a la máquina de impresión \
en un único archivo y se imprime a máxima velocidad.",
    claimed: "Este archivo declara la conformidad con PDF/VT-1, sobre PDF/X-4, para el \
perfil de la máquina de impresión que se le indicó.",
    unclaimed: "Este ejemplar no declara la conformidad con ninguna norma: PDF/VT se \
apoya en PDF/X-4, que exige el perfil de la máquina en la que se \
imprime la tirada. Indíquelo en la línea de comandos y el mismo archivo \
declarará ambas.",
    press: "Perfil de la máquina de impresión indicado en la línea de comandos",
};

/// The letters in Italian.
const ITALIAN: Words = Words {
    title: "Lettere di rinnovo degli abbonamenti, stagione 2027",
    tagline: "Sala da concerto · stagione 2027",
    member: "N. abbonato",
    sent: "inviata il",
    heading: "Il Suo posto per la stagione 2027",
    greeting: "Gentile {name},",
    body: "Il Suo abbonamento scade con l’ultimo concerto di questa stagione. Per \
conservare il posto {seat} anche nel 2027, La preghiamo di rinnovarlo entro \
il {date}. L’importo indicato qui sotto è già al netto del Suo sconto \
fedeltà.",
    tiers: [
        "Abbonamento intera stagione",
        "Abbonamento mezza stagione",
        "Abbonamento studenti",
        "Abbonamento sostenitore",
    ],
    discount: "Sconto fedeltà: {seasons} stagioni con noi",
    total: "Totale da pagare",
    closing: "Risponda a questa lettera o chiami la biglietteria entro il {date}. \
Saremo lieti di rivederLa in sala.",
    signature: "La biglietteria",
    note_title: "Quattro lettere, una sola impaginazione, un solo file",
    note: "Queste quattro lettere hanno la stessa impaginazione e cambiano soltanto per \
destinatario, posto e importo: è proprio questo che il file comunica alla \
macchina da stampa. Ogni lettera è una parte a sé del documento e ne indica \
il destinatario, il numero di abbonato, il CAP e l’importo dovuto. \
L’intestazione e questa nota sono un unico oggetto grafico, collocato su \
ogni pagina e contrassegnato perché il RIP lo elabori una sola volta e lo \
conservi per l’intero file. È la stampa a dati variabili: una tiratura di \
migliaia di lettere personalizzate inviata alla macchina in un solo file e \
stampata alla massima velocità.",
    claimed: "Questo file dichiara la conformità a PDF/VT-1, basato su PDF/X-4, per il \
profilo della macchina da stampa che gli è stato fornito.",
    unclaimed: "Questa copia non dichiara alcuna norma: PDF/VT si fonda su PDF/X-4, che \
richiede il profilo della macchina su cui si stampa la tiratura. Lo si \
indichi sulla riga di comando e lo stesso file dichiarerà la conformità \
a entrambe.",
    press: "Profilo della macchina da stampa fornito sulla riga di comando",
};

/// The letters in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Cartas de renovação da assinatura, temporada 2027",
    tagline: "Sala de concertos · temporada 2027",
    member: "N.º de assinante",
    sent: "enviada a",
    heading: "O seu lugar na temporada 2027",
    greeting: "Caro(a) {name},",
    body: "A sua assinatura termina com o último concerto desta temporada. Para manter \
o lugar {seat} em 2027, renove-a antes de {date}. O montante abaixo já \
inclui o seu desconto de fidelidade.",
    tiers: [
        "Assinatura de temporada completa",
        "Assinatura de meia temporada",
        "Assinatura de estudante",
        "Assinatura de mecenas",
    ],
    discount: "Desconto de fidelidade, {seasons} temporadas connosco",
    total: "A pagar",
    closing: "Responda a esta carta ou telefone para a bilheteira antes de {date}. \
Contamos com a sua presença na sala.",
    signature: "A bilheteira",
    note_title: "Quatro cartas, uma paginação, um ficheiro",
    note: "Estas quatro cartas partilham a mesma paginação e só diferem no \
destinatário, no lugar e no montante. E o ficheiro di-lo à máquina de \
impressão. Cada carta é uma parte própria do documento, com o destinatário, \
o número de assinante, o código postal e o montante devido. O cabeçalho e \
esta nota são um único objeto gráfico, colocado em todas as páginas e \
marcado para ser rasterizado uma só vez e conservado para todo o ficheiro. \
Isto é impressão de dados variáveis: uma tiragem de milhares de cartas \
personalizadas enviada à máquina como um só ficheiro e impressa à velocidade \
máxima.",
    claimed: "Este ficheiro declara conformidade com PDF/VT-1, assente em PDF/X-4, para \
o perfil da máquina de impressão que lhe foi fornecido.",
    unclaimed: "Esta cópia não declara conformidade com nenhuma norma: o PDF/VT assenta \
no PDF/X-4, que exige o perfil da máquina de impressão onde a tiragem é \
feita. Indique-o na linha de comandos e o mesmo ficheiro passa a \
declarar as duas.",
    press: "Perfil da máquina de impressão indicado na linha de comandos",
};

/// The letters in Dutch.
const DUTCH: Words = Words {
    title: "Verlengingsbrieven seizoen 2027",
    tagline: "Concertzaal · seizoen 2027",
    member: "Abonneenr.",
    sent: "verstuurd op",
    heading: "Uw plaats in seizoen 2027",
    greeting: "Beste {name},",
    body: "Uw abonnement loopt af na het laatste concert van dit seizoen. Wilt u plaats \
{seat} ook in 2027 houden, verleng dan vóór {date}. Op het bedrag hieronder \
is uw loyaliteitskorting al in mindering gebracht.",
    tiers: [
        "Abonnement hele seizoen",
        "Abonnement half seizoen",
        "Studentenabonnement",
        "Begunstigersabonnement",
    ],
    discount: "Loyaliteitskorting, al {seasons} seizoenen bij ons",
    total: "Te betalen",
    closing: "Beantwoord deze brief of bel vóór {date} met de klantenservice. We zien u \
graag terug in de zaal.",
    signature: "De klantenservice",
    note_title: "Vier brieven, één opmaak, één bestand",
    note: "Deze vier brieven hebben dezelfde opmaak en verschillen alleen in ontvanger, \
plaats en bedrag. Dat staat ook in het bestand voor de drukpers. Elke brief \
is een eigen documentdeel met de ontvanger, het abonneenummer, de postcode \
en het verschuldigde bedrag. Het briefhoofd en deze notitie vormen één \
gedeeld grafisch object dat op elke pagina staat en zo is gemarkeerd dat de \
RIP het één keer rastert en voor het hele bestand bewaart. Dit is drukken \
met variabele data: een oplage van duizenden persoonlijke brieven die als \
één bestand naar de drukpers gaat en op volle snelheid wordt gedrukt.",
    claimed: "Dit bestand verklaart te voldoen aan PDF/VT-1, op basis van PDF/X-4, voor \
het opgegeven ICC-profiel van de drukpers.",
    unclaimed: "Dit exemplaar verklaart aan geen enkele norm te voldoen: PDF/VT bouwt \
voort op PDF/X-4, en daarvoor is het ICC-profiel nodig van de drukpers \
waarop de oplage wordt gedrukt. Geef dat profiel op via de \
opdrachtregel, dan verklaart hetzelfde bestand aan beide te voldoen.",
    press: "ICC-profiel van de drukpers, opgegeven via de opdrachtregel",
};

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

/// An amount, with a space between its thousands, a point before its cents and
/// a hyphen before it when it is taken off.
fn money(cents: i64) -> String {
    let sign = if cents < 0 { "-" } else { "" };
    let (whole, fraction) = (cents.abs() / 100, cents.abs() % 100);
    let digits = whole.to_string();
    let mut grouped = String::with_capacity(digits.len() + 4);
    for (index, digit) in digits.chars().enumerate() {
        if index > 0 && (digits.len() - index) % 3 == 0 {
            grouped.push(' ');
        }
        grouped.push(digit);
    }
    format!("{sign}{grouped}.{fraction:02} EUR")
}

/// The flow the letter sets its words in, at `size` points on `leading`.
fn ink_flow(handle: &FontHandle, size: f64, leading: f64) -> TextFlow<'_> {
    TextFlow::new(handle, size).leading(leading).color(INK)
}

/// The flow one row of the amounts sets its label in, and its amount.
fn row_flow(handle: &FontHandle) -> TextFlow<'_> {
    ink_flow(handle, 10.5, 14.0)
}

/// The flow the note at the foot of every page is set in.
fn note_flow(handle: &FontHandle) -> TextFlow<'_> {
    TextFlow::new(handle, NOTE_TYPE.0)
        .leading(NOTE_TYPE.1)
        .color(NOTE_INK)
}

/// Sets `text` in `flow` across `width` points from `x`, its top at `top`, and
/// returns how tall it stands.
fn set(
    content: &mut Content,
    flow: &TextFlow<'_>,
    text: &str,
    x: f64,
    top: f64,
    width: f64,
) -> Result<f64, Error> {
    let lines = flow.break_lines(text, width);
    content.begin_text();
    flow.draw(content, &lines, x, top, width)?;
    content.end_text();
    Ok(flow.height(&lines))
}

/// The words of the note at the foot of every page, its last line saying
/// whether the file claims PDF/VT.
const fn note_lines(words: &Words, claims: bool) -> [&'static str; 2] {
    [
        words.note,
        if claims {
            words.claimed
        } else {
            words.unclaimed
        },
    ]
}

/// Sets the letterhead and the note on `content`, and returns where the note's
/// last line ends, in points up from the foot of the sheet.
fn shared(
    content: &mut Content,
    handle: &FontHandle,
    words: &Words,
    claims: bool,
) -> Result<f64, Error> {
    content.save_state();
    content.set_fill(BAND)?;
    content
        .rect(0.0, HEAD_BOTTOM, SHEET.0, SHEET.1 - HEAD_BOTTOM)?
        .fill();
    content.set_fill(NOTE_FILL)?;
    content
        .rect(
            MARGIN - NOTE_INSET,
            NOTE_BAND.0,
            NOTE_WIDTH,
            NOTE_BAND.1 - NOTE_BAND.0,
        )?
        .fill();

    let name = TextFlow::new(handle, 20.0).leading(24.0).color(ON_BAND);
    set(content, &name, SENDER, MARGIN, 822.0, WIDTH)?;
    let tagline = TextFlow::new(handle, 9.5).leading(12.0).color(ON_BAND);
    set(content, &tagline, words.tagline, MARGIN, 792.0, WIDTH)?;

    let mut top = NOTE_BAND.1 - NOTE_INSET;
    let heading = TextFlow::new(handle, 10.5).leading(14.0).color(NOTE_INK);
    top -= set(content, &heading, words.note_title, MARGIN, top, WIDTH)? + 3.0;
    let note = note_flow(handle);
    for line in note_lines(words, claims) {
        top -= set(content, &note, line, MARGIN, top, WIDTH)? + 4.0;
    }
    content.restore_state();
    Ok(top + 4.0)
}

/// The drawing every page shares: the letterhead and the note, marked for a
/// press to render once and keep for the whole file, and written
/// self-contained.
fn shared_drawing(handle: &FontHandle, words: &Words, claims: bool) -> Result<Drawing, Error> {
    let mut content = Content::new();
    shared(&mut content, handle, words, claims)?;
    let hints = ReuseHints::new()
        .with_identity(SHARED_IDENTITY)?
        .with_scope(ReuseScope::File);
    Ok(Drawing::new(content, Rect::new(0.0, 0.0, SHEET.0, SHEET.1))
        .with_reuse(Some(hints))
        .encapsulated())
}

/// Sets the letter to `recipient` in `words` onto `content`, from under the
/// letterhead down, and returns where its last line ends, in points up from the
/// foot of the sheet.
fn letter(
    content: &mut Content,
    handle: &FontHandle,
    words: &Words,
    recipient: &Recipient,
) -> Result<f64, Error> {
    content.save_state();
    let mut top = 728.0;

    let address = ink_flow(handle, 11.0, 14.0);
    for line in [
        recipient.name,
        recipient.street,
        &format!("{} {TOWN}", recipient.postcode),
    ] {
        top -= set(content, &address, line, MARGIN, top, WIDTH)?;
    }
    top -= 22.0;

    let small = ink_flow(handle, 9.0, 12.0);
    let reference = format!(
        "{} {} · {} {SENT}",
        words.member, recipient.number, words.sent
    );
    top -= set(content, &small, &reference, MARGIN, top, WIDTH)? + 28.0;

    let heading = ink_flow(handle, 17.0, 21.0);
    top -= set(content, &heading, words.heading, MARGIN, top, WIDTH)? + 14.0;

    let body = ink_flow(handle, 10.5, 15.0);
    let greeting = words.greeting.replace("{name}", recipient.name);
    top -= set(content, &body, &greeting, MARGIN, top, WIDTH)? + 6.0;
    let said = words
        .body
        .replace("{seat}", recipient.seat)
        .replace("{date}", DEADLINE);
    top -= set(content, &body, &said, MARGIN, top, WIDTH)? + 16.0;

    let label = row_flow(handle);
    let amount = row_flow(handle).align(Align::Right);
    let discount = words
        .discount
        .replace("{seasons}", &recipient.seasons.to_string());
    for (what, cents) in [
        (words.tiers[recipient.tier], recipient.price),
        (discount.as_str(), -recipient.discount),
    ] {
        set(content, &label, what, MARGIN, top, LABEL_WIDTH)?;
        set(
            content,
            &amount,
            &money(cents),
            MARGIN + LABEL_WIDTH,
            top,
            AMOUNT_WIDTH,
        )?;
        top -= ROW;
    }
    content.set_stroke(RULE)?.set_line_width(0.5)?;
    content
        .move_to(MARGIN, top - 2.0)?
        .line_to(MARGIN + WIDTH, top - 2.0)?
        .stroke();
    top -= 8.0;
    set(content, &label, words.total, MARGIN, top, LABEL_WIDTH)?;
    set(
        content,
        &amount,
        &money(recipient.due()),
        MARGIN + LABEL_WIDTH,
        top,
        AMOUNT_WIDTH,
    )?;
    top -= ROW + 12.0;

    let closing = words.closing.replace("{date}", DEADLINE);
    top -= set(content, &body, &closing, MARGIN, top, WIDTH)? + 14.0;
    top -= set(content, &body, words.signature, MARGIN, top, WIDTH)?;
    top -= set(content, &body, SENDER, MARGIN, top, WIDTH)?;
    content.restore_state();
    Ok(top)
}

/// What one letter states about itself, for the press that prints it.
fn stated(recipient: &Recipient) -> Result<PartData, Error> {
    #[expect(
        clippy::cast_precision_loss,
        reason = "an amount in cents of a letter stays far below 2^53"
    )]
    let due = recipient.due() as f64 / 100.0;
    PartData::new()
        .set("Recipient", recipient.name)?
        .set("MemberNumber", recipient.number)?
        .set("Postcode", recipient.postcode)?
        .set("AmountDue", PartValue::Real(due))
}

/// The hierarchy: one part per letter, each taking the next page, under the
/// part that is the whole mailing.
fn hierarchy() -> Result<DocumentParts, Error> {
    let mut mailing = DocumentPart::new();
    for recipient in &RECIPIENTS {
        mailing = mailing.child(DocumentPart::new().next_pages(1).data(stated(recipient)?));
    }
    DocumentParts::new(mailing)
        .node_names(["Mailing", "Recipient"])
        .map(|parts| parts.record_level(1))
}

/// The four letters as one file, claiming PDF/VT-1 on PDF/X-4 when `press` is
/// the profile of a press, and nothing otherwise.
fn build(
    words: &Words,
    font: &[u8],
    press: Option<&[u8]>,
) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    let mut facts = Metadata::default();
    facts.title = Some(words.title.to_owned());
    facts.producer = Some("hqf-pdf".to_owned());
    facts.created = Some(MADE.to_owned());
    facts.trapped = Some(Trapped::No);
    // The print standard asks for the program the job was made with.
    facts.creator = press.map(|_| "hqf-pdf".to_owned());
    doc.set_metadata(facts);

    if let Some(profile) = press {
        let described = icc::space(profile).ok_or("the press profile must describe CMYK")?;
        doc.set_output_intent(OutputIntent::new(
            IccBased::new(profile, described)?,
            CUSTOM,
            words.press,
        )?);
        doc.set_print_conformance(PdfX::X4);
        doc.set_variable_print_conformance(PdfVt::Vt1);
        doc.set_version(Version::V1_6);
    } else {
        doc.set_version(Version::V2_0);
    }

    let handle = doc.add_font(Font::parse(font.to_vec())?);
    let background = doc.add_drawing(shared_drawing(&handle, words, press.is_some())?);

    for recipient in &RECIPIENTS {
        let mut content = Content::new();
        content.draw_form(background.name(), 0.0, 0.0, 1.0)?;
        letter(&mut content, &handle, words, recipient)?;
        let mut page = Page::new(SHEET.0, SHEET.1);
        page.content = content.into_bytes();
        page.trim = Some(Rect::new(0.0, 0.0, SHEET.0, SHEET.1));
        doc.add_page(page)?;
    }
    doc.set_document_parts(hierarchy()?);
    Ok(doc.to_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 languages do not overwrite each other in `tmp/`.
    let out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("variable_print")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);
    let press = args.next().map(fs::read).transpose()?;

    let bytes = build(words, &fs::read(&font_path)?, press.as_deref())?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;
    println!(
        "wrote {out}: {} bytes, {} letters, {}",
        bytes.len(),
        RECIPIENTS.len(),
        if press.is_some() {
            "claiming PDF/VT-1 on PDF/X-4"
        } else {
            "claiming nothing"
        }
    );
    Ok(())
}

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

    use super::{
        AMOUNT_WIDTH, LABEL_WIDTH, NOTE_BAND, NOTE_INSET, RECIPIENTS, WORDS, build, default_font,
        language, letter, money, row_flow, shared,
    };

    /// How close above the note's band the letter may come, in points.
    const NOTE_GAP: f64 = 20.0;

    /// The font the letters are set in, to measure what they set.
    fn handle() -> FontHandle {
        let mut doc = Document::new();
        doc.add_font(Font::parse(std::fs::read(default_font()).unwrap()).unwrap())
    }

    /// The lines two languages are allowed to write the same way: what is left
    /// to pay is said the same way in Spanish and in Portuguese.
    const SPARED: [&str; 1] = [r#"total: "A pagar""#];

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

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

    #[test]
    fn every_language_holds_each_row_on_one_line_and_each_letter_above_the_note() {
        let handle = handle();
        let label = row_flow(&handle);

        for (language, words) in &WORDS {
            let code = language.code();
            for recipient in &RECIPIENTS {
                let discount = words
                    .discount
                    .replace("{seasons}", &recipient.seasons.to_string());
                for row in [words.tiers[recipient.tier], &discount, words.total] {
                    let lines = label.break_lines(row, LABEL_WIDTH);
                    assert_eq!(lines.len(), 1, "{code}: {row} takes two lines");
                }
                assert_eq!(
                    label
                        .break_lines(&money(recipient.due()), AMOUNT_WIDTH)
                        .len(),
                    1,
                    "{code}: an amount takes two lines"
                );
                let bottom = letter(&mut Content::new(), &handle, words, recipient).unwrap();
                assert!(
                    bottom >= NOTE_BAND.1 + NOTE_GAP,
                    "{code}: the letter to {} ends {bottom} pt up from the foot of the sheet, \
                     into the note",
                    recipient.name
                );
            }
            for claims in [false, true] {
                let bottom = shared(&mut Content::new(), &handle, words, claims).unwrap();
                assert!(
                    bottom >= NOTE_BAND.0 + NOTE_INSET,
                    "{code}: the note ends {bottom} pt up from the foot of the sheet, inside \
                     the inset of its band"
                );
            }
        }
    }

    #[test]
    fn a_press_profile_makes_the_file_claim_pdf_vt_on_pdf_x() {
        // The header of a press profile, which is all the claim reads of it.
        let mut press = vec![0_u8; 128];
        press[0..4].copy_from_slice(&128_u32.to_be_bytes());
        press[12..16].copy_from_slice(b"prtr");
        press[16..20].copy_from_slice(b"CMYK");
        press[36..40].copy_from_slice(b"acsp");
        let font = std::fs::read(default_font()).unwrap();

        for (language, words) in &WORDS {
            let bytes = build(words, &font, Some(&press)).unwrap();
            assert!(bytes.starts_with(b"%PDF-1.6"), "{}", language.code());
            assert!(
                bytes.windows(8).any(|window| window == b"PDF/VT-1"),
                "{}: the file does not claim PDF/VT-1",
                language.code()
            );
        }
    }
}