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 | //! Writes an archival form: a PDF/A-3 file a reader fills in.
//!
//! A form and an archival file pull in opposite directions. A form leaves its
//! fields for reading software to draw; an archival file forbids exactly that,
//! and demands every mark be baked into the page. This reconciles them: each
//! field carries its own appearance — a text value drawn as glyphs, a tick or
//! dot drawn as a vector — so the file needs no help from reading software and
//! no font it does not embed.
//!
//! A form field draws no border of its own: the PDF standard leaves widgets
//! borderless by default, so a reader sees only what the page draws behind
//! them. This example gives every field a border, so the boxes a reader clicks
//! are plain to see, and says as much on the page. The borders are optional —
//! the same form is valid without them.
//!
//! Whether the result is really PDF/A-3 is not for us to say. `veraPDF` says,
//! and `scripts/check_pdfa.sh` asks it.
//!
//! Every field also carries a tooltip, which is its accessible name: the
//! sentence reading software shows when the pointer rests on the box, and what
//! a screen reader speaks in place of the field's own name. The label drawn
//! beside the box serves as both, so what a sighted reader sees and what a
//! screen reader says are the same words.
//!
//! The labels, the options and the metadata are held in `Words`, once per
//! language, and `HQF_PDF_LANG` picks which set is drawn. A field's name is not
//! among them: it is what a filled form's data comes back under, so it stays
//! the same whichever language the page is drawn in.
//!
//! Usage: `cargo run --example write_archival_form -- tmp/archival_form.pdf
//! [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_archival_form --
//! tmp/formulaire_archive.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::metadata::xmp::{Metadata, PdfA};
use hqf_pdf::{
CheckBox, ChoiceField, Document, FieldBorder, Font, FontHandle, License, Page, RadioGroup, Rgb,
TextField,
};
#[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 form was drawn up. The library never reads the clock — a document
/// that stamped itself with the time would be a different file on every build —
/// so the caller says when.
const ISSUED: &str = "2026-07-14T09:30:00+02:00";
/// Who drew the form up, and the value the name field starts with. Neither is
/// language.
const AUTHOR: &str = "Olivier Pons";
const REGISTERED_NAME: &str = "Ada Lovelace";
/// The names the two radio buttons send back, in the order they are drawn.
const PAYMENT_VALUES: [&str; 2] = ["card", "transfer"];
/// The words the page is written in, one set per language.
///
/// A field's name is not here: it is the name a filled form's data comes back
/// under, and reading software that changed language would send back something
/// else. The metadata is, because a reader reads it beside the page.
#[derive(Debug)]
struct Words {
/// The line at the head of the page.
title: &'static str,
/// What the two lines under the title say the boxes are.
boxes_are_fields: &'static str,
/// What the second of them says about their borders.
borders_are_optional: &'static str,
/// The label beside the field a reader gives a name in.
name: &'static str,
/// The label beside the field a reader gives an address in.
email: &'static str,
/// The line beside the check box.
subscribe: &'static str,
/// The label beside the drop-down.
plan: &'static str,
/// The options the drop-down offers; the second is the one it starts on.
plans: [&'static str; 2],
/// The label beside the radio buttons.
payment: &'static str,
/// The line beside each radio button, in the order they are drawn.
payments: [&'static str; 2],
/// The title the document carries in its metadata.
document_title: &'static str,
/// What its metadata says the document is.
document_subject: &'static str,
}
impl Words {
/// The words the page is written in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "Registration",
boxes_are_fields: "The boxes below are clickable form fields.",
borders_are_optional: "Their borders are optional: the standard draws none by default.",
name: "Name",
email: "Email",
subscribe: "Subscribe to the newsletter",
plan: "Plan",
plans: ["Monthly", "Yearly"],
payment: "Payment",
payments: ["Card", "Transfer"],
document_title: "A registration form",
document_subject: "A fillable form that is also an archival file",
};
/// The page in French.
const FRENCH: Words = Words {
title: "Inscription",
boxes_are_fields: "Les cases ci-dessous sont des champs à remplir.",
borders_are_optional: "Leur bordure est facultative : par défaut, la norme n’en prévoit aucune.",
name: "Nom",
email: "Courriel",
subscribe: "S’abonner à la lettre d’information",
plan: "Formule",
plans: ["Mensuelle", "Annuelle"],
payment: "Paiement",
payments: ["Carte", "Virement"],
document_title: "Un formulaire d’inscription",
document_subject: "Un formulaire à remplir qui est aussi un fichier d’archivage",
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Inschrijving",
boxes_are_fields: "De vakjes hieronder zijn klikbare formuliervelden.",
borders_are_optional: "Hun randen zijn optioneel: de norm tekent er standaard geen.",
name: "Naam",
email: "E-mail",
subscribe: "Abonneren op de nieuwsbrief",
plan: "Abonnement",
plans: ["Maandelijks", "Jaarlijks"],
payment: "Betaling",
payments: ["Kaart", "Overschrijving"],
document_title: "Een inschrijfformulier",
document_subject: "Een invulbaar formulier dat ook een archief-pdf is",
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "Inscrição",
boxes_are_fields: "As caixas abaixo são campos de formulário clicáveis.",
borders_are_optional: "Os seus contornos são opcionais: a norma não desenha nenhum por omissão.",
name: "Nome",
email: "E-mail",
subscribe: "Subscrever a newsletter",
plan: "Plano",
plans: ["Mensal", "Anual"],
payment: "Pagamento",
payments: ["Cartão", "Transferência"],
document_title: "Um formulário de inscrição",
document_subject: "Um formulário preenchível que é também um PDF de arquivo",
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Iscrizione",
boxes_are_fields: "Le caselle qui sotto sono campi di modulo cliccabili.",
borders_are_optional: "I loro bordi sono facoltativi: la norma non ne disegna nessuno per impostazione predefinita.",
name: "Nome",
email: "E-mail",
subscribe: "Iscriversi alla newsletter",
plan: "Piano",
plans: ["Mensile", "Annuale"],
payment: "Pagamento",
payments: ["Carta", "Bonifico"],
document_title: "Un modulo di iscrizione",
document_subject: "Un modulo compilabile che è anche un PDF d’archivio",
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Inscripción",
boxes_are_fields: "Las casillas de abajo son campos de formulario en los que se puede hacer clic.",
borders_are_optional: "Sus bordes son opcionales: la norma no prevé ninguno por defecto.",
name: "Nombre",
email: "Correo electrónico",
subscribe: "Suscribirse al boletín",
plan: "Plan",
plans: ["Mensual", "Anual"],
payment: "Pago",
payments: ["Tarjeta", "Transferencia"],
document_title: "Un formulario de inscripción",
document_subject: "Un formulario rellenable que es también un PDF de archivo",
};
/// The page in German.
const GERMAN: Words = Words {
title: "Anmeldung",
boxes_are_fields: "Die Felder unten sind anklickbare Formularfelder.",
borders_are_optional: "Ihre Rahmen sind optional: Nach der Norm wird standardmäßig keiner gezeichnet.",
name: "Name",
email: "E-Mail",
subscribe: "Newsletter abonnieren",
plan: "Tarif",
plans: ["Monatlich", "Jährlich"],
payment: "Zahlung",
payments: ["Karte", "Überweisung"],
document_title: "Ein Anmeldeformular",
document_subject: "Ein ausfüllbares Formular, das zugleich eine Archivdatei ist",
};
/// 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 size the labels and the field text are set at.
const SIZE: f64 = 12.0;
/// The colour every field's border is stroked in.
const BORDER: Rgb = Rgb::gray(0.6);
/// The width every field's border is stroked at, in points.
const BORDER_WIDTH: f64 = 0.75;
/// Draws one line of text, with its baseline at `(x, y)`.
fn draw(
content: &mut Content,
font: &FontHandle,
x: f64,
y: f64,
text: &str,
) -> Result<(), hqf_pdf::Error> {
content.begin_text();
content.set_font(font, SIZE)?;
content.text_origin(x, y)?;
content.show_glyphs(&font.glyphs(text));
content.end_text();
Ok(())
}
/// The form page: a label and a fillable box for each field, one of every kind.
fn form_page(font: &FontHandle, words: &'static Words) -> Result<Page, hqf_pdf::Error> {
let mut content = Content::new();
let mut page = Page::a4();
draw(&mut content, font, 72.0, 760.0, words.title)?;
draw(&mut content, font, 72.0, 738.0, words.boxes_are_fields)?;
draw(&mut content, font, 72.0, 722.0, words.borders_are_optional)?;
// A filled text field and an empty one: the empty field's baked appearance
// is empty, which is what makes the file archival without hiding the field.
draw(&mut content, font, 72.0, 700.0, words.name)?;
page.fields.push(
TextField::new("Name", 180.0, 697.0, 240.0, SIZE + 4.0, font.name(), SIZE)
.value(REGISTERED_NAME)
.border(FieldBorder::solid(BORDER, BORDER_WIDTH))
.tooltip(words.name)
.into(),
);
draw(&mut content, font, 72.0, 664.0, words.email)?;
page.fields.push(
TextField::new("Email", 180.0, 661.0, 240.0, SIZE + 4.0, font.name(), SIZE)
.border(FieldBorder::solid(BORDER, BORDER_WIDTH))
.tooltip(words.email)
.into(),
);
draw(&mut content, font, 90.0, 628.0, words.subscribe)?;
page.fields.push(
CheckBox::new("Subscribe", 72.0, 626.0, SIZE, SIZE)
.checked()
.border(FieldBorder::solid(BORDER, BORDER_WIDTH))
.tooltip(words.subscribe)
.into(),
);
draw(&mut content, font, 72.0, 592.0, words.plan)?;
page.fields.push(
ChoiceField::new("Plan", 180.0, 589.0, 240.0, SIZE + 4.0, font.name(), SIZE)
.option(words.plans[0])
.option(words.plans[1])
.selected(words.plans[1])
.dropdown()
.border(FieldBorder::solid(BORDER, BORDER_WIDTH))
.tooltip(words.plan)
.into(),
);
draw(&mut content, font, 72.0, 556.0, words.payment)?;
page.fields.push(
RadioGroup::new("Payment")
.option(PAYMENT_VALUES[0], 180.0, 553.0, SIZE, SIZE)
.option(PAYMENT_VALUES[1], 320.0, 553.0, SIZE, SIZE)
.selected(PAYMENT_VALUES[0])
.border(FieldBorder::solid(BORDER, BORDER_WIDTH))
.tooltip(words.payment)
.into(),
);
draw(&mut content, font, 198.0, 556.0, words.payments[0])?;
draw(&mut content, font, 338.0, 556.0, words.payments[1])?;
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: Vec<String> = env::args().skip(1).collect();
let evaluation = args.iter().any(|arg| arg == "--evaluation");
args.retain(|arg| !arg.starts_with("--"));
let mut args = args.into_iter();
// 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("archival_form")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(if evaluation {
License::evaluation()
} else {
licence::licensed()
});
doc.set_conformance(PdfA::A3B);
let mut facts = Metadata::default();
facts.title = Some(words.document_title.to_owned());
facts.author = Some(AUTHOR.to_owned());
facts.subject = Some(words.document_subject.to_owned());
facts.producer = Some("hqf-pdf".to_owned());
facts.created = Some(ISSUED.to_owned());
doc.set_metadata(facts);
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
doc.add_page(form_page(&font, words)?)?;
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 super::{WORDS, language};
/// The lines two languages are allowed to write the same way, where two
/// languages spell a word alike. Every word on this page and in its
/// metadata differs.
const SPARED: [&str; 6] = [
// Written the same way in German.
r#"name: "Name""#,
// Written the same way in Spanish.
r#"plan: "Plan""#,
// Written the same way in Portuguese.
r#""Anual""#,
r#"email: "E-mail""#,
r#"name: "Nome""#,
r#"payment: "Pagamento""#,
];
#[test]
fn every_language_draws_the_page_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the form says these in more than one language: {untranslated:?}"
);
}
}
|