An archivable PDF/A-3 form

A form that is also a PDF/A-3 file: every field already drawn, with a visible frame, expecting nothing from the reader's software.

Rust write_archival_form.rs 295 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! 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 the reader's 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 reader help 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.
//!
//! 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, Font, FontHandle, FormField, License, Page, RadioGroup, Rgb,
};

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

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

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

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// 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 a reader 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 : la norme n'en dessine 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'archive",
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 2] =
    [(Language::English, &ENGLISH), (Language::French, &FRENCH)];

/// 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.name(), 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(
        FormField::new("Name", 180.0, 697.0, 240.0, SIZE + 4.0, font.name(), SIZE)
            .value(REGISTERED_NAME)
            .border(BORDER, BORDER_WIDTH)
            .into(),
    );

    draw(&mut content, font, 72.0, 664.0, words.email)?;
    page.fields.push(
        FormField::new("Email", 180.0, 661.0, 240.0, SIZE + 4.0, font.name(), SIZE)
            .border(BORDER, BORDER_WIDTH)
            .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(BORDER, BORDER_WIDTH)
            .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(BORDER, BORDER_WIDTH)
            .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(BORDER, BORDER_WIDTH)
            .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() -> 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);
    doc.set_metadata(Metadata {
        title: Some(words.document_title.to_owned()),
        author: Some(AUTHOR.to_owned()),
        subject: Some(words.document_subject.to_owned()),
        producer: Some("hqf-pdf".to_owned()),
        created: Some(ISSUED.to_owned()),
        ..Metadata::default()
    });

    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. There are
    /// none: every word on this page and in its metadata differs.
    const SPARED: [&str; 0] = [];

    #[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:?}"
        );
    }
}