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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060 | //! Writes an archival cover sheet whose metadata carries fields of its own: a
//! records office's reference, department, retention date and classification.
//!
//! PDF/A accepts metadata no standard ever heard of, but not silently. A
//! property from outside the standard schemas travels with a description of
//! itself — what it is called, how it is to be read, who it is written for, and
//! what it means — or the file is not conformant. One schema says all of that,
//! and the library writes both halves: the properties into the packet, the
//! description into the extension block.
//!
//! The page prints the very fields the packet declares, from one list read
//! twice, so that what a person reads and what a machine reads cannot drift
//! apart.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the sheet is drawn up in. The names the properties are written
//! under are not words: they are what a machine looks them up by, and they are
//! spelled the same way whoever reads the sheet. What each of them says and
//! what each of them means are words, and travel into the packet with the page.
//!
//! A second page declares a second schema, a loan record, whose six fields are
//! read the six other ways a property may be: as a yes or no, a media type, a
//! proper name, a real number, an identifier and an address, and two lists: the
//! witnesses to the loan, in no order, and its changes of hands, in order, each
//! a structure of the record's own invention that the extension block describes
//! field by field, and the conditions of the loan, one text in three languages,
//! each marked with its language. It states the keywords the document carries,
//! when it changed and whether it was trapped, that date as PDF writes it and
//! read back, and weighs the packet the page carries of its own against the
//! same facts claiming three standards.
//!
//! Whether the result is really PDF/A-3 is not for us to say. `veraPDF` says,
//! and `scripts/check_pdfa.sh` asks it.
//!
//! Usage: `cargo run --example write_own_schema -- tmp/own_schema.pdf
//! [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_own_schema --
//! tmp/schema_propre.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::metadata::date;
use hqf_pdf::metadata::xmp::{
self, Claims, Metadata, PdfA, PdfUa, PdfX, Trapped, Xmp, XmpCategory, XmpField, XmpProperty,
XmpSchema, XmpStructType, XmpType, XmpValue, XmpValueType,
};
use hqf_pdf::{Align, Document, Font, FontHandle, Page, TabMethod, TextFlow};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
use language::Language;
/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// When the sheet was drawn up. The library never reads the clock, so the
/// caller says when.
const ISSUED: &str = "2026-07-14T09:30:00+02:00";
/// The namespace the office's properties live in. It is the office's own, and
/// resolves to nothing: a namespace names a set of properties, it is not an
/// address anything fetches.
const NAMESPACE: &str = "https://hqf-pdf.example/ns/records/1.0/";
/// The prefix the office's properties are written with.
const PREFIX: &str = "rec";
/// The namespace the loan record's properties live in.
const LOAN_NAMESPACE: &str = "https://hqf-pdf.example/ns/loans/1.0/";
/// The prefix the loan record's properties are written with.
const LOAN_PREFIX: &str = "loan";
/// When the sheet last changed.
const CHANGED: &str = "2026-09-17T14:05:00+02:00";
/// The loan record's fields: what each is written under, how a validator is to
/// read it, and what it says, which is the same in every language.
const LOAN_FIELDS: [(&str, XmpValueType, &str); 6] = [
("Sealed", XmpValueType::Boolean, "True"),
("Format", XmpValueType::MimeType, "application/pdf"),
("Custodian", XmpValueType::ProperName, "HQF Development"),
("ShelfMetres", XmpValueType::Real, "1.5"),
(
"Series",
XmpValueType::Uri,
"https://hqf-pdf.com/records/series/42",
),
(
"Catalogue",
XmpValueType::Url,
"https://hqf-pdf.com/records/catalogue",
),
];
/// The namespace the fields of a change of hands live in.
const MOVEMENT_NAMESPACE: &str = "https://hqf-pdf.example/ns/loans/movement/1.0/";
/// The prefix the fields of a change of hands are written with.
const MOVEMENT_PREFIX: &str = "mvt";
/// Who witnessed the loan, in no particular order.
const WITNESSES: [&str; 2] = ["Claire Martin", "Jan de Vries"];
/// The conditions of the loan, one text in three languages: each as its
/// language and its text, the one a reader takes by default first.
const CONDITIONS: [(&str, &str); 3] = [
("x-default", "To be returned unopened by 31 December 2026"),
(
"fr",
"À rendre sans l’ouvrir, au plus tard le 31 décembre 2026",
),
("de", "Ungeöffnet bis zum 31. Dezember 2026 zurückzugeben"),
];
/// Each change of hands, in order: the day, and who took the dossier.
const MOVEMENTS: [(&str, &str); 2] = [
("2026-09-01", "Claire Martin"),
("2026-09-17", "HQF Development"),
];
/// One field of the office's own: what it is written under, how a validator is
/// to read it, and who it is written for. What it says and what it means are
/// words, and stand in [`Words`] under the same order.
struct Field {
/// The name the property is written under, which is what a machine looks it
/// up by.
name: &'static str,
/// How a validator is to read the value.
value_type: XmpValueType,
/// Who the property is written for.
category: XmpCategory,
}
/// The fields the sheet carries. The page draws them and the packet declares
/// them, from this one list.
const FIELDS: [Field; 5] = [
Field {
name: "Reference",
value_type: XmpValueType::Text,
category: XmpCategory::External,
},
Field {
name: "Department",
value_type: XmpValueType::Text,
category: XmpCategory::External,
},
Field {
name: "RetainUntil",
value_type: XmpValueType::Date,
category: XmpCategory::Internal,
},
Field {
name: "Classification",
value_type: XmpValueType::Text,
category: XmpCategory::External,
},
Field {
name: "Sheets",
value_type: XmpValueType::Integer,
category: XmpCategory::Internal,
},
];
/// The words the sheet is drawn up in, one set per language.
#[derive(Debug)]
struct Words {
/// What the sheet is called, on the page and in the file's own title.
title: &'static str,
/// The paragraph under the title.
prose: &'static str,
/// The heading over what the sheet says, and the one over what the packet
/// declares of it.
headings: [&'static str; 2],
/// What this sheet says for each field of [`FIELDS`]. A reference, a date
/// and a count are not words; a department and how widely a dossier may be
/// circulated are.
values: [&'static str; 5],
/// What each field of [`FIELDS`] means, which is what the packet carries
/// beside it so that a validator will take it.
descriptions: [&'static str; 5],
/// The note at the foot of the sheet.
note: &'static str,
/// What the records office calls its own metadata, for a person reading the
/// packet.
schema: &'static str,
/// What the file says it is about.
subject: &'static str,
/// The second page's heading.
more_title: &'static str,
/// The paragraph under it.
more_prose: &'static str,
/// What the loan record calls its schema.
loan_schema: &'static str,
/// What each field of the loan record means.
loan_descriptions: [&'static str; 6],
/// What the loan record's two lists and its text in several languages mean:
/// the witnesses, the changes of hands, then the conditions of the loan.
loan_lists: [&'static str; 3],
/// What a change of hands is, then what each of its two fields means: the
/// day, and who took the dossier.
movement: [&'static str; 3],
/// What the schema is declared under; `{namespace}` and `{prefix}` stand
/// for them.
declared: &'static str,
/// The keywords the document carries.
keywords: &'static str,
/// What the document states of itself; `{keywords}`, `{modified}` and
/// `{trapped}` stand for them.
states: &'static str,
/// Whether a document was trapped: yes, no, not known.
trapped: [&'static str; 3],
/// The date of change both ways; `{pdf}` and `{iso}` stand for them.
dates: &'static str,
/// What the packets weigh; `{page}` and `{claimed}` stand for them.
packets: &'static str,
}
impl Words {
/// The words the sheet is drawn up in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
/// What the file calls itself: what the sheet is, then the reference it is
/// filed under.
fn document_title(&self) -> String {
format!("{} {}", self.title, self.values[0])
}
/// The structure a change of hands is written as: the day, and who took the
/// dossier.
fn movement(&self) -> Result<XmpStructType, hqf_pdf::Error> {
let [about, when, holder] = self.movement;
XmpStructType::new(
"Movement",
MOVEMENT_NAMESPACE,
MOVEMENT_PREFIX,
about,
[
XmpField::new("When", XmpValueType::Date, when),
XmpField::new("Holder", XmpValueType::ProperName, holder),
],
)
}
/// The loan record's schema: its six fields of one value each, then the
/// witnesses as a list in no order, the changes of hands as a list in
/// order, and the conditions of the loan as one text in three languages.
fn loan_schema(&self) -> Result<XmpSchema, hqf_pdf::Error> {
let mut properties: Vec<XmpProperty> = LOAN_FIELDS
.iter()
.zip(self.loan_descriptions)
.map(|((name, value_type, value), description)| {
XmpProperty::new(*name, *value, description).with_value_type(*value_type)
})
.collect();
let [witnesses, movements, conditions] = self.loan_lists;
properties.push(
XmpProperty::new("Witnesses", XmpValue::bag(WITNESSES), witnesses)
.with_value_type(XmpType::bag(XmpValueType::ProperName)),
);
let changes = XmpValue::seq(MOVEMENTS.map(|(when, holder)| {
XmpValue::structure([("When", when.into()), ("Holder", holder.into())])
}));
properties.push(
XmpProperty::new("Movements", changes, movements)
.with_value_type(XmpType::seq(self.movement()?)),
);
properties.push(
XmpProperty::new("Conditions", XmpValue::lang_alt(CONDITIONS), conditions)
.with_value_type(XmpType::LangAlt),
);
XmpSchema::new(self.loan_schema, LOAN_NAMESPACE, LOAN_PREFIX, properties)
}
/// The schema the packet declares, built from the fields the page draws.
fn schema(&self) -> Result<XmpSchema, hqf_pdf::Error> {
let properties: Vec<XmpProperty> = FIELDS
.iter()
.zip(self.values)
.zip(self.descriptions)
.map(|((field, value), description)| {
XmpProperty::new(field.name, value, description)
.with_value_type(field.value_type)
.with_category(field.category)
})
.collect();
XmpSchema::new(self.schema, NAMESPACE, PREFIX, properties)
}
}
/// The sheet in English.
const ENGLISH: Words = Words {
title: "Records office cover sheet",
prose: "The fields below are the records office's own. No part of the PDF standard knows what \
a retention date is, so the file explains itself: each field arrives in the metadata \
packet with its name, the way it is to be read, who it is written for, and what it \
means. An archival validator accepts them on that description, and refuses metadata \
that turns up without one.",
headings: [
"What the sheet says",
"What the packet declares of each of them",
],
values: [
"RO-2026-004318",
"Planning",
"2056-12-31T23:59:59+01:00",
"Public",
"1",
],
descriptions: [
"The reference the records office files the dossier under",
"The department the dossier came from",
"The date the dossier may be destroyed, and not before",
"How widely the dossier may be circulated",
"How many sheets the dossier holds",
],
note: "Every value above is written twice: once on this page, and once in the packet a machine \
reads, under the prefix the schema names. Reading the file's metadata gives back this \
table, field for field.",
schema: "Records Office Schema",
subject: "An archival sheet carrying metadata of its own",
more_title: "What else a packet can carry",
more_prose: "A second schema, the loan record's, carries fields of the six other kinds a property may be read as, and two lists: the witnesses to the loan, in no particular order, and each change of hands, in order, which is a structure the packet describes field by field. The conditions of the loan are one text in three languages, each version marked with its language. The document states its keywords, when it changed and whether it was trapped, and this page carries a packet of its own.",
loan_schema: "Loan Record Schema",
loan_descriptions: [
"Whether the dossier left the office sealed",
"The media type the dossier is lent in",
"Who holds the dossier while it is out",
"How much shelf the dossier takes, in metres",
"The series the dossier belongs to",
"Where the office's catalogue is read",
],
loan_lists: [
"Who witnessed the loan",
"Each time the dossier changed hands, in order",
"The conditions of the loan, in each language they were agreed in",
],
movement: [
"One change of hands of a dossier",
"The day the dossier changed hands",
"Who took the dossier",
],
declared: "Declared in the namespace {namespace}, under the prefix {prefix}:",
keywords: "archive, planning, retention",
states: "The document's keywords: {keywords}; it changed on {modified}; trapped: \
{trapped}.",
trapped: ["yes", "no", "not known"],
dates: "That date as PDF writes it: {pdf}; read back: {iso}.",
packets: "This page carries a packet of {page} bytes of its own; the same facts claiming \
PDF/A-3b, PDF/UA-1 and PDF/X-4 would weigh {claimed} bytes.",
};
/// The sheet in French.
const FRENCH: Words = Words {
title: "Bordereau du service d’archives",
prose: "Les champs ci-dessous sont propres au service d’archives. Aucune partie de la \
norme PDF ne sait ce qu’est une date de conservation : le fichier s’explique \
donc lui-même. Chaque champ arrive dans le paquet de métadonnées avec son nom, \
la façon de le lire, le public auquel il s’adresse et son sens. Un validateur \
d’archivage les accepte sur cette description, et refuse toute métadonnée qui \
en est dépourvue.",
headings: [
"Ce que dit le bordereau",
"Ce que le paquet déclare pour chacun",
],
values: [
"RO-2026-004318",
"Urbanisme",
"2056-12-31T23:59:59+01:00",
"Public",
"1",
],
descriptions: [
"La référence sous laquelle le service d’archives classe le dossier",
"Le service d’où vient le dossier",
"La date à partir de laquelle le dossier peut être détruit",
"Le périmètre de diffusion du dossier",
"Le nombre de feuilles du dossier",
],
note: "Chaque valeur ci-dessus est écrite deux fois : une fois sur cette page, une \
fois dans le paquet que lit une machine, sous le préfixe que nomme le schéma. \
Lire les métadonnées du fichier restitue ce tableau, champ pour champ.",
schema: "Schéma du service d’archives",
subject: "Un bordereau d’archives doté de ses propres métadonnées",
more_title: "Ce qu’un paquet peut encore contenir",
more_prose: "Un second schéma, celui de la fiche de prêt, contient des champs de chacun des six autres types de valeur qu’une propriété peut prendre, ainsi que deux listes : les témoins du prêt, sans ordre particulier, et les passages du dossier d’une main à l’autre, dans l’ordre. Chaque passage est une structure que le paquet décrit champ par champ. Les conditions du prêt forment un seul texte en trois langues, dont chaque version indique sa langue. Le document indique ses mots-clés, sa date de modification et s’il a fait l’objet d’un recouvrement, et cette page contient son propre paquet.",
loan_schema: "Schéma de la fiche de prêt",
loan_descriptions: [
"Si le dossier a quitté le service sous scellés",
"Le type de média sous lequel le dossier est prêté",
"Qui détient le dossier pendant le prêt",
"La longueur de rayonnage du dossier, en mètres",
"La série à laquelle appartient le dossier",
"L’adresse où se consulte le catalogue du service",
],
loan_lists: [
"Qui a été témoin du prêt",
"Chaque passage du dossier d’une main à l’autre, dans l’ordre",
"Les conditions du prêt, une version par langue",
],
movement: [
"Un passage du dossier d’une main à l’autre",
"Le jour où le dossier a changé de mains",
"Qui a reçu le dossier",
],
declared: "Déclaré dans l’espace de noms {namespace}, sous le préfixe {prefix} :",
keywords: "archives, urbanisme, conservation",
states: "Mots-clés du document : {keywords} ; modifié le {modified} ; recouvrement : \
{trapped}.",
trapped: ["oui", "non", "inconnu"],
dates: "Cette date telle que l’écrit le PDF : {pdf} ; relue : {iso}.",
packets: "Cette page contient son propre paquet de {page} octets ; les mêmes \
informations, déclarant la conformité à PDF/A-3b, PDF/UA-1 et PDF/X-4, pèseraient \
{claimed} octets.",
};
/// The sheet in Dutch.
const DUTCH: Words = Words {
title: "Voorblad van het dossierarchief",
prose: "De velden hieronder zijn die van het dossierarchief zelf. Geen deel van de PDF-norm weet wat een bewaardatum is, dus legt het bestand zichzelf uit: elk veld komt in het metadatapakket met zijn naam, de manier waarop het gelezen moet worden, voor wie het geschreven is en wat het betekent. Een archiefvalidator aanvaardt ze op die beschrijving, en weigert metadata die zonder beschrijving opduikt.",
headings: [
"Wat het blad zegt",
"Wat het pakket van elk ervan verklaart",
],
values: [
"RO-2026-004318",
"Ruimtelijke ordening",
"2056-12-31T23:59:59+01:00",
"Openbaar",
"1",
],
descriptions: [
"Het kenmerk waaronder het archief het dossier opbergt",
"De afdeling waar het dossier vandaan kwam",
"De datum waarop het dossier vernietigd mag worden, en niet eerder",
"Hoe ruim het dossier verspreid mag worden",
"Hoeveel bladen het dossier bevat",
],
note: "Elke waarde hierboven is twee keer geschreven: één keer op deze pagina en één keer in het pakket dat een machine leest, onder het voorvoegsel dat het schema noemt. De metadata van het bestand lezen geeft deze tabel terug, veld voor veld.",
schema: "Schema van het dossierarchief",
subject: "Een archiefblad met eigen metadata",
more_title: "Wat een pakket nog meer kan bevatten",
more_prose: "Een tweede schema, dat van het uitleenregister, bevat velden van de zes andere soorten waarin een eigenschap gelezen kan worden, en twee lijsten: de getuigen van de uitlening, in willekeurige volgorde, en elke keer dat het dossier van hand wisselde, op volgorde, als een structuur die het pakket veld voor veld beschrijft. De voorwaarden van de uitlening zijn één tekst in drie talen, elke versie gemerkt met haar taal. Het document noemt zijn trefwoorden, wanneer het veranderde en of het getrapt is, en deze pagina heeft een eigen pakket.",
loan_schema: "Schema van het uitleenregister",
loan_descriptions: [
"Of het dossier verzegeld het archief verliet",
"Het mediatype waarin het dossier wordt uitgeleend",
"Wie het dossier heeft terwijl het weg is",
"Hoeveel plankruimte het dossier inneemt, in meters",
"De reeks waartoe het dossier behoort",
"Waar de catalogus van het archief te lezen is",
],
loan_lists: [
"Wie de uitlening als getuige bijwoonde",
"Elke keer dat het dossier van hand wisselde, op volgorde",
"De voorwaarden van de uitlening, in elke taal waarin ze zijn afgesproken",
],
movement: [
"Eén keer dat een dossier van hand wisselde",
"De dag waarop het dossier van hand wisselde",
"Wie het dossier overnam",
],
declared: "Gedeclareerd in de naamruimte {namespace}, onder het voorvoegsel {prefix}:",
keywords: "archief, ruimtelijke ordening, bewaring",
states: "De trefwoorden van het document: {keywords}; het veranderde op {modified}; getrapt: {trapped}.",
trapped: ["ja", "nee", "onbekend"],
dates: "Die datum zoals PDF hem schrijft: {pdf}; teruggelezen: {iso}.",
packets: "Deze pagina heeft een eigen pakket van {page} bytes; dezelfde gegevens met een claim op PDF/A-3b, PDF/UA-1 en PDF/X-4 zouden {claimed} bytes wegen.",
};
/// The sheet in Portuguese.
const PORTUGUESE: Words = Words {
title: "Folha de rosto do arquivo de processos",
prose: "Os campos abaixo são próprios do arquivo de processos. Nenhuma parte da norma PDF sabe o que é uma data de conservação, por isso o ficheiro explica-se a si mesmo: cada campo chega ao pacote de metadados com o seu nome, a forma de o ler, para quem é escrito e o que significa. Um validador de arquivo aceita-os com essa descrição, e recusa os metadados que chegam sem ela.",
headings: ["O que a folha diz", "O que o pacote declara de cada um"],
values: [
"RO-2026-004318",
"Urbanismo",
"2056-12-31T23:59:59+01:00",
"Público",
"1",
],
descriptions: [
"A referência com que o arquivo regista o processo",
"O serviço de onde vem o processo",
"A data a partir da qual o processo pode ser destruído, e não antes",
"Com que amplitude o processo pode circular",
"Quantas folhas tem o processo",
],
note: "Cada valor acima é escrito duas vezes: uma nesta página e outra no pacote que uma máquina lê, com o prefixo que o esquema nomeia. Ler os metadados do ficheiro devolve esta tabela, campo a campo.",
schema: "Esquema do arquivo de processos",
subject: "Uma folha de arquivo com metadados próprios",
more_title: "Que mais um pacote pode levar",
more_prose: "Um segundo esquema, o do registo de empréstimos, leva campos dos outros seis tipos em que uma propriedade pode ser lida, e duas listas: as testemunhas do empréstimo, sem ordem definida, e cada mudança de mãos do processo, por ordem, sob a forma de uma estrutura que o pacote descreve campo a campo. As condições do empréstimo são um único texto em três línguas, cada versão marcada com a sua língua. O documento indica as suas palavras-chave, quando mudou e se foi submetido a trapping, e esta página leva um pacote próprio.",
loan_schema: "Esquema do registo de empréstimos",
loan_descriptions: [
"Se o processo saiu do arquivo selado",
"O tipo de suporte em que o processo é emprestado",
"Quem tem o processo enquanto está fora",
"Quanta prateleira ocupa o processo, em metros",
"A série a que o processo pertence",
"Onde se consulta o catálogo do arquivo",
],
loan_lists: [
"Quem testemunhou o empréstimo",
"Cada vez que o processo mudou de mãos, por ordem",
"As condições do empréstimo, em cada língua em que foram acordadas",
],
movement: [
"Uma mudança de mãos de um processo",
"O dia em que o processo mudou de mãos",
"Quem recebeu o processo",
],
declared: "Declarado no espaço de nomes {namespace}, com o prefixo {prefix}:",
keywords: "arquivo, urbanismo, conservação",
states: "As palavras-chave do documento: {keywords}; mudou em {modified}; trapping: {trapped}.",
trapped: ["sim", "não", "desconhecido"],
dates: "Essa data como o PDF a escreve: {pdf}; relida: {iso}.",
packets: "Esta página leva um pacote próprio de {page} bytes; os mesmos dados a declarar PDF/A-3b, PDF/UA-1 e PDF/X-4 pesariam {claimed} bytes.",
};
/// The sheet in Italian.
const ITALIAN: Words = Words {
title: "Frontespizio dell’archivio atti",
prose: "I campi qui sotto sono propri dell’archivio atti. Nessuna parte della norma PDF sa cos’è una data di conservazione, così il file si spiega da sé: ogni campo arriva nel pacchetto di metadati con il suo nome, il modo di leggerlo, per chi è scritto e cosa significa. Un validatore d’archivio li accetta su quella descrizione, e rifiuta i metadati che arrivano senza.",
headings: [
"Cosa dice il foglio",
"Cosa dichiara il pacchetto di ciascuno",
],
values: [
"RO-2026-004318",
"Urbanistica",
"2056-12-31T23:59:59+01:00",
"Pubblico",
"1",
],
descriptions: [
"Il riferimento con cui l’archivio registra la pratica",
"Il servizio da cui proviene la pratica",
"La data da cui la pratica può essere distrutta, e non prima",
"Quanto largamente può circolare la pratica",
"Quanti fogli contiene la pratica",
],
note: "Ogni valore qui sopra è scritto due volte: una su questa pagina e una nel pacchetto che legge una macchina, con il prefisso che nomina lo schema. Leggere i metadati del file restituisce questa tabella, campo per campo.",
schema: "Schema dell’archivio atti",
subject: "Un foglio d’archivio che porta metadati propri",
more_title: "Cos’altro può portare un pacchetto",
more_prose: "Un secondo schema, quello del registro dei prestiti, porta campi degli altri sei tipi in cui si può leggere una proprietà, e due elenchi: i testimoni del prestito, in ordine sparso, e ogni passaggio di mano della pratica, in ordine, sotto forma di una struttura che il pacchetto descrive campo per campo. Le condizioni del prestito sono un unico testo in tre lingue, ogni versione contrassegnata dalla sua lingua. Il documento indica le sue parole chiave, quando è cambiato e se è stato sottoposto a trapping, e questa pagina porta un pacchetto proprio.",
loan_schema: "Schema del registro dei prestiti",
loan_descriptions: [
"Se la pratica è uscita dall’archivio sigillata",
"Il tipo di supporto in cui la pratica è prestata",
"Chi tiene la pratica mentre è fuori",
"Quanto scaffale occupa la pratica, in metri",
"La serie a cui appartiene la pratica",
"Dove si consulta il catalogo dell’archivio",
],
loan_lists: [
"Chi ha assistito al prestito come testimone",
"Ogni passaggio di mano della pratica, in ordine",
"Le condizioni del prestito, in ogni lingua in cui sono state concordate",
],
movement: [
"Un passaggio di mano di una pratica",
"Il giorno in cui la pratica è passata di mano",
"Chi ha ricevuto la pratica",
],
declared: "Dichiarato nello spazio dei nomi {namespace}, con il prefisso {prefix}:",
keywords: "archivio, urbanistica, conservazione",
states: "Le parole chiave del documento: {keywords}; è cambiato il {modified}; trapping: {trapped}.",
trapped: ["sì", "no", "sconosciuto"],
dates: "Quella data come la scrive PDF: {pdf}; riletta: {iso}.",
packets: "Questa pagina porta un pacchetto proprio di {page} byte; gli stessi dati che dichiarano PDF/A-3b, PDF/UA-1 e PDF/X-4 peserebbero {claimed} byte.",
};
/// The sheet in Spanish.
const SPANISH: Words = Words {
title: "Portada del archivo de expedientes",
prose: "Los campos de abajo son propios del archivo de expedientes. Ninguna parte de la norma PDF sabe qué es una fecha de conservación, así que el archivo se explica solo: cada campo llega al paquete de metadatos con su nombre, la forma de leerlo, para quién se escribe y qué significa. Un validador de archivo los acepta con esa descripción, y rechaza los metadatos que llegan sin ella.",
headings: [
"Lo que dice la hoja",
"Lo que el paquete declara de cada uno",
],
values: [
"RO-2026-004318",
"Urbanismo",
"2056-12-31T23:59:59+01:00",
"Público",
"1",
],
descriptions: [
"La referencia con que el archivo registra el expediente",
"El servicio del que procede el expediente",
"La fecha a partir de la cual el expediente puede destruirse, y no antes",
"Con qué amplitud puede circular el expediente",
"Cuántas hojas tiene el expediente",
],
note: "Cada valor de arriba se escribe dos veces: una en esta página y otra en el paquete que lee una máquina, con el prefijo que nombra el esquema. Leer los metadatos del archivo devuelve esta tabla, campo por campo.",
schema: "Esquema del archivo de expedientes",
subject: "Una hoja de archivo con metadatos propios",
more_title: "Qué más puede llevar un paquete",
more_prose: "Un segundo esquema, el del registro de préstamos, lleva campos de los otros seis tipos en que puede leerse una propiedad, y dos listas: los testigos del préstamo, sin un orden concreto, y cada cambio de manos del expediente, por orden, en forma de una estructura que el paquete describe campo por campo. Las condiciones del préstamo son un único texto en tres idiomas, cada versión marcada con su idioma. El documento indica sus palabras clave, cuándo cambió y si se le aplicó reventado, y esta página lleva un paquete propio.",
loan_schema: "Esquema del registro de préstamos",
loan_descriptions: [
"Si el expediente salió del archivo precintado",
"El tipo de soporte en que se presta el expediente",
"Quién tiene el expediente mientras está fuera",
"Cuánto estante ocupa el expediente, en metros",
"La serie a la que pertenece el expediente",
"Dónde se consulta el catálogo del archivo",
],
loan_lists: [
"Quiénes presenciaron el préstamo como testigos",
"Cada vez que el expediente cambió de manos, por orden",
"Las condiciones del préstamo, en cada idioma en que se acordaron",
],
movement: [
"Un cambio de manos de un expediente",
"El día en que el expediente cambió de manos",
"Quién recibió el expediente",
],
declared: "Declarado en el espacio de nombres {namespace}, con el prefijo {prefix}:",
keywords: "archivo, urbanismo, conservación",
states: "Las palabras clave del documento: {keywords}; cambió el {modified}; reventado: {trapped}.",
trapped: ["sí", "no", "desconocido"],
dates: "Esa fecha tal como la escribe PDF: {pdf}; leída de nuevo: {iso}.",
packets: "Esta página lleva un paquete propio de {page} bytes; los mismos datos declarando PDF/A-3b, PDF/UA-1 y PDF/X-4 pesarían {claimed} bytes.",
};
/// The sheet in German.
const GERMAN: Words = Words {
title: "Deckblatt des Archivamts",
prose: "Die Felder unten sind die eigenen des Archivamts. Kein Teil der PDF-Norm weiß, was ein Aufbewahrungsdatum ist, also erklärt sich die Datei selbst: Jedes Feld kommt im Metadatenpaket mit seinem Namen, der Art, wie es zu lesen ist, für wen es geschrieben ist und was es bedeutet. Ein Archivvalidator nimmt sie nach dieser Beschreibung an und lehnt Metadaten ab, die ohne eine solche auftauchen.",
headings: ["Was das Blatt sagt", "Was das Paket zu jedem davon erklärt"],
values: [
"RO-2026-004318",
"Planung",
"2056-12-31T23:59:59+01:00",
"Öffentlich",
"1",
],
descriptions: [
"Das Zeichen, unter dem das Archivamt die Akte ablegt",
"Die Abteilung, aus der die Akte stammt",
"Der Tag, an dem die Akte vernichtet werden darf, und nicht früher",
"Wie weit die Akte verbreitet werden darf",
"Wie viele Blätter die Akte enthält",
],
note: "Jeder Wert oben steht zweimal da: einmal auf dieser Seite und einmal in dem Paket, das eine Maschine liest, unter dem Präfix, das das Schema nennt. Wer die Metadaten der Datei liest, erhält diese Tabelle zurück, Feld für Feld.",
schema: "Schema des Archivamts",
subject: "Ein Archivblatt mit eigenen Metadaten",
more_title: "Was ein Paket sonst noch tragen kann",
more_prose: "Ein zweites Schema, das des Ausleihvermerks, trägt Felder der sechs anderen Arten, als die eine Eigenschaft gelesen werden kann, dazu zwei Listen: die Zeugen der Ausleihe, ohne bestimmte Reihenfolge, und jede Übergabe der Akte, der Reihe nach, als Struktur, die das Paket Feld für Feld beschreibt. Die Bedingungen der Ausleihe sind ein einziger Text in drei Sprachen, jede Fassung mit ihrer Sprache gekennzeichnet. Das Dokument nennt seine Schlüsselwörter, wann es geändert wurde und ob es überfüllt wurde, und diese Seite trägt ein eigenes Paket.",
loan_schema: "Schema des Ausleihvermerks",
loan_descriptions: [
"Ob die Akte das Amt versiegelt verlassen hat",
"Der Medientyp, in dem die Akte verliehen wird",
"Wer die Akte hat, solange sie außer Haus ist",
"Wie viele Regalmeter die Akte einnimmt",
"Die Reihe, zu der die Akte gehört",
"Wo der Katalog des Amts gelesen wird",
],
loan_lists: [
"Wer die Ausleihe bezeugt hat",
"Jede Übergabe der Akte, der Reihe nach",
"Die Bedingungen der Ausleihe, in jeder Sprache, in der sie vereinbart wurden",
],
movement: [
"Eine Übergabe einer Akte",
"Der Tag, an dem die Akte übergeben wurde",
"Wer die Akte übernommen hat",
],
declared: "Im Namensraum {namespace} erklärt, unter dem Präfix {prefix}:",
keywords: "Archiv, Planung, Aufbewahrung",
states: "Die Schlüsselwörter des Dokuments: {keywords}; geändert am {modified}; überfüllt: {trapped}.",
trapped: ["ja", "nein", "unbekannt"],
dates: "Dieses Datum, wie PDF es schreibt: {pdf}; zurückgelesen: {iso}.",
packets: "Diese Seite trägt ein eigenes Paket von {page} Bytes; dieselben Angaben mit dem Anspruch PDF/A-3b, PDF/UA-1 und PDF/X-4 wögen {claimed} Bytes.",
};
/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
(Language::English, &ENGLISH),
(Language::French, &FRENCH),
(Language::German, &GERMAN),
(Language::Spanish, &SPANISH),
(Language::Italian, &ITALIAN),
(Language::Portuguese, &PORTUGUESE),
(Language::Dutch, &DUTCH),
];
/// The left edge the sheet is set from.
const X: f64 = 72.0;
/// The room the sheet has across the page.
const WIDTH: f64 = 451.0;
/// How far into that room the values stand, leaving the names to their left.
const VALUES: f64 = 150.0;
/// Where the first block starts, down from the top of the page.
const TOP: f64 = 780.0;
/// Draws `text` in `flow` at `top`, and hands back the top of whatever follows
/// it.
fn block(
content: &mut Content,
flow: &TextFlow<'_>,
text: &str,
top: f64,
) -> Result<f64, hqf_pdf::Error> {
let lines = flow.break_lines(text, WIDTH);
content.begin_text();
flow.draw(content, &lines, X, top, WIDTH)?;
content.end_text();
Ok(top - flow.height(&lines))
}
/// Draws the sheet — what it is, what it says about itself, and how a reader
/// may check — and hands back the top of whatever would follow it.
fn draw(content: &mut Content, font: &FontHandle, words: &Words) -> Result<f64, hqf_pdf::Error> {
let title = TextFlow::new(font, 20.0).space_after(14.0);
let prose = TextFlow::new(font, 10.5)
.leading(15.0)
.align(Align::Justify)
.space_after(16.0);
let heading = TextFlow::new(font, 12.0)
.space_before(20.0)
.space_after(8.0);
let row = TextFlow::new(font, 11.0)
.leading(17.0)
.tab_method(TabMethod::Ruler)
.tab_ruler([VALUES]);
let declared = TextFlow::new(font, 9.5)
.leading(14.0)
.hanging_list(0.0, VALUES);
let note = TextFlow::new(font, 9.0).leading(13.0).space_before(18.0);
let mut top = block(content, &title, words.title, TOP)?;
top = block(content, &prose, words.prose, top)?;
top = block(content, &heading, words.headings[0], top)?;
let values: String = FIELDS
.iter()
.zip(words.values)
.map(|(field, value)| format!("{}\t{value}", field.name))
.collect::<Vec<_>>()
.join("\n");
top = block(content, &row, &values, top)?;
top = block(content, &heading, words.headings[1], top)?;
let rows: String = FIELDS
.iter()
.zip(words.descriptions)
.map(|(field, description)| {
format!(
"{PREFIX}:{}\t{} · {} · {description}",
field.name,
field.value_type.as_str(),
field.category.as_str(),
)
})
.collect::<Vec<_>>()
.join("\n");
top = block(content, &declared, &rows, top)?;
block(content, ¬e, words.note, top)
}
/// What `value` says, as the page prints it: text as it stands, the items of a
/// list parted by semicolons, each text in several languages after its language
/// and a colon, the fields of a structure by commas.
fn shown(value: &XmpValue) -> String {
match value {
XmpValue::Text(text) => text.clone(),
XmpValue::Seq(items) | XmpValue::Bag(items) | XmpValue::Alt(items) => {
items.iter().map(shown).collect::<Vec<_>>().join("; ")
}
XmpValue::LangAlt(texts) => texts
.iter()
.map(|(language, text)| format!("{language}: {text}"))
.collect::<Vec<_>>()
.join("; "),
XmpValue::Structure(fields) => fields
.iter()
.map(|(_, field)| shown(field))
.collect::<Vec<_>>()
.join(", "),
_ => String::new(),
}
}
/// Where `trapped` stands in [`Words::trapped`].
#[allow(
clippy::match_same_arms,
reason = "a state the library adds later reads as not known"
)]
const fn trapped_place(trapped: Trapped) -> usize {
match trapped {
Trapped::Yes => 0,
Trapped::No => 1,
Trapped::Unknown => 2,
_ => 2,
}
}
/// The second page: the loan record's schema read back field by field, with the
/// structure a change of hands is written as, what the document states of
/// itself, its date of change both ways, and what the packets weigh. `facts` is
/// what the document states.
fn second_sheet(
font: &FontHandle,
words: &Words,
facts: &Metadata,
) -> Result<Page, Box<dyn std::error::Error>> {
let title = TextFlow::new(font, 20.0).space_after(14.0);
let prose = TextFlow::new(font, 10.5)
.leading(15.0)
.align(Align::Justify)
.space_after(16.0);
let declared = TextFlow::new(font, 9.5)
.leading(14.0)
.hanging_list(0.0, VALUES);
let line = TextFlow::new(font, 10.0).leading(14.0).space_before(10.0);
let mut content = Content::new();
let mut top = block(&mut content, &title, words.more_title, TOP)?;
top = block(&mut content, &prose, words.more_prose, top)?;
let schema = words.loan_schema()?;
let heading = words
.declared
.replace("{namespace}", schema.namespace())
.replace("{prefix}", schema.prefix());
top = block(&mut content, &line, &heading, top)?;
let movement = words.movement()?;
let rows: String = schema
.properties()
.iter()
.map(|property| {
format!(
"{}:{}\t{} · {} · {}",
schema.prefix(),
property.name(),
shown(property.value()),
property.value_type(),
property.description(),
)
})
.chain([format!("{}\t{}", movement.name(), movement.description())])
.chain(movement.fields().iter().map(|field| {
format!(
"{MOVEMENT_PREFIX}:{}\t{} · {}",
field.name(),
field.value_type(),
field.description(),
)
}))
.collect::<Vec<_>>()
.join("\n");
top = block(&mut content, &declared, &rows, top)?;
let changed_on = facts.modified.as_deref().unwrap_or_default();
let states = words
.states
.replace("{keywords}", facts.keywords.as_deref().unwrap_or_default())
.replace("{modified}", changed_on)
.replace(
"{trapped}",
words.trapped[facts.trapped.map_or(2, trapped_place)],
);
top = block(&mut content, &line, &states, top)?;
let written = date::to_pdf(changed_on)?;
let read_back = date::from_pdf(&written).unwrap_or_default();
let dates = words
.dates
.replace("{pdf}", &written)
.replace("{iso}", &read_back);
top = block(&mut content, &line, &dates, top)?;
let mut own = Metadata::default();
own.title = Some(words.more_title.to_owned());
let page_packet = xmp::packet(Claims::new(), &own)?;
let claiming = xmp::packet(
Claims::new()
.archival(PdfA::A3B)
.accessibility(PdfUa::One)
.print(PdfX::X4),
&own,
)?;
let packets = words
.packets
.replace("{page}", &page_packet.len().to_string())
.replace("{claimed}", &claiming.len().to_string());
block(&mut content, &line, &packets, top)?;
let mut sheet = Page::a4();
sheet.content = content.into_bytes();
sheet.metadata = Some(Xmp::packet(page_packet));
Ok(sheet)
}
/// The sheet, as a page.
fn cover_sheet(font: &FontHandle, words: &Words) -> Result<Page, hqf_pdf::Error> {
let mut content = Content::new();
draw(&mut content, font, words)?;
let mut page = Page::a4();
page.content = content.into_bytes();
Ok(page)
}
fn main() -> std::process::ExitCode {
failure::reported(run())
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args = env::args().skip(1);
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let path = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("own_schema")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(licence::licensed());
doc.set_conformance(PdfA::A3B);
let mut facts = Metadata::default();
facts.title = Some(words.document_title());
facts.author = Some("Olivier Pons".to_owned());
facts.subject = Some(words.subject.to_owned());
facts.producer = Some("hqf-pdf".to_owned());
facts.created = Some(ISSUED.to_owned());
facts.modified = Some(CHANGED.to_owned());
facts.keywords = Some(words.keywords.to_owned());
facts.schemas = vec![words.schema()?, words.loan_schema()?];
let stated = facts.clone();
doc.set_metadata(facts);
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
doc.add_page(cover_sheet(&font, words)?)?;
doc.add_page(second_sheet(&font, words, &stated)?)?;
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&path).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &bytes)?;
println!("wrote {path}: {} bytes", bytes.len());
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::content::Content;
use hqf_pdf::{Document, Font};
use super::{FIELDS, WORDS, default_font, draw, language};
/// The lines two languages are allowed to write the same way.
///
/// Three of the five values are not words at all — a reference the office
/// files under, the date the dossier may be destroyed, and how many sheets
/// it holds — and `Public` is the same word in both languages. The names
/// the properties are written under are not in `Words`: a machine looks
/// them up by those, so they cannot follow the page.
const SPARED: [&str; 8] = [
"\"RO-2026-004318\"",
"\"2056-12-31T23:59:59+01:00\"",
"\"Public\"",
"\"1\"",
// Written the same way in Spanish.
r#""no""#,
// Written the same way in Portuguese.
r#""Público""#,
r#""Urbanismo""#,
// Written the same way in Dutch.
r#""ja""#,
];
/// How far down the page the last block may reach. A language whose
/// descriptions run to more lines than English's pushes the note down, and
/// nothing on this page is broken over a second sheet.
const FLOOR: f64 = 40.0;
#[test]
fn every_language_draws_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:?}"
);
}
/// The sheet is one page and nothing on it flows onto a second, so a set of
/// words long enough to fill the paper drops the note off the bottom of it
/// without a single line saying so.
#[test]
fn every_language_lays_the_sheet_out_on_one_page() {
let mut doc = Document::new();
let text = 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 code = named.code();
let mut content = Content::new();
let foot = draw(&mut content, &text, words).expect("the sheet lays out");
assert!(
foot >= FLOOR,
"the {code} sheet ends {foot:.1} points up the page, and the \
paper is done at {FLOOR:.1}"
);
}
}
/// Every field the packet declares says what it is for, and every field the
/// page draws has a value under it: a set of words short of either leaves a
/// property the standard's own rules refuse.
#[test]
fn every_language_says_what_each_field_holds_and_means() {
for (named, words) in WORDS {
let code = named.code();
assert_eq!(words.values.len(), FIELDS.len(), "{code} values");
assert!(
words.descriptions.iter().all(|line| !line.is_empty()),
"the {code} sheet declares a field without saying what it means"
);
}
}
}
|