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    if character == ' ' {
90        return Some(Glyph {
91            contours: Vec::new(),
92            advance: BUILTIN_ADVANCE,
93        });
94    }
95    if let Some(rows) = glyph_rows(code) {
96        return Some(Glyph {
97            contours: rows_to_contours(&rows),
98            advance: BUILTIN_ADVANCE,
99        });
100    }
101    if character == '\u{2022}' {
102        return Some(Glyph {
103            contours: rows_to_contours(&[0, 0, 0b00100, 0b01110, 0b00100, 0, 0]),
104            advance: BUILTIN_ADVANCE,
105        });
106    }
107    // Latin-1 text is the common case for base-14 fonts, so an accented letter
108    // is drawn as its unaccented base plus the mark rather than as .notdef.
109    if let Some((base, accent)) = decompose(character) {
110        let rows = glyph_rows(u8::try_from(u32::from(base)).unwrap_or(b'?'))
111            .or_else(|| upper(base).and_then(|upper| glyph_rows(upper as u8)))
112            .unwrap_or_else(notdef_rows);
113        let mut contours = rows_to_contours(&rows);
114        contours.extend(
115            accent
116                .cells()
117                .iter()
118                .map(|&(column, layer)| mark_cell(column, layer)),
119        );
120        return Some(Glyph {
121            contours,
122            advance: BUILTIN_ADVANCE,
123        });
124    }
125    if character == '\u{00F8}' || character == '\u{00D8}' {
126        // `ø` is `o` with a slash through it, which no mark above the box can
127        // show, so the slash goes across the glyph body instead.
128        let mut contours = rows_to_contours(&glyph_rows(b'O').unwrap_or_else(notdef_rows));
129        contours.extend(
130            [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]
131                .iter()
132                .map(|&(column, layer)| mark_cell(column, layer)),
133        );
134        return Some(Glyph {
135            contours,
136            advance: BUILTIN_ADVANCE,
137        });
138    }
139    let rows = upper(character)
140        .and_then(|upper| glyph_rows(upper as u8))
141        .unwrap_or_else(notdef_rows);
142    Some(Glyph {
143        contours: rows_to_contours(&rows),
144        advance: BUILTIN_ADVANCE,
145    })
146}
147
148/// A mark that can sit on a 5×7 base letter: above the glyph box (layers 0 and
149/// up) or below the baseline (negative layers, used by the cedilla).
150#[derive(Clone, Copy, PartialEq, Eq, Debug)]
151enum Accent {
152    Acute,
153    Grave,
154    Circumflex,
155    Diaeresis,
156    Tilde,
157    Ring,
158    Cedilla,
159}
160
161impl Accent {
162    /// Cell coordinates: `column` across the five-column box, `layer` up from
163    /// the top of the glyph (layer 0 starts at 7/9 em) or, when negative, down
164    /// from the baseline.
165    fn cells(self) -> &'static [(u8, i8)] {
166        match self {
167            Self::Acute => &[(2, 0), (3, 0), (3, 1)],
168            Self::Grave => &[(2, 1), (3, 1), (3, 0)],
169            Self::Circumflex => &[(1, 0), (2, 1), (3, 0)],
170            Self::Diaeresis => &[(1, 1), (3, 1)],
171            Self::Tilde => &[(1, 1), (2, 0), (3, 1)],
172            Self::Ring => &[(1, 0), (2, 1), (3, 0), (2, 0)],
173            Self::Cedilla => &[(2, -1), (3, -1), (3, -2)],
174        }
175    }
176}
177
178/// One cell of a mark, as a rectangle in em units.
179fn mark_cell(column: u8, layer: i8) -> Vec<Point> {
180    let x0 = f64::from(column) * BUILTIN_CELL;
181    let x1 = x0 + BUILTIN_CELL;
182    let (bottom, top) = if layer < 0 {
183        (
184            f64::from(layer) * BUILTIN_CELL,
185            f64::from(layer + 1) * BUILTIN_CELL,
186        )
187    } else {
188        (
189            f64::from(BUILTIN_HEIGHT + layer as u8) * BUILTIN_CELL,
190            f64::from(BUILTIN_HEIGHT + layer as u8 + 1) * BUILTIN_CELL,
191        )
192    };
193    vec![
194        Point::new(x0, bottom),
195        Point::new(x1, bottom),
196        Point::new(x1, top),
197        Point::new(x0, top),
198    ]
199}
200
201/// The base letter and mark for a precomposed Latin-1 / Latin Extended-A
202/// character the 5×7 alphabet does not carry itself.
203fn decompose(character: char) -> Option<(char, Accent)> {
204    let (base, accent) = match character {
205        'á' | 'Á' => ('a', Accent::Acute),
206        'é' | 'É' => ('e', Accent::Acute),
207        'í' | 'Í' => ('i', Accent::Acute),
208        'ó' | 'Ó' => ('o', Accent::Acute),
209        'ú' | 'Ú' => ('u', Accent::Acute),
210        'ý' | 'Ý' => ('y', Accent::Acute),
211        'à' | 'À' => ('a', Accent::Grave),
212        'è' | 'È' => ('e', Accent::Grave),
213        'ì' | 'Ì' => ('i', Accent::Grave),
214        'ò' | 'Ò' => ('o', Accent::Grave),
215        'ù' | 'Ù' => ('u', Accent::Grave),
216        'â' | 'Â' => ('a', Accent::Circumflex),
217        'ê' | 'Ê' => ('e', Accent::Circumflex),
218        'î' | 'Î' => ('i', Accent::Circumflex),
219        'ô' | 'Ô' => ('o', Accent::Circumflex),
220        'û' | 'Û' => ('u', Accent::Circumflex),
221        'ä' | 'Ä' => ('a', Accent::Diaeresis),
222        'ë' | 'Ë' => ('e', Accent::Diaeresis),
223        'ï' | 'Ï' => ('i', Accent::Diaeresis),
224        'ö' | 'Ö' => ('o', Accent::Diaeresis),
225        'ü' | 'Ü' => ('u', Accent::Diaeresis),
226        'ÿ' | 'Ÿ' => ('y', Accent::Diaeresis),
227        'ã' | 'Ã' => ('a', Accent::Tilde),
228        'õ' | 'Õ' => ('o', Accent::Tilde),
229        'ñ' | 'Ñ' => ('n', Accent::Tilde),
230        'å' | 'Å' => ('a', Accent::Ring),
231        'ç' | 'Ç' => ('c', Accent::Cedilla),
232        _ => return None,
233    };
234    Some((base, accent))
235}
236
237fn upper(character: char) -> Option<char> {
238    character
239        .to_uppercase()
240        .next()
241        .filter(|upper| *upper != character)
242}
243
244fn notdef_rows() -> [u8; BUILTIN_HEIGHT as usize] {
245    [
246        0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111,
247    ]
248}
249
250fn rows_to_contours(rows: &[u8; BUILTIN_HEIGHT as usize]) -> Vec<Vec<Point>> {
251    let mut contours = Vec::new();
252    for (row, bits) in rows.iter().enumerate() {
253        for column in 0..BUILTIN_WIDTH {
254            let mask = 1_u8 << (BUILTIN_WIDTH - 1 - column);
255            if bits & mask == 0 {
256                continue;
257            }
258            let x0 = f64::from(column) * BUILTIN_CELL;
259            let x1 = x0 + BUILTIN_CELL;
260            let top = f64::from(BUILTIN_HEIGHT - 1 - row as u8) * BUILTIN_CELL;
261            let bottom = top + BUILTIN_CELL;
262            contours.push(vec![
263                Point::new(x0, bottom),
264                Point::new(x1, bottom),
265                Point::new(x1, top),
266                Point::new(x0, top),
267            ]);
268        }
269    }
270    contours
271}
272
273fn glyph_rows(code: u8) -> Option<[u8; 7]> {
274    let rows = match code {
275        b'A' => [
276            0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
277        ],
278        b'B' => [
279            0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
280        ],
281        b'C' => [
282            0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
283        ],
284        b'D' => [
285            0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
286        ],
287        b'E' => [
288            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
289        ],
290        b'F' => [
291            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
292        ],
293        b'G' => [
294            0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
295        ],
296        b'H' => [
297            0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
298        ],
299        b'I' => [
300            0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
301        ],
302        b'J' => [
303            0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100,
304        ],
305        b'K' => [
306            0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
307        ],
308        b'L' => [
309            0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
310        ],
311        b'M' => [
312            0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
313        ],
314        b'N' => [
315            0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
316        ],
317        b'O' => [
318            0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
319        ],
320        b'P' => [
321            0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
322        ],
323        b'Q' => [
324            0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101,
325        ],
326        b'R' => [
327            0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
328        ],
329        b'S' => [
330            0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
331        ],
332        b'T' => [
333            0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
334        ],
335        b'U' => [
336            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
337        ],
338        b'V' => [
339            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
340        ],
341        b'W' => [
342            0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
343        ],
344        b'X' => [
345            0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
346        ],
347        b'Y' => [
348            0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
349        ],
350        b'Z' => [
351            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
352        ],
353        b'0' => [
354            0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
355        ],
356        b'1' => [
357            0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
358        ],
359        b'2' => [
360            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
361        ],
362        b'3' => [
363            0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
364        ],
365        b'4' => [
366            0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
367        ],
368        b'5' => [
369            0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
370        ],
371        b'6' => [
372            0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
373        ],
374        b'7' => [
375            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
376        ],
377        b'8' => [
378            0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
379        ],
380        b'9' => [
381            0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
382        ],
383        b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
384        b',' => [0, 0, 0, 0, 0b01100, 0b01100, 0b01000],
385        b'!' => [
386            0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
387        ],
388        b'?' => [
389            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100,
390        ],
391        b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
392        b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
393        b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0b01000],
394        b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
395        b'"' => [0b01010, 0b01010, 0, 0, 0, 0, 0],
396        b'(' => [
397            0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
398        ],
399        b')' => [
400            0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
401        ],
402        b'/' => [
403            0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000,
404        ],
405        b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
406        b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
407        b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
408        b'#' => [
409            0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010,
410        ],
411        b'%' => [
412            0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
413        ],
414        b'&' => [
415            0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101,
416        ],
417        _ => return None,
418    };
419    Some(rows)
420}
421
422/// Collects `ttf-parser` outlines into em-space contours.
423struct OutlineBuilder {
424    units: f64,
425    contours: Vec<Vec<Point>>,
426    current: Vec<Point>,
427}
428
429impl OutlineBuilder {
430    fn new(units: f64) -> Self {
431        Self {
432            units,
433            contours: Vec::new(),
434            current: Vec::new(),
435        }
436    }
437
438    fn point(&self, x: f32, y: f32) -> Point {
439        Point::new(f64::from(x) / self.units, f64::from(y) / self.units)
440    }
441
442    fn finish_contour(&mut self) {
443        if self.current.len() > 1 {
444            self.contours.push(std::mem::take(&mut self.current));
445        }
446    }
447}
448
449impl ttf_parser::OutlineBuilder for OutlineBuilder {
450    fn move_to(&mut self, x: f32, y: f32) {
451        self.finish_contour();
452        self.current.push(self.point(x, y));
453    }
454
455    fn line_to(&mut self, x: f32, y: f32) {
456        self.current.push(self.point(x, y));
457    }
458
459    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
460        let Some(&start) = self.current.last() else {
461            return;
462        };
463        let control = self.point(x1, y1);
464        let end = self.point(x, y);
465        for step in 1..=8 {
466            let t = f64::from(step) / 8.0;
467            let u = 1.0 - t;
468            self.current.push(Point::new(
469                u * u * start.x + 2.0 * u * t * control.x + t * t * end.x,
470                u * u * start.y + 2.0 * u * t * control.y + t * t * end.y,
471            ));
472        }
473    }
474
475    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
476        let Some(&start) = self.current.last() else {
477            return;
478        };
479        let c1 = self.point(x1, y1);
480        let c2 = self.point(x2, y2);
481        let end = self.point(x, y);
482        for step in 1..=12 {
483            let t = f64::from(step) / 12.0;
484            let u = 1.0 - t;
485            self.current.push(Point::new(
486                u * u * u * start.x
487                    + 3.0 * u * u * t * c1.x
488                    + 3.0 * u * t * t * c2.x
489                    + t * t * t * end.x,
490                u * u * u * start.y
491                    + 3.0 * u * u * t * c1.y
492                    + 3.0 * u * t * t * c2.y
493                    + t * t * t * end.y,
494            ));
495        }
496    }
497
498    fn close(&mut self) {
499        self.finish_contour();
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::Font;
506    use pdf2::Encoding;
507
508    #[test]
509    fn the_builtin_font_draws_letters_as_ink() {
510        let font = Font::builtin(Encoding::standard());
511        let glyph = font.glyph(b'H').expect("H");
512        assert!(!glyph.contours.is_empty());
513        assert!((glyph.advance - 0.6667).abs() < 1e-3);
514        // Every contour is a rectangle inside the glyph box.
515        for contour in &glyph.contours {
516            assert_eq!(contour.len(), 4);
517            for point in contour {
518                assert!(point.x >= 0.0 && point.x <= 6.0 / 9.0 + 1e-9);
519                assert!(point.y >= 0.0 && point.y <= 7.0 / 9.0 + 1e-9);
520            }
521        }
522    }
523
524    #[test]
525    fn the_builtin_font_is_blank_for_space() {
526        let font = Font::builtin(Encoding::standard());
527        let glyph = font.glyph(b' ').expect("space");
528        assert!(glyph.contours.is_empty());
529        assert!(glyph.advance > 0.0);
530    }
531
532    #[test]
533    fn a_broken_font_program_is_rejected() {
534        assert!(Font::true_type(Encoding::standard(), vec![0, 1, 2, 3]).is_none());
535        assert!(Font::true_type(Encoding::standard(), Vec::new()).is_none());
536    }
537
538    #[test]
539    fn accented_latin_composes_instead_of_drawing_notdef() {
540        let font = Font::builtin(Encoding::win_ansi());
541        // code, the ASCII base the accent is composed onto, and the number of
542        // mark cells the accent contributes.
543        for (code, base, marks) in [
544            (0xE9_u8, b'E', 3), // é, acute
545            (0xF1, b'N', 3),    // ñ, tilde
546            (0xFC, b'U', 2),    // ü, diaeresis
547            (0xE7, b'C', 3),    // ç, cedilla
548            (0xE5, b'A', 4),    // å, ring
549            (0xE2, b'A', 3),    // â, circumflex
550        ] {
551            let glyph = font.glyph(code).expect("a composed glyph");
552            let plain = font.glyph(base).expect("the base letter");
553            assert_eq!(
554                glyph.contours.len(),
555                plain.contours.len() + marks,
556                "{} on {}",
557                code as char,
558                base as char
559            );
560            assert_ne!(glyph.contours, plain.contours);
561        }
562        // Anything the table does not name still falls back to .notdef, and
563        // that is a hollow box, not a panic.
564        let other = font.glyph(0xA4).expect("undefined code");
565        assert_eq!(other.contours.len(), 20, "the notdef box");
566    }
567
568    #[test]
569    fn marks_sit_outside_the_glyph_box_and_cedillas_below_the_baseline() {
570        let font = Font::builtin(Encoding::win_ansi());
571        let acute = font.glyph(0xE9).expect("é");
572        let top = acute
573            .contours
574            .iter()
575            .flatten()
576            .fold(f64::MIN, |max, point| max.max(point.y));
577        assert!((7.0 / 9.0..=1.0).contains(&top), "accent tops out at {top}");
578        let cedilla = font.glyph(0xE7).expect("ç");
579        let bottom = cedilla
580            .contours
581            .iter()
582            .flatten()
583            .fold(f64::MAX, |min, point| min.min(point.y));
584        assert!(bottom < 0.0, "the cedilla hangs to {bottom}");
585    }
586
587    #[test]
588    fn unknown_characters_become_the_notdef_box() {
589        let font = Font::builtin(Encoding::standard());
590        // 0xA4 is undefined in StandardEncoding, so there is no glyph at all.
591        assert!(font.glyph(0xA4).is_none());
592        // A mapped but unpatterned character gets the notdef box, not a panic.
593        let glyph = font.glyph(b'@').expect("@");
594        assert_eq!(
595            glyph.contours.len(),
596            20,
597            "the notdef box is a hollow 5×7 frame"
598        );
599    }
600}