write_pdf417.rs

Die Rust-Datei des Beispiels „PDF417-Codes“. Der Code auf Ausweisdokumenten und Versandpapieren: Er trägt weit mehr Text als eine Strichreihe und übersteht einen darübergezogenen Laserscanner.

Rust 495 Zeilen

Wofür dieses Beispiel da ist

PDF417 ist der Code auf Ausweisdokumenten, Fahrkarten und Versandpapieren. Er trägt weit mehr Text, als eine Strichreihe kann, und er übersteht einen darübergezogenen Laserscanner statt einer still gehaltenen Kamera — genau das haben ein Schalterangestellter und eine Laderampe tatsächlich in der Hand.

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
//! Writes a page of PDF417 codes, drawn as stacked bars.
//!
//! Whether a PDF417 code works is not a question the page can answer, and not
//! one a human eye can: it is answered by a scanner. So the page carries what
//! each code says under it, and `scripts/check_pdf417.sh` points a decoder at
//! the rendered image and compares.
//!
//! The head of the sheet says what the stacked bars are for, so that the page
//! is worth something to whoever opens it without the code beside it. Those
//! words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which
//! set the sheet is headed in. What the codes carry stands apart from them: a
//! scanner reads it, not a person, and it is the same in every language.
//!
//! A second page sets the same kind of code at five of the nine levels of
//! correction, one of them handed over as UTF-8 bytes that name their character
//! set, and four built other ways, in one column. Each says under its payload
//! the level it was built at and the correction codewords that level adds.
//!
//! Usage: `cargo run --example write_pdf417 -- tmp/pdf417.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_pdf417 --
//! tmp/pdf417_fr.pdf`

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

use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::eci::Charset;
use hqf_pdf::pdf417::{ErrorLevel, QUIET_ZONE, ROW_ASPECT};
use hqf_pdf::{Document, Error, Font, FontHandle, License, Page, Pdf417};

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

/// What the codes carry: a tracking link, a serial number, and a line of mixed
/// punctuation.
const CARRIED: &[&str] = &[
    "https://example.test/track/FR-1964413",
    "SN:2026-07-19/ACME-4472",
    "a-Z 0..9 +*#% and on",
];

/// How many data columns each code is drawn in, which is what settles how wide
/// the symbol comes out: the rows follow from the text.
const COLUMNS: usize = 4;

/// The width of one module on the second page, in points: six pixels to a
/// module at 288dpi, as on the first.
const SMALL_MODULE: f64 = 1.5;

/// What the codes of the second page carry: levels 0 and 5, four built other
/// ways, and level 8.
const LEVELLED: [&str; 7] = [
    "LEVEL 0",
    "Zürich ✓",
    "COLUMNS 3",
    "PLAIN BYTES",
    "LEVEL BYTES",
    "COLUMN BYTES",
    "SHAPE 8",
];

/// The width of one module, in points. Six pixels to a module at 288dpi, so
/// every module's edge lands on a pixel boundary.
const MODULE: f64 = 1.5;

/// Where the foot of the first code sits, in points up from the foot of the
/// sheet.
const TOP: f64 = 660.0;

/// How far in from the left edge of the sheet the head of the page is set. The
/// quiet zone of each code starts here too, so the heading stands over the left
/// edge of the block of codes.
const MARGIN: f64 = 72.0;

/// Where the baseline of the heading sits, in points up from the foot of the
/// sheet.
const HEAD_TOP: f64 = 794.0;

/// The size the heading is set at, in points.
const HEADING: f64 = 16.0;

/// The size the lines under the heading are set at, in points.
const BODY: f64 = 10.5;

/// How far under the heading the first line beneath it sits, in points.
const HEAD_GAP: f64 = 24.0;

/// How far below one line under the heading the next one sits, in points.
const LINE_STEP: f64 = 15.0;

/// The words the sheet is headed in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the page says it is, at its head and in what the file says of
    /// itself.
    title: &'static str,
    /// What the page says under its heading.
    lines: [&'static str; 2],
    /// The second page's heading.
    more_title: &'static str,
    /// The line under a code of the second page that says its level of
    /// correction; `{level}` and `{codewords}` stand for what is read back.
    level: &'static str,
}

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

/// The head of the sheet in English.
const ENGLISH: Words = Words {
    title: "PDF417 codes, drawn as stacked bars",
    lines: [
        "A PDF417 code is rows of bars stacked one over another, and it holds a whole",
        "form rather than a number. Under each one is what a scanner reads back.",
    ],
    more_title: "Levels of correction, and codes built other ways",
    level: "level {level}: {codewords} correction codewords",
};

/// The head of the sheet in French.
const FRENCH: Words = Words {
    title: "Des codes PDF417, dessinés en barres empilées",
    lines: [
        "Un code PDF417 est fait de rangées de barres empilées, et il contient un formulaire",
        "entier plutôt qu’un numéro. Sous chacun figure ce qu’un scanner y lit.",
    ],
    more_title: "Niveaux de correction, et codes construits autrement",
    level: "niveau {level}\u{a0}: {codewords}\u{a0}mots de correction",
};

/// The head of the sheet in Dutch.
const DUTCH: Words = Words {
    title: "PDF417-codes, getekend als gestapelde streepjes",
    lines: [
        "Een PDF417-code is een stapel rijen streepjes boven elkaar, en hij bevat een heel",
        "formulier in plaats van een getal. Onder elke code wat een scanner leest.",
    ],
    more_title: "Correctieniveaus, en codes op andere manieren opgebouwd",
    level: "niveau {level}: {codewords} correctiecodewoorden",
};

/// The head of the sheet in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Códigos PDF417, desenhados como barras empilhadas",
    lines: [
        "Um código PDF417 é feito de filas de barras empilhadas e guarda",
        "um formulário inteiro e não um número. Por baixo de cada um, o que um leitor lê.",
    ],
    more_title: "Níveis de correção, e códigos construídos de outras formas",
    level: "nível {level}: {codewords} palavras de correção",
};

/// The head of the sheet in Italian.
const ITALIAN: Words = Words {
    title: "Codici PDF417, disegnati come barre sovrapposte",
    lines: [
        "Un codice PDF417 è fatto di file di barre sovrapposte, e contiene un intero",
        "modulo anziché un numero. Sotto ciascuno, ciò che legge uno scanner.",
    ],
    more_title: "Livelli di correzione, e codici costruiti in altri modi",
    level: "livello {level}: {codewords} parole di correzione",
};

/// The head of the sheet in Spanish.
const SPANISH: Words = Words {
    title: "Códigos PDF417, dibujados como barras apiladas",
    lines: [
        "Un código PDF417 son filas de barras apiladas unas sobre otras, y guarda un",
        "formulario entero y no un número. Debajo de cada uno, lo que lee un escáner.",
    ],
    more_title: "Niveles de corrección, y códigos construidos de otras formas",
    level: "nivel {level}: {codewords} palabras de corrección",
};

/// The head of the sheet in German.
const GERMAN: Words = Words {
    title: "PDF417-Codes, als gestapelte Balken gezeichnet",
    lines: [
        "Ein PDF417-Code besteht aus übereinandergestapelten Balkenreihen und fasst",
        "ein ganzes Formular statt einer Zahl. Darunter steht, was ein Scanner liest.",
    ],
    more_title: "Korrekturstufen und anders gebaute Codes",
    level: "Stufe {level}: {codewords} Korrekturcodewörter",
};

/// 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 heading, and the lines under it that say what the page is for.
fn head(content: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    content.begin_text();
    content.set_font(font, HEADING)?;
    content.text_origin(MARGIN, HEAD_TOP)?;
    content.show_glyphs(&font.glyphs(words.title));
    content.end_text();

    let mut y = HEAD_TOP - HEAD_GAP;
    for line in words.lines {
        content.begin_text();
        content.set_font(font, BODY)?;
        content.text_origin(MARGIN, y)?;
        content.show_glyphs(&font.glyphs(line));
        content.end_text();
        y -= LINE_STEP;
    }
    Ok(())
}

/// The codes of the second page: one at level 0, one handed over as UTF-8 bytes
/// that name their character set, four built other ways, and one at level 8.
/// Each comes with the level it was built at.
fn levelled() -> Result<Vec<(Pdf417, ErrorLevel)>, Error> {
    Ok(vec![
        (
            Pdf417::with_level(LEVELLED[0], ErrorLevel::Zero)?,
            ErrorLevel::Zero,
        ),
        (
            Pdf417::from_bytes_in(LEVELLED[1].as_bytes(), Charset::UTF_8, ErrorLevel::Five)?,
            ErrorLevel::Five,
        ),
        (Pdf417::with_columns(LEVELLED[2], 3)?, ErrorLevel::default()),
        (
            Pdf417::from_bytes(LEVELLED[3].as_bytes())?,
            ErrorLevel::default(),
        ),
        (
            Pdf417::from_bytes_with_level(LEVELLED[4].as_bytes(), ErrorLevel::Three)?,
            ErrorLevel::Three,
        ),
        (
            Pdf417::from_bytes_with_columns(LEVELLED[5].as_bytes(), 5)?,
            ErrorLevel::default(),
        ),
        (
            Pdf417::from_bytes_with_shape(LEVELLED[6].as_bytes(), 12, ErrorLevel::Eight)?,
            ErrorLevel::Eight,
        ),
    ])
}

/// The number a level of correction goes by, from the codewords it adds: two
/// raised to one more than the level.
const fn level_number(level: ErrorLevel) -> u32 {
    level.codewords().trailing_zeros() - 1
}

/// The second page: the codes of [`levelled`] one above the other, each with
/// its payload and its level under it, under the page's heading.
///
/// One column: a decoder reads codes set side by side less surely than codes
/// set one above the other.
fn levelled_page(font: &FontHandle, words: &Words) -> Result<Page, Box<dyn std::error::Error>> {
    let mut content = Content::new();
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    content.begin_text();
    content.set_font(font, HEADING)?;
    content.text_origin(MARGIN, HEAD_TOP)?;
    content.show_glyphs(&font.glyphs(words.more_title));
    content.end_text();

    let quiet = f64::from(u32::try_from(QUIET_ZONE)?) * SMALL_MODULE;
    let aspect = f64::from(u32::try_from(ROW_ASPECT)?);
    let mut top = HEAD_TOP - 40.0;
    for ((code, correction), carried) in levelled()?.iter().zip(LEVELLED) {
        let width = f64::from(u32::try_from(code.width())?) * SMALL_MODULE;
        let height = f64::from(u32::try_from(code.height())?) * SMALL_MODULE * aspect;
        let bottom = top - height;
        let left = MARGIN;
        content.draw_pdf417(code, left + quiet, bottom, width, height)?;
        let said = words
            .level
            .replace("{level}", &level_number(*correction).to_string())
            .replace("{codewords}", &correction.codewords().to_string());
        for (line, drop) in [(carried, 10.0), (said.as_str(), 19.0)] {
            content.begin_text();
            content.set_font(font, 7.0)?;
            content.text_origin(left + quiet, bottom - drop)?;
            content.show_glyphs(&font.glyphs(line));
            content.end_text();
        }
        top = bottom - quiet.mul_add(2.0, 30.0);
    }

    let mut page = Page::a4();
    page.content = content.into_bytes();
    Ok(page)
}

/// How many of `code`'s modules are dark, out of how many, as the terminal says
/// it.
fn dark_modules(code: &Pdf417) -> String {
    let dark = (0..code.height())
        .map(|row| {
            (0..code.width())
                .filter(|column| code.is_dark(row, *column))
                .count()
        })
        .sum::<usize>();
    format!(
        "{} rows of {} modules, {dark} of them dark",
        code.height(),
        code.width()
    )
}

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("pdf417")));
    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_info(Name::new("Title"), words.title);

    let font: FontHandle = doc.add_font(Font::parse(fs::read(&font_path)?)?);

    let mut content = Content::new();
    content.set_fill_rgb(0.0, 0.0, 0.0)?;
    head(&mut content, &font, words)?;

    let quiet = f64::from(u32::try_from(QUIET_ZONE)?) * MODULE;
    let aspect = f64::from(u32::try_from(ROW_ASPECT)?);
    let left = MARGIN;
    let mut top = TOP;
    for carried in CARRIED {
        let code = Pdf417::with_shape(carried, COLUMNS, ErrorLevel::default())?;
        let width = f64::from(u32::try_from(code.width())?) * MODULE;
        // A module is drawn taller than it is wide, so a row is that much
        // deeper than a module is across.
        let height = f64::from(u32::try_from(code.height())?) * MODULE * aspect;

        // The quiet zone is the caller's: the code is drawn that far in, and
        // nothing else is drawn beside it.
        content.draw_pdf417(&code, left + quiet, top, width, height)?;
        println!("{}", dark_modules(&code));

        content.begin_text();
        content.set_font(&font, 8.0)?;
        content.text_origin(left + quiet, top - 12.0)?;
        content.show_glyphs(&font.glyphs(carried));
        content.end_text();

        top -= height + quiet.mul_add(2.0, 36.0);
    }

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;
    doc.add_page(levelled_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 {} ({} bytes)", path, bytes.len());
    Ok(())
}

#[cfg(test)]
mod tests {
    use hqf_pdf::pdf417::{ErrorLevel, ROW_ASPECT};
    use hqf_pdf::{Document, Font, Pdf417};

    use super::{
        BODY, CARRIED, COLUMNS, HEAD_GAP, HEAD_TOP, HEADING, LINE_STEP, MARGIN, MODULE, TOP, WORDS,
        default_font, language,
    };

    /// The width of the sheet, in points: A4, which the page is.
    const SHEET_WIDTH: f64 = 595.276;

    /// The lines two languages are allowed to write the same way. The heading
    /// and the lines under it are the whole of `Words`, and no two languages
    /// write one alike; what the codes carry is read by a scanner rather than
    /// by a person, so it stands apart from them.
    const SPARED: [&str; 0] = [];

    /// The room a line set from the left margin has before it reaches the
    /// margin on the other side of the sheet.
    const PAPER: f64 = SHEET_WIDTH - 2.0 * MARGIN;

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

    /// Nothing at the head of the sheet is broken to a width: a line longer
    /// than the paper runs off the edge of it.
    #[test]
    fn every_language_writes_lines_that_fit_the_room_they_have() {
        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 lines =
                std::iter::once((HEADING, words.title)).chain(words.lines.map(|line| (BODY, line)));

            for (size, line) in lines {
                let measured = text.measure(line, size);
                assert!(
                    measured <= PAPER,
                    "the {code} sheet draws {line:?} over {measured:.1} points, \
                     and it has {PAPER:.1}"
                );
            }
        }
    }

    /// The head of the sheet is set above the codes, and the first of them is
    /// the one that reaches highest. A line too many at the head would be drawn
    /// over it.
    #[test]
    fn the_head_of_the_sheet_stands_clear_of_the_codes() {
        let first = Pdf417::with_shape(CARRIED[0], COLUMNS, ErrorLevel::default())
            .expect("what the first code carries is a code a PDF417 symbol holds");
        let rows = f64::from(u32::try_from(first.height()).expect("a symbol is a few dozen rows"));
        let aspect = f64::from(u32::try_from(ROW_ASPECT).expect("a row is a few modules deep"));
        let codes = (rows * MODULE).mul_add(aspect, TOP);

        for (named, words) in WORDS {
            let count = u32::try_from(words.lines.len()).expect("a head has few lines");
            let last = LINE_STEP.mul_add(-f64::from(count - 1), HEAD_TOP - HEAD_GAP);
            assert!(
                last - BODY >= codes,
                "the {} head ends on a line at {last:.1} points, and the codes \
                 reach {codes:.1}",
                named.code()
            );
        }
    }
}