Code 128 and retail barcodes

A page of barcodes, drawn as bars: Code 128 and the retail family, EAN-13, UPC-A, EAN-8.

Rust write_barcode.rs 322 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
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
//! Writes a page of barcodes, drawn as bars: Code 128 for arbitrary text, an
//! EAN-13 for a thirteen-digit article number, a UPC-A for its twelve-digit
//! North American cousin, and a short EAN-8.
//!
//! Whether a barcode 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
//! barcode says under it, and `scripts/check_barcode.sh` points a decoder at
//! the rendered image and compares.
//!
//! The head of the sheet says what the 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 barcodes carry stands apart from them: a
//! scanner reads it, not a person, and it is the same in every language.
//!
//! Usage: `cargo run --example write_barcode -- tmp/barcode.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_barcode --
//! tmp/barcode_fr.pdf`

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

use hqf_pdf::barcode::QUIET_ZONE;
use hqf_pdf::content::Content;
use hqf_pdf::cos::Name;
use hqf_pdf::{Code128, Document, Ean8, Ean13, Error, Font, FontHandle, License, Page, UpcA};

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

/// What the Code 128 barcodes carry: an invoice number, a payment reference,
/// and a line holding every kind of character code set B carries.
const CARRIED: &[&str] = &["FR-1964413", "REF 2026-07-16/ACME", "a-Z 0..9 +*#%"];

/// The thirteen-digit article number the EAN-13 barcode carries.
const ARTICLE: &str = "9780201379624";

/// The twelve-digit article number the UPC-A barcode carries.
const UPC_ARTICLE: &str = "036000291452";

/// The eight-digit article number the EAN-8 barcode carries.
const EAN8_ARTICLE: &str = "96385074";

/// The width of the narrowest bar, in points. Everything else is a whole number
/// of these.
const MODULE: f64 = 1.0;

/// How tall the bars are drawn, in points.
const BAR_HEIGHT: f64 = 40.0;

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

/// How far in from the left edge of the sheet the head of the page is set. The
/// quiet zone of the first barcode starts here too, so the heading stands over
/// the left edge of the block of bars.
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],
}

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: "Barcodes, drawn as bars",
    lines: [
        "Each barcode below is drawn as bars, not pasted in as a picture, so it prints",
        "exactly as wide as it should. Under each one is what a scanner reads back.",
    ],
};

/// The head of the sheet in French.
const FRENCH: Words = Words {
    title: "Des codes-barres, dessinés en barres",
    lines: [
        "Chaque code-barres ci-dessous est dessiné en barres, pas collé comme une image :",
        "il s'imprime à la largeur exacte. Sous chacun est écrit ce qu'un scanner y lit.",
    ],
};

/// 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 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.name(), 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.name(), BODY)?;
        content.text_origin(MARGIN, y)?;
        content.show_glyphs(&font.glyphs(line));
        content.end_text();
        y -= LINE_STEP;
    }
    Ok(())
}

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("barcode")));
    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 mut top = TOP;
    for carried in CARRIED {
        let code = Code128::new(carried)?;

        // The quiet zone is the caller's: the bars start ten modules in, and
        // nothing else is drawn beside them.
        let left = f64::from(u32::try_from(QUIET_ZONE)?).mul_add(MODULE, MARGIN);
        let width = f64::from(u32::try_from(code.module_count())?) * MODULE;
        content.draw_barcode(&code, left, top, width, BAR_HEIGHT)?;

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

        top -= 120.0;
    }

    let left = f64::from(u32::try_from(QUIET_ZONE)?).mul_add(MODULE, MARGIN);

    let ean = Ean13::new(ARTICLE)?;
    let width = f64::from(u32::try_from(ean.module_count())?) * MODULE;
    content.draw_ean13(&ean, left, top, width, BAR_HEIGHT)?;
    content.begin_text();
    content.set_font(font.name(), 9.0)?;
    content.text_origin(left, top - 12.0)?;
    content.show_glyphs(&font.glyphs(ARTICLE));
    content.end_text();
    top -= 120.0;

    let upc = UpcA::new(UPC_ARTICLE)?;
    let width = f64::from(u32::try_from(upc.module_count())?) * MODULE;
    content.draw_upc_a(&upc, left, top, width, BAR_HEIGHT)?;
    content.begin_text();
    content.set_font(font.name(), 9.0)?;
    content.text_origin(left, top - 12.0)?;
    content.show_glyphs(&font.glyphs(UPC_ARTICLE));
    content.end_text();
    top -= 120.0;

    let ean8 = Ean8::new(EAN8_ARTICLE)?;
    let width = f64::from(u32::try_from(ean8.module_count())?) * MODULE;
    content.draw_ean8(&ean8, left, top, width, BAR_HEIGHT)?;
    content.begin_text();
    content.set_font(font.name(), 9.0)?;
    content.text_origin(left, top - 12.0)?;
    content.show_glyphs(&font.glyphs(EAN8_ARTICLE));
    content.end_text();

    let mut page = Page::a4();
    page.content = content.into_bytes();
    doc.add_page(page)?;

    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::{Document, Font};

    use super::{
        BAR_HEIGHT, BODY, HEAD_GAP, HEAD_TOP, HEADING, LINE_STEP, MARGIN, 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 barcodes 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 bars, and the bars start where
    /// the first barcode is drawn. A line too many at the head would be drawn
    /// over them.
    #[test]
    fn the_head_of_the_sheet_stands_clear_of_the_bars() {
        let bars = TOP + BAR_HEIGHT;

        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 >= bars,
                "the {} head ends on a line at {last:.1} points, and the bars \
                 reach {bars:.1}",
                named.code()
            );
        }
    }
}