Skip to main content

pdf2_render/
font.rs

1//! Fonts for text rendering: a provider trait, a built-in base-14 fallback and
2//! TrueType outlines through `ttf-parser`.
3
4use pdf2::Encoding;
5
6use crate::geom::Point;
7
8/// One glyph's outline in em units: y grows upwards, the baseline is y = 0 and
9/// one em is 1.0.
10#[derive(Debug, Clone, Default, PartialEq)]
11pub struct Glyph {
12    /// Closed contours of the outline.
13    pub contours: Vec<Vec<Point>>,
14    /// Advance width in em units.
15    pub advance: f64,
16}
17
18/// A resolved font ready to place glyphs.
19#[derive(Debug, Clone)]
20pub enum Font {
21    /// The built-in fallback: a 5×7 bitmap alphabet, used when the document
22    /// carries no usable font program (all of the base-14 cases).
23    Builtin {
24        /// Code → character table.
25        encoding: Encoding,
26    },
27    /// An embedded TrueType program.
28    TrueType {
29        /// Code → character table.
30        encoding: Encoding,
31        /// The font program, still compressed in the PDF sense is not our
32        /// business: this is the decoded `/FontFile2`.
33        data: Vec<u8>,
34    },
35}
36
37impl Font {
38    /// The built-in fallback with an encoding.
39    pub fn builtin(encoding: Encoding) -> Self {
40        Self::Builtin { encoding }
41    }
42
43    /// An embedded TrueType program, rejected when it cannot be parsed.
44    pub fn true_type(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
45        let face = ttf_parser::Face::parse(&data, 0).ok()?;
46        if face.units_per_em() == 0 {
47            return None;
48        }
49        Some(Self::TrueType { encoding, data })
50    }
51
52    /// The outline and advance for a byte code, or `None` when there is no
53    /// glyph for it.
54    pub fn glyph(&self, code: u8) -> Option<Glyph> {
55        match self {
56            Self::Builtin { encoding } => builtin_glyph(encoding.character(code)?),
57            Self::TrueType { encoding, data } => {
58                let character = encoding.character(code)?;
59                let face = ttf_parser::Face::parse(data, 0).ok()?;
60                let glyph_id = face.glyph_index(character)?;
61                let units = f64::from(face.units_per_em());
62                let mut builder = OutlineBuilder::new(units);
63                face.outline_glyph(glyph_id, &mut builder)?;
64                let advance = f64::from(face.glyph_hor_advance(glyph_id).unwrap_or(0)) / units;
65                Some(Glyph {
66                    contours: builder.contours,
67                    advance,
68                })
69            }
70        }
71    }
72
73    /// The advance of a code in em units, falling back to the built-in metric.
74    pub fn advance(&self, code: u8) -> f64 {
75        self.glyph(code)
76            .map_or(BUILTIN_ADVANCE, |glyph| glyph.advance)
77    }
78}
79
80const BUILTIN_ADVANCE: f64 = 6.0 / 9.0;
81const BUILTIN_CELL: f64 = 1.0 / 9.0;
82const BUILTIN_WIDTH: u8 = 5;
83const BUILTIN_HEIGHT: u8 = 7;
84
85/// A 5×7 bitmap alphabet. Lowercase letters use the uppercase shapes; anything
86/// without a pattern is drawn as a notdef box.
87fn builtin_glyph(character: char) -> Option<Glyph> {
88    let code = u8::try_from(u32::from(character)).ok()?;
89    let rows = if character == ' ' {
90        [0_u8; BUILTIN_HEIGHT as usize]
91    } else if let Some(rows) = glyph_rows(code) {
92        rows
93    } else if character == '\u{2022}' {
94        [0, 0, 0b00100, 0b01110, 0b00100, 0, 0]
95    } else if let Some(upper) = upper(character) {
96        glyph_rows(upper as u8).unwrap_or(notdef_rows())
97    } else {
98        notdef_rows()
99    };
100    Some(Glyph {
101        contours: rows_to_contours(&rows),
102        advance: BUILTIN_ADVANCE,
103    })
104}
105
106fn upper(character: char) -> Option<char> {
107    character
108        .to_uppercase()
109        .next()
110        .filter(|upper| *upper != character)
111}
112
113fn notdef_rows() -> [u8; BUILTIN_HEIGHT as usize] {
114    [
115        0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111,
116    ]
117}
118
119fn rows_to_contours(rows: &[u8; BUILTIN_HEIGHT as usize]) -> Vec<Vec<Point>> {
120    let mut contours = Vec::new();
121    for (row, bits) in rows.iter().enumerate() {
122        for column in 0..BUILTIN_WIDTH {
123            let mask = 1_u8 << (BUILTIN_WIDTH - 1 - column);
124            if bits & mask == 0 {
125                continue;
126            }
127            let x0 = f64::from(column) * BUILTIN_CELL;
128            let x1 = x0 + BUILTIN_CELL;
129            let top = f64::from(BUILTIN_HEIGHT - 1 - row as u8) * BUILTIN_CELL;
130            let bottom = top + BUILTIN_CELL;
131            contours.push(vec![
132                Point::new(x0, bottom),
133                Point::new(x1, bottom),
134                Point::new(x1, top),
135                Point::new(x0, top),
136            ]);
137        }
138    }
139    contours
140}
141
142fn glyph_rows(code: u8) -> Option<[u8; 7]> {
143    let rows = match code {
144        b'A' => [
145            0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
146        ],
147        b'B' => [
148            0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
149        ],
150        b'C' => [
151            0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
152        ],
153        b'D' => [
154            0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
155        ],
156        b'E' => [
157            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
158        ],
159        b'F' => [
160            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
161        ],
162        b'G' => [
163            0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
164        ],
165        b'H' => [
166            0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
167        ],
168        b'I' => [
169            0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
170        ],
171        b'J' => [
172            0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100,
173        ],
174        b'K' => [
175            0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
176        ],
177        b'L' => [
178            0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
179        ],
180        b'M' => [
181            0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
182        ],
183        b'N' => [
184            0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
185        ],
186        b'O' => [
187            0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
188        ],
189        b'P' => [
190            0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
191        ],
192        b'Q' => [
193            0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101,
194        ],
195        b'R' => [
196            0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
197        ],
198        b'S' => [
199            0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
200        ],
201        b'T' => [
202            0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
203        ],
204        b'U' => [
205            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
206        ],
207        b'V' => [
208            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
209        ],
210        b'W' => [
211            0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
212        ],
213        b'X' => [
214            0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
215        ],
216        b'Y' => [
217            0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
218        ],
219        b'Z' => [
220            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
221        ],
222        b'0' => [
223            0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
224        ],
225        b'1' => [
226            0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
227        ],
228        b'2' => [
229            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
230        ],
231        b'3' => [
232            0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
233        ],
234        b'4' => [
235            0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
236        ],
237        b'5' => [
238            0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
239        ],
240        b'6' => [
241            0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
242        ],
243        b'7' => [
244            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
245        ],
246        b'8' => [
247            0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
248        ],
249        b'9' => [
250            0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
251        ],
252        b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
253        b',' => [0, 0, 0, 0, 0b01100, 0b01100, 0b01000],
254        b'!' => [
255            0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
256        ],
257        b'?' => [
258            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100,
259        ],
260        b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
261        b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
262        b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0b01000],
263        b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
264        b'"' => [0b01010, 0b01010, 0, 0, 0, 0, 0],
265        b'(' => [
266            0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
267        ],
268        b')' => [
269            0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
270        ],
271        b'/' => [
272            0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000,
273        ],
274        b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
275        b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
276        b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
277        b'#' => [
278            0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010,
279        ],
280        b'%' => [
281            0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
282        ],
283        b'&' => [
284            0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101,
285        ],
286        _ => return None,
287    };
288    Some(rows)
289}
290
291/// Collects `ttf-parser` outlines into em-space contours.
292struct OutlineBuilder {
293    units: f64,
294    contours: Vec<Vec<Point>>,
295    current: Vec<Point>,
296}
297
298impl OutlineBuilder {
299    fn new(units: f64) -> Self {
300        Self {
301            units,
302            contours: Vec::new(),
303            current: Vec::new(),
304        }
305    }
306
307    fn point(&self, x: f32, y: f32) -> Point {
308        Point::new(f64::from(x) / self.units, f64::from(y) / self.units)
309    }
310
311    fn finish_contour(&mut self) {
312        if self.current.len() > 1 {
313            self.contours.push(std::mem::take(&mut self.current));
314        }
315    }
316}
317
318impl ttf_parser::OutlineBuilder for OutlineBuilder {
319    fn move_to(&mut self, x: f32, y: f32) {
320        self.finish_contour();
321        self.current.push(self.point(x, y));
322    }
323
324    fn line_to(&mut self, x: f32, y: f32) {
325        self.current.push(self.point(x, y));
326    }
327
328    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
329        let Some(&start) = self.current.last() else {
330            return;
331        };
332        let control = self.point(x1, y1);
333        let end = self.point(x, y);
334        for step in 1..=8 {
335            let t = f64::from(step) / 8.0;
336            let u = 1.0 - t;
337            self.current.push(Point::new(
338                u * u * start.x + 2.0 * u * t * control.x + t * t * end.x,
339                u * u * start.y + 2.0 * u * t * control.y + t * t * end.y,
340            ));
341        }
342    }
343
344    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
345        let Some(&start) = self.current.last() else {
346            return;
347        };
348        let c1 = self.point(x1, y1);
349        let c2 = self.point(x2, y2);
350        let end = self.point(x, y);
351        for step in 1..=12 {
352            let t = f64::from(step) / 12.0;
353            let u = 1.0 - t;
354            self.current.push(Point::new(
355                u * u * u * start.x
356                    + 3.0 * u * u * t * c1.x
357                    + 3.0 * u * t * t * c2.x
358                    + t * t * t * end.x,
359                u * u * u * start.y
360                    + 3.0 * u * u * t * c1.y
361                    + 3.0 * u * t * t * c2.y
362                    + t * t * t * end.y,
363            ));
364        }
365    }
366
367    fn close(&mut self) {
368        self.finish_contour();
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::Font;
375    use pdf2::Encoding;
376
377    #[test]
378    fn the_builtin_font_draws_letters_as_ink() {
379        let font = Font::builtin(Encoding::standard());
380        let glyph = font.glyph(b'H').expect("H");
381        assert!(!glyph.contours.is_empty());
382        assert!((glyph.advance - 0.6667).abs() < 1e-3);
383        // Every contour is a rectangle inside the glyph box.
384        for contour in &glyph.contours {
385            assert_eq!(contour.len(), 4);
386            for point in contour {
387                assert!(point.x >= 0.0 && point.x <= 6.0 / 9.0 + 1e-9);
388                assert!(point.y >= 0.0 && point.y <= 7.0 / 9.0 + 1e-9);
389            }
390        }
391    }
392
393    #[test]
394    fn the_builtin_font_is_blank_for_space() {
395        let font = Font::builtin(Encoding::standard());
396        let glyph = font.glyph(b' ').expect("space");
397        assert!(glyph.contours.is_empty());
398        assert!(glyph.advance > 0.0);
399    }
400
401    #[test]
402    fn a_broken_font_program_is_rejected() {
403        assert!(Font::true_type(Encoding::standard(), vec![0, 1, 2, 3]).is_none());
404        assert!(Font::true_type(Encoding::standard(), Vec::new()).is_none());
405    }
406
407    #[test]
408    fn unknown_characters_become_the_notdef_box() {
409        let font = Font::builtin(Encoding::standard());
410        // 0xA4 is undefined in StandardEncoding, so there is no glyph at all.
411        assert!(font.glyph(0xA4).is_none());
412        // A mapped but unpatterned character gets the notdef box, not a panic.
413        let glyph = font.glyph(b'@').expect("@");
414        assert_eq!(
415            glyph.contours.len(),
416            20,
417            "the notdef box is a hollow 5×7 frame"
418        );
419    }
420}