Fonts kept inside the file

Text set in a font the file carries inside it, cut down to the letters actually used.

Rust write_text.rs 201 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
//! Sets text in an embedded font, and writes the result to disk.
//!
//! `pdftotext` must be able to pull the words back out of the result: if it
//! cannot, the `ToUnicode` map is wrong and the text is unsearchable and
//! uncopyable even though the page looks right.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set is drawn. The number, the issuer and the three amounts are the
//! same in every language.
//!
//! Usage: `cargo run --example write_text -- tmp/text.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_text -- tmp/texte.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::{Document, Font, Page};

#[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 the caller names none: the one
/// committed for the tests, so that the example runs on any machine.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The invoice's number.
const NUMBER: &str = "1964413";

/// Who issued it.
const ISSUER: &str = "HQF Development, Cabriès";

/// What each of the three billed lines comes to, in the order they are set.
const AMOUNTS: [&str; 3] = ["4 250.00 EUR", "850.00 EUR", "5 100.00 EUR"];

/// How many characters a billed line runs to: its label, a space, the leader
/// dots, a space, then its amount. The dots take whatever is left, so the
/// amounts end on the same character however long the label before them is.
const LINE_CHARS: usize = 57;

/// The words the page is written in, one set per language.
///
/// What is not language stays out of it: the invoice's number, who issued it
/// and the three amounts read the same wherever the page is read.
#[derive(Debug)]
struct Words {
    /// The document's title, which a reader shows over the page.
    title: &'static str,
    /// What stands before the invoice's number.
    number_label: &'static str,
    /// The line that gives the day it was issued and the term it falls due in.
    dates: &'static str,
    /// What each billed line is called, in the order `AMOUNTS` prices them.
    items: [&'static str; AMOUNTS.len()],
}

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

    /// The lines the sample page sets, and which `pdftotext` must find again.
    ///
    /// They are not all spelled out of the ASCII range for the look of it: an
    /// accent and a dash are two glyphs a wrong `ToUnicode` map loses first,
    /// and a page that only ever said "Total" would never catch it.
    fn lines(&self) -> Vec<String> {
        let mut lines = vec![
            format!("{} {NUMBER} — {ISSUER}", self.number_label),
            self.dates.to_owned(),
        ];
        lines.extend(self.items.iter().zip(AMOUNTS).map(|(item, amount)| {
            let dots = LINE_CHARS.saturating_sub(item.chars().count() + amount.chars().count() + 2);
            format!("{item} {} {amount}", ".".repeat(dots))
        }));
        lines
    }
}

/// The page in English.
const ENGLISH: Words = Words {
    title: "hqf-pdf text sample",
    number_label: "Invoice No.",
    dates: "Issued 14 July 2026 — due within 30 days",
    items: ["Rendering engine development", "VAT at 20 %", "Total due"],
};

/// The page in French.
const FRENCH: Words = Words {
    title: "hqf-pdf, échantillon de texte",
    number_label: "Facture n°",
    dates: "Émise le 14 juillet 2026 — payable sous 30 jours",
    items: [
        "Développement du moteur de rendu",
        "TVA 20 %",
        "Total à payer",
    ],
};

/// 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)];

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);
    let lines = words.lines();

    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 out = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("text")));

    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let font = Font::parse(fs::read(&font_path)?)?;
    println!(
        "font: {} ({} glyphs, {} units per em, {:?} outlines)",
        font.postscript_name(),
        font.glyph_count(),
        font.units_per_em(),
        font.outlines()
    );

    let mut doc = Document::new();
    doc.set_license(licence::licensed()); // no notice, so the text stands alone
    doc.set_info(Name::new("Title"), words.title);
    let handle = doc.add_font(font);

    let mut c = Content::new();
    c.begin_text();
    c.set_font(handle.name(), 14.0)?;
    c.text_position(60.0, 760.0)?;
    for line in &lines {
        c.show_glyphs(&handle.glyphs(line));
        // Move down one line. Td is relative to the start of the previous line.
        c.text_position(0.0, -28.0)?;
    }
    c.end_text();

    // A rule under the total, positioned from the measured width of the text,
    // to prove the metrics agree with what was drawn.
    let last = lines.last().map_or("", String::as_str);
    let width = handle.measure(last, 14.0);
    c.set_line_width(0.8)?;
    let baseline = 28.0_f64.mul_add(-5.0, 760.0);
    c.rect(60.0, baseline, width, 0.0)?;
    c.stroke();

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

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&out).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&out, &bytes)?;

    println!("wrote {out}: {} bytes", bytes.len());
    println!("the last line measures {width:.1} pt at 14 pt");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{WORDS, language};

    /// The lines two languages are allowed to write the same way. There are
    /// none: the number, the issuer and the amounts are held outside the words.
    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 page says these in more than one language: {untranslated:?}"
        );
    }
}