Skip to main content

pdf_textlayer/
metrics.rs

1//! Advance widths used to size each invisible run.
2//!
3//! The overlay font has no outlines, so any font's widths can drive the
4//! layout. Proportional widths matter: OCR reports whole lines, and a word
5//! inside a line only lands under its image when the characters before it
6//! advance by roughly what the printed characters did.
7
8use unicode_width::UnicodeWidthChar;
9
10use crate::metrics_data::{HELVETICA, HELVETICA_BOLD, TIMES, TIMES_BOLD, TIMES_BOLD_ITALIC, TIMES_ITALIC};
11
12const COURIER_ADVANCE: u16 = 600;
13const WIDE_ADVANCE: u16 = 1000;
14
15/// Which width table sizes the text.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
17pub enum FontMetrics {
18    /// Helvetica widths. Fits most printed Latin text.
19    #[default]
20    Helvetica,
21    /// Times widths.
22    Times,
23    /// Courier widths (monospaced).
24    Courier,
25}
26
27impl FontMetrics {
28    /// Resolve a font name.
29    ///
30    /// Accepts the PyMuPDF short names the Python package has always taken
31    /// (`helv`, `tiro`, `cour`). The CJK names (`china-s`, `china-t`,
32    /// `japan`, `korea`) resolve to Helvetica: the overlay font encodes every
33    /// script, so a CJK font is no longer needed to keep that text.
34    pub fn from_name(name: &str) -> Option<FontMetrics> {
35        match name.to_ascii_lowercase().as_str() {
36            "helv" | "helvetica" | "china-s" | "china-t" | "japan" | "korea" => Some(FontMetrics::Helvetica),
37            "tiro" | "times" | "times-roman" => Some(FontMetrics::Times),
38            "cour" | "courier" => Some(FontMetrics::Courier),
39            _ => None,
40        }
41    }
42
43    /// Advance of `character` in 1/1000 em, or `None` when it cannot be drawn.
44    ///
45    /// Control characters, zero-width characters, and characters outside the
46    /// Basic Multilingual Plane cannot be drawn.
47    pub(crate) fn advance(&self, character: char) -> Option<u16> {
48        let codepoint = character as u32;
49        if codepoint > 0xFFFF {
50            return None;
51        }
52
53        let table: &[(u16, u16)] = match self {
54            FontMetrics::Helvetica => &HELVETICA,
55            FontMetrics::Times => &TIMES,
56            FontMetrics::Courier => &[],
57        };
58
59        if let Some(advance) = lookup(table, character) {
60            return Some(advance);
61        }
62
63        match character.width() {
64            None | Some(0) => None,
65            Some(1) => Some(self.fallback_advance()),
66            Some(_) => Some(WIDE_ADVANCE),
67        }
68    }
69
70    /// Advance for a narrow character the table does not list.
71    pub(crate) fn fallback_advance(&self) -> u16 {
72        match self {
73            FontMetrics::Helvetica => 556,
74            FontMetrics::Times => 500,
75            FontMetrics::Courier => COURIER_ADVANCE,
76        }
77    }
78}
79
80impl std::str::FromStr for FontMetrics {
81    type Err = crate::Error;
82
83    fn from_str(name: &str) -> Result<FontMetrics, crate::Error> {
84        FontMetrics::from_name(name).ok_or_else(|| crate::Error::UnknownFont(name.to_string()))
85    }
86}
87
88fn lookup(table: &[(u16, u16)], character: char) -> Option<u16> {
89    let codepoint = u16::try_from(character as u32).ok()?;
90    let index = table.binary_search_by_key(&codepoint, |entry| entry.0).ok()?;
91
92    Some(table[index].1)
93}
94
95/// Advance of `character` in one of the 14 standard fonts, in 1/1000 em.
96///
97/// A PDF may use a standard font without listing its widths. `base_font` is
98/// the font's `/BaseFont` name. Names outside the standard set get the
99/// closest of them: bold and italic are read from the name, and anything
100/// that is not Times or Courier is treated as Helvetica.
101pub(crate) fn standard_font_advance(base_font: &str, character: char) -> u16 {
102    let name = base_font.to_ascii_lowercase();
103    let bold = name.contains("bold");
104    let italic = name.contains("italic") || name.contains("oblique");
105
106    if name.contains("courier") {
107        return COURIER_ADVANCE;
108    }
109
110    let (table, fallback): (&[(u16, u16)], u16) = if name.contains("times") {
111        match (bold, italic) {
112            (true, true) => (&TIMES_BOLD_ITALIC, 500),
113            (true, false) => (&TIMES_BOLD, 500),
114            (false, true) => (&TIMES_ITALIC, 500),
115            (false, false) => (&TIMES, 500),
116        }
117    } else if bold {
118        (&HELVETICA_BOLD, 556)
119    } else {
120        (&HELVETICA, 556)
121    };
122
123    lookup(table, character).unwrap_or(fallback)
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn helvetica_widths_match_the_standard_metrics() {
132        let helvetica = FontMetrics::Helvetica;
133
134        assert_eq!(helvetica.advance(' '), Some(278));
135        assert_eq!(helvetica.advance('A'), Some(667));
136        assert_eq!(helvetica.advance('i'), Some(222));
137        assert_eq!(helvetica.advance('é'), Some(556));
138        assert_eq!(helvetica.advance('€'), Some(556));
139    }
140
141    #[test]
142    fn scripts_outside_the_table_still_have_an_advance() {
143        let helvetica = FontMetrics::Helvetica;
144
145        assert_eq!(helvetica.advance('中'), Some(1000));
146        assert_eq!(helvetica.advance('א'), Some(556));
147    }
148
149    #[test]
150    fn undrawable_characters_have_no_advance() {
151        let helvetica = FontMetrics::Helvetica;
152
153        assert_eq!(helvetica.advance('\n'), None);
154        assert_eq!(helvetica.advance('\u{200b}'), None);
155        assert_eq!(helvetica.advance('\u{0301}'), None);
156        assert_eq!(helvetica.advance('😀'), None);
157    }
158
159    #[test]
160    fn standard_fonts_are_picked_from_the_base_font_name() {
161        assert_eq!(standard_font_advance("Helvetica", 'a'), 556);
162        assert_eq!(standard_font_advance("Helvetica-Bold", 'a'), 556);
163        assert_eq!(standard_font_advance("Helvetica-Bold", 'f'), 333);
164        assert_eq!(standard_font_advance("Helvetica", 'f'), 278);
165        assert_eq!(standard_font_advance("Times-Roman", 'a'), 444);
166        assert_eq!(standard_font_advance("Times-BoldItalic", 'a'), 500);
167        assert_eq!(standard_font_advance("Courier-Oblique", 'a'), 600);
168        assert_eq!(standard_font_advance("ABCDEF+Arial-BoldMT", 'f'), 333);
169    }
170
171    #[test]
172    fn courier_is_monospaced() {
173        let courier = FontMetrics::Courier;
174
175        assert_eq!(courier.advance('i'), Some(600));
176        assert_eq!(courier.advance('W'), Some(600));
177    }
178
179    #[test]
180    fn pymupdf_font_names_resolve() {
181        assert_eq!(FontMetrics::from_name("helv"), Some(FontMetrics::Helvetica));
182        assert_eq!(FontMetrics::from_name("tiro"), Some(FontMetrics::Times));
183        assert_eq!(FontMetrics::from_name("cour"), Some(FontMetrics::Courier));
184        assert_eq!(FontMetrics::from_name("china-s"), Some(FontMetrics::Helvetica));
185        assert_eq!(FontMetrics::from_name("comic"), None);
186    }
187}