write_print_ready.py

Die Python-Datei des Beispiels „Ein für die Druckerei vorbereiteter Bogen“. Ein Bogen, größer als die fertige Seite: Die Farbe läuft drei Millimeter über das Messer hinaus, die Schnittmarken stehen außerhalb davon in einer Farbe, die jede Platte trägt, jede Farbe ist in den vier Druckfarben angegeben, und die Seite nennt das Papier, den Rand der Farbe und den Schnitt. Übergeben Sie ihm das Profil einer Druckmaschine, und er beansprucht PDF/X-4, und der Bogen druckt auf sich selbst, auf welchem Profil er steht.

Python 946 Zeilen

Wofür dieses Beispiel da ist

Eine Druckerei verbringt ihren Tag damit, Dateien zu öffnen, zu denen sie Fragen stellen muss: Reicht die Farbe etwas über die Linie hinaus, der das Messer folgen wird, wo genau liegt diese Linie, sind die Farben in den Druckfarben einer Druckmaschine oder in den Farben eines Bildschirms angegeben. Dieser Bogen beantwortet alles, bevor jemand zurückschreibt. Das Papier ist absichtlich größer als die fertige Seite: 472 mal 692 typografische Punkt Bogen für eine fertige Seite von 400 mal 620. Auf jeder Seite stehen sechsunddreißig dieser Punkt, neun davon, damit die Farbe über den Schnitt hinauslaufen kann, und der Rest, damit die Schnittmarken außerhalb davon Platz haben. Die Seite nennt alle drei: das Papier, wie weit die Farbe über den Schnitt hinausläuft, und den Schnitt selbst.

Was dieses Beispiel zeigt

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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
"""A sheet a printer can run without asking the sender a single question.

The Python twin of the `write_print_ready` example in Rust. 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: python examples/write_print_ready.py [out.pdf] [font.ttf] [press.icc]
       HQF_PDF_LANG=fr python examples/write_print_ready.py
"""

from __future__ import annotations

import sys
from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The date the document says it was made on, so that two runs of the example produce the
# same bytes.
MADE = "2026-07-25T10:00:00+02:00"

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

# The finished page: where the blade falls, in the sheet's own coordinates.
TRIM = (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.
SHEET = (TRIM[2] + MARGIN + MARGIN, TRIM[3] + MARGIN + MARGIN)

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

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

# The width of one ink swatch, the gap to the next, their bottom edge and their height.
SWATCH = 64.0
SWATCH_GAP = 10.0
SWATCH_Y = 292.0
SWATCH_HEIGHT = 42.0

# The house sending the sheet, which the footer names before saying what the sheet is.
HOUSE = "HQF Development"

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

# Where the first line of the closing note sits, and how far below one line the next one
# does, in points.
CLOSING_TOP = 104.0
CLOSING_STEP = 12.0

# What each ink swatch is made of, in the order `Words.inks` names them.
MIXES = ["100 0 0 0", "0 100 0 0", "0 0 100 0", "0 0 0 100", "100 100 100 100"]

# 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.
BOXES = ["MediaBox", "BleedBox", "TrimBox"]
ENTRIES = ["Title", "Trapped"]

# What the file writes for the trapping entry, which the page states beside what it
# means.
TRAPPED = "No"

# 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.
CUSTOM = "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.
BUILT_IN = ("sRGB", "sRGB IEC61966-2.1")


@dataclass(frozen=True)
class Words:
    """Every word the sheet is written in, in one 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.
    """

    # What the job is called, on the page and in what the file says of itself.
    title: str
    # What the sheet is headed by.
    heading: str
    # The line under that heading.
    strapline: str
    # What the footer says the sheet is, after the name of the house sending it.
    footer: 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: tuple[str, str, str, str]
    # What each of the five panels is headed by.
    panels: tuple[str, str, str, str, str]
    # The line under the first panel.
    boxes_note: str
    # What each of the three boxes is for, after the size it measures.
    boxes: tuple[str, str, str]
    # The lines under the second panel.
    ink_stops: tuple[str, str, str]
    # The lines under the third panel.
    four_inks: tuple[str, str]
    # What each printing ink is called, in the order the swatches lay them.
    inks: tuple[str, str, str, str, str]
    # The lines under the fourth panel.
    marks: tuple[str, str, str]
    # What the last two pairs the page states are called.
    stated_for: str
    claim: str
    # What the trapping entry means, after the word the file writes.
    trapped: str
    # What stands before and after the size of the profile the file is stated for.
    profile_of: str
    bytes: str
    # What the claim says when the file makes none.
    no_claim: str
    # What the condition a profile off the command line describes is called.
    custom_info: str
    # The closing note of a file that claims the print standard.
    claimed: tuple[str, str, str, str, str]
    # The closing note of a file that claims nothing.
    unclaimed: tuple[str, str, str, str, str]


# The sheet in English.
ENGLISH = 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.
FRENCH = Words(
    title="Catalogue de printemps, couverture",
    heading="Prête pour l’impression",
    strapline="Une feuille remise sans laisser la moindre question à l’imprimeur.",
    footer="une feuille, prête pour le tirage",
    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 restent 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 va jusqu’à une boîte "
         "intermédiaire.")
    ),
    boxes=(
        "la feuille entière, repères compris",
        "jusqu’où va l’encre",
        "où tombe la lame",
    ),
    ink_stops=(
        "Le bandeau en tête de page dépasse la lame de 9 points sur trois côtés,",
        "et la barre du pied fait de même. Une lame qui tombe un point à côté",
        "tombe encore dans l’encre : la page finie n’a aucun bord blanc.",
    ),
    four_inks=(
        ("Chaque couleur de cette page est exprimée dans les quatre encres "
         "d’imprimerie. Une"),
        ("couleur d’écran devrait être séparée par quelqu’un, et ce quelqu’un serait "
         "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 présent sur chaque plaque est celui sur lequel la presse "
         "cale ses plaques."),
    ),
    stated_for="Déclarée pour",
    claim="Revendication",
    trapped="indiqué 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, grâce au 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 la refuse si le fichier ne contient pas le profil de presse, un"
         " titre,"),
        ("une mention du grossi-maigri et une boîte de coupe par page. Les quatre y "
         "sont."),
    ),
    unclaimed=(
        ("Ce fichier ne revendique pas PDF/X-4. Cette revendication promet à "
         "l’imprimeur"),
        ("qu’il peut tirer le fichier sans question, et la promesse repose sur le "
         "profil de la"),
        ("presse pour laquelle le travail a été séparé. La bibliothèque ne fournit "
         "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.",
    ),
)

# The sheet in Dutch.
DUTCH = Words(
    title="Voorjaarscatalogus, omslag",
    heading="Klaar voor de pers",
    strapline=(
        "Eén blad, aangeleverd zonder dat de drukker iets hoeft te vragen."
    ),
    footer="één blad, klaar om te drukken",
    slug=("blad", "snijlijn", "afloop", "CMYK"),
    panels=(
        "De drie kaders die dit blad noemt",
        "Waar de inkt ophoudt",
        "Vier inkten, geen drie",
        "De tekens staan buiten de inkt",
        "Wat het bestand over zichzelf zegt",
    ),
    boxes_note=(
        "Het papier is groter dan de afgewerkte pagina; de inkt loopt tot een kader "
        "ertussen."
    ),
    boxes=(
        "het hele blad, met tekens en al",
        "hoe ver de inkt loopt",
        "waar het mes valt",
    ),
    ink_stops=(
        "De band bovenaan deze pagina loopt aan drie kanten 9 punten voorbij het mes,",
        "en de balk onderaan doet hetzelfde. Een mes dat een punt verkeerd",
        "valt, valt nog in de inkt, dus de afgewerkte pagina heeft geen witte rand.",
    ),
    four_inks=(
        "Elke kleur op deze pagina is uitgedrukt in de vier drukinkten. Een "
        "schermkleur",
        "zou door iemand gescheiden moeten worden, en die iemand is de drukker.",
    ),
    inks=("Cyaan", "Magenta", "Geel", "Zwart", "Register"),
    marks=(
        "De hoektekens staan voorbij de afloop, dus neemt het mes ze mee",
        "met de rest van het papier. Ze liggen in alle vier inkten tegelijk: een",
        "teken dat op elke plaat drukt, is een teken waarop de pers haar platen "
        "uitlijnt.",
    ),
    stated_for="Vermeld voor",
    claim="Claim",
    trapped="in het bestand vermeld, niet onbekend gelaten",
    profile_of="een profiel van",
    bytes="bytes",
    no_claim="geen: de notitie hieronder zegt waarom",
    custom_info="Een persprofiel meegegeven op de opdrachtregel",
    claimed=(
        "Dit bestand claimt PDF/X-4, via het profiel dat op de opdrachtregel is meegegeven.",
        "De claim staat er twee keer: de uitvoerintentie staat ervoor in als",
        "GTS_PDFX, en de metadata noemt het geclaimde deel. De bibliotheek weigert de",
        "claim tenzij het bestand het persprofiel, een titel, een woord over trapping",
        "en een snijkader op elke pagina bevat. Alle vier zijn aanwezig.",
    ),
    unclaimed=(
        "Dit bestand claimt geen PDF/X-4. Die claim belooft een drukkerij dat ze het bestand",
        "kan drukken zonder terug te vragen, en die belofte rust op het profiel van de",
        "pers waarvoor het werk gescheiden is. De bibliotheek bouwt één profiel, sRGB, en",
        "sRGB beschrijft een scherm: het mag niet voor een pers invallen. Geef een persprofiel",
        "mee op de opdrachtregel en hetzelfde blad claimt PDF/X-4.",
    ),
)

# The sheet in Portuguese.
PORTUGUESE = Words(
    title="Catálogo de primavera, capa",
    heading="Pronto para a gráfica",
    strapline=(
        "Uma folha, entregue sem nada que o impressor tenha de perguntar."
    ),
    footer="uma folha, pronta a imprimir",
    slug=("folha", "corte", "sangria", "CMYK"),
    panels=(
        "As três caixas que esta folha indica",
        "Onde a tinta para",
        "Quatro tintas, não três",
        "As marcas ficam fora da tinta",
        "O que o ficheiro diz de si mesmo",
    ),
    boxes_note=(
        "O papel é maior do que a página acabada; a tinta vai até uma caixa "
        "intermédia."
    ),
    boxes=(
        "a folha toda, marcas incluídas",
        "até onde vai a tinta",
        "onde cai a lâmina",
    ),
    ink_stops=(
        "A faixa no topo desta página passa 9 pontos da lâmina em três",
        "lados, e a barra no pé faz o mesmo. Uma lâmina que caia um ponto",
        "ao lado continua a cair na tinta, por isso a página acabada não tem margem branca.",
    ),
    four_inks=(
        "Cada cor desta página é dita nas quatro tintas de impressão. Uma cor de ecrã",
        "teria de ser separada por alguém, e esse alguém é o impressor.",
    ),
    inks=("Ciano", "Magenta", "Amarelo", "Preto", "Registo"),
    marks=(
        "As marcas de canto são desenhadas para lá da sangria, por isso a lâmina "
        "leva-as",
        "com o resto do papel. São postas nas quatro tintas ao mesmo tempo: uma",
        "marca que imprime em cada chapa é a marca pela qual a máquina alinha as "
        "chapas.",
    ),
    stated_for="Indicado para",
    claim="Declaração",
    trapped="dito no ficheiro, não deixado por saber",
    profile_of="um perfil de",
    bytes="bytes",
    no_claim="nenhum: a nota abaixo diz porquê",
    custom_info="Um perfil de impressão passado na linha de comandos",
    claimed=(
        "Este ficheiro declara PDF/X-4, através do perfil passado na linha de comandos.",
        "A declaração é escrita duas vezes: a intenção de saída responde por ela como",
        "GTS_PDFX, e os metadados nomeiam a parte declarada. A biblioteca recusa a",
        "declaração se o ficheiro não levar o perfil de impressão, um título, uma indicação sobre",
        "trapping e uma caixa de corte em cada página. Estão cá as quatro.",
    ),
    unclaimed=(
        "Este ficheiro não declara PDF/X-4. Declará-lo promete a uma gráfica que pode imprimir",
        "o ficheiro sem perguntar nada, e a promessa assenta no perfil da",
        "máquina para a qual o trabalho foi separado. A biblioteca só cria um perfil, o sRGB, e o",
        "sRGB descreve um ecrã, não uma máquina de impressão. Passe um perfil",
        "de impressão na linha de comandos e a mesma folha declara PDF/X-4.",
    ),
)

# The sheet in Italian.
ITALIAN = Words(
    title="Catalogo di primavera, copertina",
    heading="Pronto per la stampa",
    strapline=(
        "Un foglio consegnato senza che il tipografo debba chiedere nulla."
    ),
    footer="un foglio, pronto per la tiratura",
    slug=("foglio", "rifilo", "abbondanza", "CMYK"),
    panels=(
        "I tre riquadri che indica questo foglio",
        "Dove si ferma l’inchiostro",
        "Quattro inchiostri, non tre",
        "I segni stanno fuori dall’inchiostro",
        "Cosa dice di sé il file",
    ),
    boxes_note=(
        "La carta è più grande della pagina finita; l’inchiostro arriva a un riquadro "
        "intermedio."
    ),
    boxes=(
        "tutto il foglio, segni compresi",
        "fin dove arriva l’inchiostro",
        "dove cade la lama",
    ),
    ink_stops=(
        "La fascia in testa a questa pagina supera la lama di 9 punti su tre",
        "lati, e la barra al piede fa lo stesso. Una lama che cade un punto",
        "più in là cade ancora nell’inchiostro, così la pagina finita non ha bordo bianco.",
    ),
    four_inks=(
        "Ogni colore di questa pagina è espresso nei quattro inchiostri da stampa. Un "
        "colore da",
        "schermo andrebbe separato da qualcuno, e quel qualcuno è il tipografo.",
    ),
    inks=("Ciano", "Magenta", "Giallo", "Nero", "Registro"),
    marks=(
        "I segni d’angolo sono disegnati oltre l’abbondanza, così la lama li porta via",
        "con il resto della carta. Sono posati nei quattro inchiostri insieme: un",
        "segno che si stampa su ogni lastra è quello su cui la macchina allinea le "
        "lastre.",
    ),
    stated_for="Indicato per",
    claim="Dichiarazione",
    trapped="detto nel file, non lasciato ignoto",
    profile_of="un profilo di",
    bytes="byte",
    no_claim="nessuno: la nota qui sotto dice perché",
    custom_info="Un profilo da stampa passato sulla riga di comando",
    claimed=(
        "Questo file dichiara PDF/X-4, tramite il profilo passato sulla riga di comando.",
        "La dichiarazione è scritta due volte: l’intento di uscita ne risponde come",
        "GTS_PDFX, e i metadati nominano la parte dichiarata. La libreria rifiuta la",
        "dichiarazione se il file non porta il profilo da stampa, un titolo, un’indicazione",
        "sul trapping e un riquadro di rifilo su ogni pagina. Qui ci sono tutti e quattro.",
    ),
    unclaimed=(
        "Questo file non dichiara PDF/X-4. Dichiararlo promette a una tipografia che può stampare",
        "il file senza chiedere nulla, e la promessa poggia sul profilo della",
        "macchina per cui il lavoro è stato separato. La libreria costruisce un profilo, sRGB, e",
        "sRGB descrive uno schermo: non può fare le veci di una macchina da stampa. Passate un",
        "profilo da stampa sulla riga di comando e lo stesso foglio dichiara PDF/X-4.",
    ),
)

# The sheet in Spanish.
SPANISH = Words(
    title="Catálogo de primavera, cubierta",
    heading="Listo para la imprenta",
    strapline=(
        "Una hoja, entregada sin nada que el impresor tenga que preguntar."
    ),
    footer="una hoja, lista para tirar",
    slug=("hoja", "corte", "sangrado", "CMYK"),
    panels=(
        "Las tres cajas que indica esta hoja",
        "Dónde acaba la tinta",
        "Cuatro tintas, no tres",
        "Las marcas quedan fuera de la tinta",
        "Lo que el archivo dice de sí mismo",
    ),
    boxes_note=(
        "El papel es mayor que la página acabada; la tinta llega a una caja "
        "intermedia."
    ),
    boxes=(
        "la hoja entera, marcas incluidas",
        "hasta dónde llega la tinta",
        "dónde cae la cuchilla",
    ),
    ink_stops=(
        "La banda de cabeza de esta página pasa 9 puntos de la cuchilla por tres",
        "lados, y la barra del pie hace lo mismo. Una cuchilla que cae un punto",
        "desviada sigue cayendo en tinta, así que la página acabada no tiene borde blanco.",
    ),
    four_inks=(
        "Cada color de esta página se expresa en las cuatro tintas de imprenta. Un "
        "color de",
        "pantalla tendría que separarlo alguien, y ese alguien es el impresor.",
    ),
    inks=("Cian", "Magenta", "Amarillo", "Negro", "Registro"),
    marks=(
        "Las marcas de esquina se dibujan más allá del sangrado, así que la cuchilla",
        "se las lleva con el resto del papel. Van en las cuatro tintas a la vez: una",
        "marca que se imprime en cada plancha es la que usa la prensa para alinearlas.",
    ),
    stated_for="Indicado para",
    claim="Declaración",
    trapped="indicado en el archivo, no dejado sin definir",
    profile_of="un perfil de",
    bytes="bytes",
    no_claim="ninguno: la nota de abajo dice por qué",
    custom_info="Un perfil de imprenta pasado en la línea de órdenes",
    claimed=(
        "Este archivo declara PDF/X-4, mediante el perfil pasado en la línea de órdenes.",
        "La declaración se escribe dos veces: la intención de salida responde de ella",
        "como GTS_PDFX, y los metadatos nombran la parte declarada. La biblioteca rechaza",
        "la declaración salvo que el archivo lleve el perfil de imprenta, un título, una indicación",
        "de reventado y una caja de corte en cada página. Aquí están las cuatro.",
    ),
    unclaimed=(
        "Este archivo no declara PDF/X-4. Declararlo promete a una imprenta que puede tirar",
        "el archivo sin preguntar nada, y la promesa descansa en el perfil de la",
        "prensa para la que se separó el trabajo. La biblioteca construye un perfil, sRGB, y",
        "sRGB describe una pantalla: no puede ocupar el lugar de una prensa. Pase un perfil",
        "de imprenta en la línea de órdenes y la misma hoja declara PDF/X-4.",
    ),
)

# The sheet in German.
GERMAN = Words(
    title="Frühjahrskatalog, Umschlag",
    heading="Bereit für die Druckmaschine",
    strapline=(
        "Ein Bogen, übergeben ohne eine offene Frage für die Druckerei."
    ),
    footer="ein Bogen, bereit zum Druck",
    slug=("Bogen", "Endformat", "Anschnitt", "CMYK"),
    panels=(
        "Die drei Rahmen, die dieser Bogen nennt",
        "Wo die Farbe endet",
        "Vier Farben, nicht drei",
        "Die Marken stehen außerhalb der Farbe",
        "Was die Datei über sich sagt",
    ),
    boxes_note=(
        "Das Papier ist größer als die Seite; die Farbe läuft bis zu einem Rahmen "
        "dazwischen."
    ),
    boxes=(
        "der ganze Bogen samt Marken",
        "wie weit die Farbe läuft",
        "wo das Messer fällt",
    ),
    ink_stops=(
        "Das Band oben läuft an drei Seiten 9 Punkt über das",
        "Messer hinaus, die Leiste am Fuß ebenso. Ein Messer, das",
        "einen Punkt danebenfällt, trifft noch Farbe: kein weißer Rand.",
    ),
    four_inks=(
        "Jede Farbe hier ist in den vier Druckfarben angegeben. Eine",
        "Bildschirmfarbe müsste jemand separieren — die Druckerei.",
    ),
    inks=("Cyan", "Magenta", "Gelb", "Schwarz", "Passer"),
    marks=(
        "Die Eckmarken stehen jenseits des Anschnitts; das Messer nimmt sie",
        "mit dem Papier weg. Sie liegen in allen vier Farben zugleich: Eine",
        "Marke auf jeder Platte ist die, nach der die Maschine ausrichtet.",
    ),
    stated_for="Angegeben für",
    claim="Anspruch",
    trapped="in der Datei angegeben, nicht offengelassen",
    profile_of="ein Profil von",
    bytes="Bytes",
    no_claim="keins — der Hinweis unten sagt, warum",
    custom_info="Ein auf der Befehlszeile übergebenes Druckprofil",
    claimed=(
        "Diese Datei beansprucht PDF/X-4, über das Profil der Befehlszeile.",
        "Der Anspruch steht doppelt: Die Ausgabebedingung verbürgt ihn als",
        "GTS_PDFX, die Metadaten nennen den Teil. Die Bibliothek lehnt",
        "ihn ab ohne Druckprofil, Titel, Angabe zur Überfüllung und einen",
        "Endformatrahmen auf jeder Seite. Alle vier sind da.",
    ),
    unclaimed=(
        "Diese Datei beansprucht nicht PDF/X-4. Das verspräche einer Druckerei,",
        "die Datei ohne Rückfrage zu drucken, gestützt auf das Profil der",
        "Maschine, für die separiert wurde. Die Bibliothek baut nur sRGB,",
        "und sRGB beschreibt einen Bildschirm, keine Druckmaschine. Mit einem",
        "Druckprofil auf der Befehlszeile beansprucht derselbe Bogen 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.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}


def band():
    """The band across the head of the sheet, and the bar across its foot."""
    return hqf_pdf.Cmyk(0.85, 0.55, 0.0, 0.25)


def on_band():
    """The line under the title, on the band."""
    return hqf_pdf.Cmyk(0.22, 0.1, 0.0, 0.0)


def heading_ink():
    """A panel's heading."""
    return hqf_pdf.Cmyk(0.0, 0.0, 0.0, 1.0)


def body_ink():
    """A panel's body."""
    return hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.72)


def label_ink():
    """What a stated pair is called."""
    return hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.5)


def value_ink():
    """What it says."""
    return hqf_pdf.Cmyk(0.0, 0.0, 0.0, 0.85)


def registration():
    """All four inks at once, which prints on every plate."""
    return hqf_pdf.Cmyk(1.0, 1.0, 1.0, 1.0)


def inks():
    """The colour each swatch is laid in, in the order `Words.inks` names them."""
    return [
        hqf_pdf.Cmyk(1.0, 0.0, 0.0, 0.0),
        hqf_pdf.Cmyk(0.0, 1.0, 0.0, 0.0),
        hqf_pdf.Cmyk(0.0, 0.0, 1.0, 0.0),
        hqf_pdf.Cmyk(0.0, 0.0, 0.0, 1.0),
        registration(),
    ]


def trim():
    """Where the blade falls."""
    return hqf_pdf.Rect(TRIM[0], TRIM[1], TRIM[2], TRIM[3])


def bleed():
    """What the ink runs to."""
    return hqf_pdf.Rect(
        TRIM[0] - BLEED_OVER,
        TRIM[1] - BLEED_OVER,
        TRIM[2] + BLEED_OVER + BLEED_OVER,
        TRIM[3] + BLEED_OVER + BLEED_OVER,
    )


def flood(content, font, words):
    """Draw the flood at the head of the sheet and the bar at its foot.

    Both run to the ink's own box and off the blade on three sides.
    """
    ink = bleed()
    top = ink.y + ink.height

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

    content.save_state()
    content.set_fill(hqf_pdf.Cmyk.white())
    content.draw_text(font, HEADING_SIZE, LEFT, 620.0, words.heading)
    content.draw_text(font, 7.0, LEFT, 38.0, f"{HOUSE} — {words.footer}")
    content.set_fill(on_band())
    content.draw_text(font, STRAPLINE, LEFT, 600.0, words.strapline)
    content.restore_state()


def corner_marks(content):
    """Draw the four corner marks.

    Each pair of arms stands outside the ink and points at a corner of the
    finished page. They are laid in all four inks at once, so that each plate
    carries them.
    """
    left, bottom, width, height = TRIM
    right = left + width
    top = bottom + height
    near = BLEED_OVER
    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()


def slug_line(words):
    """What the line in the margin says: the job, then each box the paper takes."""
    sheet_word, trim_word, bleed_word, inks_word = words.slug
    return (
        f"{words.title} — {SHEET[0]:g} × {SHEET[1]:g} {sheet_word}"
        f" — {TRIM[2]:g} × {TRIM[3]:g} {trim_word}"
        f" — {BLEED_OVER:g} pt {bleed_word} — {inks_word}"
    )


def slug(content, font, words):
    """Draw the line in the margin naming the job.

    The blade takes it away with the rest of the paper outside the finished page.
    """
    content.save_state()
    content.set_fill(registration())
    content.draw_text(font, SLUG, LEFT, 14.0, slug_line(words))
    content.restore_state()


def panel(content, font, y, title, lines):
    """Draw one panel: its heading, and the lines of body under it."""
    content.save_state()
    content.set_fill(heading_ink())
    content.draw_text(font, PANEL, LEFT, y, title)
    content.set_fill(body_ink())
    line_y = y - 15.0
    for line in lines:
        content.draw_text(font, PANEL_BODY, LEFT, line_y, line)
        line_y -= 12.0
    content.restore_state()


def stated(content, font, top, pairs):
    """Draw a run of stated pairs, one to a line.

    What each is called on the left, and what it says beside it.
    """
    y = top
    for label, value in pairs:
        content.save_state()
        content.set_fill(label_ink())
        content.draw_text(font, PAIR, LEFT, y, label)
        content.set_fill(value_ink())
        content.draw_text(font, PAIR, LEFT + COLUMN, y, value)
        content.restore_state()
        y -= 14.0


def swatches(content, font, words):
    """Draw one swatch per printing ink, each at full strength.

    Under each stands the name of the ink and the four numbers that say it.
    """
    x = LEFT
    for name, mix, ink in zip(words.inks, MIXES, inks()):
        content.save_state()
        content.set_fill(ink)
        content.rect(x, SWATCH_Y, SWATCH, SWATCH_HEIGHT)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_fill(value_ink())
        content.draw_text(font, SWATCH_NAME, x, SWATCH_Y - 10.0, name)
        content.set_fill(label_ink())
        content.draw_text(font, 7.0, x, SWATCH_Y - 20.0, mix)
        content.restore_state()
        x += SWATCH + SWATCH_GAP


def closing(content, font, words, claims):
    """Draw the closing note: what the file claims, or why it claims nothing."""
    content.save_state()
    content.set_fill(body_ink())
    y = CLOSING_TOP
    for line in words.claimed if claims else words.unclaimed:
        content.draw_text(font, PANEL_BODY, LEFT, y, line)
        y -= CLOSING_STEP
    content.restore_state()


def stated_for():
    """The profile the document is stated for, and what it is called.

    Also whether the print standard is claimed on it: the file named on the
    command line, or the one the library builds.
    """
    if len(sys.argv) > 3:
        return Path(sys.argv[3]).read_bytes(), CUSTOM, None, True
    return hqf_pdf.srgb_icc_profile(), BUILT_IN[0], BUILT_IN[1], False


def box_sizes():
    """The size each of the three boxes measures, in the order the page states them."""
    ink = bleed()
    return [
        (SHEET[0], SHEET[1]),
        (ink.width, ink.height),
        (TRIM[2], TRIM[3]),
    ]


def sheet(font, words, identifier, size, claims):
    """The whole sheet, drawn once."""
    content = hqf_pdf.Content()
    flood(content, font, words)
    corner_marks(content)
    slug(content, font, words)

    panel(content, font, 518.0, words.panels[0], [words.boxes_note])
    stated(
        content,
        font,
        487.0,
        [
            (name, f"{width:g} × {height:g} pt — {says}")
            for name, (width, height), says in zip(BOXES, box_sizes(), words.boxes)
        ],
    )

    panel(content, font, 434.0, words.panels[1], words.ink_stops)

    panel(content, font, 371.0, words.panels[2], words.four_inks)
    swatches(content, font, words)

    panel(content, font, 248.0, words.panels[3], words.marks)

    panel(content, font, 185.0, words.panels[4], [])
    stated(
        content,
        font,
        169.0,
        [
            (ENTRIES[0], words.title),
            (ENTRIES[1], f"{TRAPPED} — {words.trapped}"),
            (
                words.stated_for,
                f"{identifier} — {words.profile_of} {size} {words.bytes}",
            ),
            (words.claim, "PDF/X-4" if claims else words.no_claim),
        ],
    )

    closing(content, font, words, claims)
    return content


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("print_ready.pdf", language)).stem)
    profile, identifier, info, claims = stated_for()

    described = hqf_pdf.icc_profile_space(profile)
    if described is None:
        raise SystemExit("the profile must describe a grey, RGB or CMYK space")
    intent = hqf_pdf.OutputIntent(
        hqf_pdf.IccBased(profile, described), identifier, info or words.custom_info
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    document.set_metadata(
        hqf_pdf.Metadata(
            title=words.title,
            producer="hqf-pdf",
            created=MADE,
            trapped=hqf_pdf.Trapped.No,
        )
    )
    document.set_output_intent(intent)
    if claims:
        document.set_print_conformance(hqf_pdf.PdfX.X4)
        document.set_version(hqf_pdf.Version.V1_6)

    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    page = hqf_pdf.Page(SHEET[0], SHEET[1])
    page.set_content(sheet(font, words, identifier, len(profile), claims))
    page.set_bleed_box(bleed())
    page.set_trim_box(trim())
    document.add_page(page)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, a press sheet stated for {identifier}, "
        f"{'claiming PDF/X-4' if claims else 'claiming nothing'}"
    )


if __name__ == "__main__":
    main()