Skip to main content

pdfboss_write/
font.rs

1//! The fourteen standard fonts (ISO 32000 §9.6.2.2), with WinAnsi text
2//! encoding and AFM metrics from `pdfboss-encoding`. Text in these faces
3//! needs no embedded font program — every conforming reader carries them.
4
5use pdfboss_core::{Dict, Name, Object};
6
7use crate::error::{Error, Result};
8
9/// One of the fourteen standard fonts every PDF consumer provides.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Standard14 {
12    /// Helvetica.
13    Helvetica,
14    /// Helvetica-Bold.
15    HelveticaBold,
16    /// Helvetica-Oblique.
17    HelveticaOblique,
18    /// Helvetica-BoldOblique.
19    HelveticaBoldOblique,
20    /// Times-Roman.
21    TimesRoman,
22    /// Times-Bold.
23    TimesBold,
24    /// Times-Italic.
25    TimesItalic,
26    /// Times-BoldItalic.
27    TimesBoldItalic,
28    /// Courier.
29    Courier,
30    /// Courier-Bold.
31    CourierBold,
32    /// Courier-Oblique.
33    CourierOblique,
34    /// Courier-BoldOblique.
35    CourierBoldOblique,
36    /// Symbol (font-specific encoding).
37    Symbol,
38    /// ZapfDingbats (font-specific encoding).
39    ZapfDingbats,
40}
41
42impl Standard14 {
43    /// All fourteen, in ISO 32000 listing order.
44    pub const ALL: [Standard14; 14] = [
45        Standard14::Helvetica,
46        Standard14::HelveticaBold,
47        Standard14::HelveticaOblique,
48        Standard14::HelveticaBoldOblique,
49        Standard14::TimesRoman,
50        Standard14::TimesBold,
51        Standard14::TimesItalic,
52        Standard14::TimesBoldItalic,
53        Standard14::Courier,
54        Standard14::CourierBold,
55        Standard14::CourierOblique,
56        Standard14::CourierBoldOblique,
57        Standard14::Symbol,
58        Standard14::ZapfDingbats,
59    ];
60
61    /// The PostScript base font name, e.g. `"Helvetica-Bold"`.
62    pub fn base_font(self) -> &'static str {
63        match self {
64            Standard14::Helvetica => "Helvetica",
65            Standard14::HelveticaBold => "Helvetica-Bold",
66            Standard14::HelveticaOblique => "Helvetica-Oblique",
67            Standard14::HelveticaBoldOblique => "Helvetica-BoldOblique",
68            Standard14::TimesRoman => "Times-Roman",
69            Standard14::TimesBold => "Times-Bold",
70            Standard14::TimesItalic => "Times-Italic",
71            Standard14::TimesBoldItalic => "Times-BoldItalic",
72            Standard14::Courier => "Courier",
73            Standard14::CourierBold => "Courier-Bold",
74            Standard14::CourierOblique => "Courier-Oblique",
75            Standard14::CourierBoldOblique => "Courier-BoldOblique",
76            Standard14::Symbol => "Symbol",
77            Standard14::ZapfDingbats => "ZapfDingbats",
78        }
79    }
80
81    /// Parses a PostScript base font name back to the variant. Exact names
82    /// only — aliases and subset-tagged forms are the reading side's
83    /// business, not the writer's.
84    pub fn from_base_font(name: &str) -> Option<Standard14> {
85        Standard14::ALL
86            .into_iter()
87            .find(|font| font.base_font() == name)
88    }
89
90    /// Whether this face encodes text as WinAnsi (the twelve text faces)
91    /// rather than a font-specific built-in encoding.
92    fn is_win_ansi(self) -> bool {
93        !matches!(self, Standard14::Symbol | Standard14::ZapfDingbats)
94    }
95
96    /// The face's code-to-character table: WinAnsi for the twelve text
97    /// faces, the built-in encodings of Annex D.5 and D.6 for Symbol and
98    /// ZapfDingbats.
99    ///
100    /// Covers ISO 32000-1 Annex D.5 and Annex D.6.
101    fn decoder(self) -> fn(u8) -> Option<char> {
102        match self {
103            Standard14::Symbol => pdfboss_encoding::symbol,
104            Standard14::ZapfDingbats => pdfboss_encoding::zapf_dingbats,
105            _ => pdfboss_encoding::win_ansi,
106        }
107    }
108
109    /// The code for `ch` in the face's encoding, scanning codes in
110    /// ascending order so a duplicated character would resolve to its lowest
111    /// code. A character the encoding lacks is an [`Error::Unencodable`].
112    fn encode_char(self, ch: char) -> Result<u8> {
113        let decode = self.decoder();
114        (0u8..=255)
115            .find(|&code| decode(code) == Some(ch))
116            .ok_or(Error::Unencodable {
117                ch,
118                font: self.base_font(),
119            })
120    }
121
122    /// Encodes text to font code bytes: WinAnsi for the twelve text faces,
123    /// the font-specific built-in encoding for Symbol and ZapfDingbats.
124    /// A character without a code is an [`Error::Unencodable`]
125    /// (crate::Error::Unencodable) — never silently dropped or replaced.
126    pub fn encode(self, text: &str) -> Result<Vec<u8>> {
127        text.chars().map(|ch| self.encode_char(ch)).collect()
128    }
129
130    /// Advance width of one character in units per 1000 of font size, from
131    /// the AFM metrics. `None` when the character has no code or metric;
132    /// Symbol and ZapfDingbats carry no metrics, so theirs are always `None`.
133    pub fn width(self, ch: char) -> Option<f32> {
134        let code = self.encode_char(ch).ok()?;
135        let glyph = match self {
136            Standard14::Symbol => pdfboss_encoding::symbol_glyph_name(code)?,
137            Standard14::ZapfDingbats => pdfboss_encoding::zapf_dingbats_glyph_name(code)?,
138            _ => pdfboss_encoding::win_ansi_glyph_name(code)?,
139        };
140        pdfboss_encoding::standard_14_width(self.base_font(), glyph)
141    }
142
143    /// Width of a whole string at `size`, in text-space units. Errors on
144    /// unencodable characters, like [`encode`](Standard14::encode); an
145    /// encodable character whose glyph has no AFM metric is an
146    /// [`Error::Other`] naming the glyph. No kerning — the AFM kern pairs
147    /// are not bundled, so this is the sum of bare advance widths.
148    pub fn text_width(self, text: &str, size: f32) -> Result<f32> {
149        let mut sum = 0.0f32;
150        for ch in text.chars() {
151            let code = self.encode_char(ch)?;
152            let glyph = pdfboss_encoding::win_ansi_glyph_name(code).ok_or_else(|| {
153                Error::Other(format!("code {code:#04x} has no WinAnsi glyph name"))
154            })?;
155            let width =
156                pdfboss_encoding::standard_14_width(self.base_font(), glyph).ok_or_else(|| {
157                    Error::Other(format!(
158                        "{} has no metric for glyph {glyph:?}",
159                        self.base_font()
160                    ))
161                })?;
162            sum += width;
163        }
164        Ok(sum * size / 1000.0)
165    }
166
167    /// The font dictionary describing this face (`/Type /Font`,
168    /// `/Subtype /Type1`, `/BaseFont`, and `/Encoding /WinAnsiEncoding`
169    /// for the twelve text faces).
170    pub(crate) fn font_dict(self) -> Dict {
171        let mut dict = Dict::new();
172        dict.insert(Name("Type".into()), Object::Name(Name("Font".into())));
173        dict.insert(Name("Subtype".into()), Object::Name(Name("Type1".into())));
174        dict.insert(
175            Name("BaseFont".into()),
176            Object::Name(Name(self.base_font().into())),
177        );
178        if self.is_win_ansi() {
179            dict.insert(
180                Name("Encoding".into()),
181                Object::Name(Name("WinAnsiEncoding".into())),
182            );
183        }
184        dict
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use pdfboss_encoding::standard_14_width;
191
192    use super::*;
193    use crate::error::Error;
194
195    // Covers ISO 32000-1 §9.6.2.2.
196    #[test]
197    fn base_font_round_trips_all_fourteen() {
198        for font in Standard14::ALL {
199            assert_eq!(Standard14::from_base_font(font.base_font()), Some(font));
200        }
201        assert_eq!(Standard14::Helvetica.base_font(), "Helvetica");
202        assert_eq!(
203            Standard14::HelveticaBoldOblique.base_font(),
204            "Helvetica-BoldOblique"
205        );
206        assert_eq!(Standard14::TimesRoman.base_font(), "Times-Roman");
207        assert_eq!(Standard14::TimesBoldItalic.base_font(), "Times-BoldItalic");
208        assert_eq!(Standard14::CourierOblique.base_font(), "Courier-Oblique");
209        assert_eq!(Standard14::Symbol.base_font(), "Symbol");
210        assert_eq!(Standard14::ZapfDingbats.base_font(), "ZapfDingbats");
211        assert_eq!(Standard14::from_base_font("helvetica"), None);
212        assert_eq!(Standard14::from_base_font("Arial"), None);
213        assert_eq!(Standard14::from_base_font(""), None);
214    }
215
216    // Covers ISO 32000-1 Annex D.2.
217    #[test]
218    fn encode_ascii_and_win_ansi_specials() {
219        assert_eq!(Standard14::Helvetica.encode("Hi").unwrap(), b"Hi");
220        assert_eq!(Standard14::TimesRoman.encode("\u{E9}").unwrap(), [0xE9]);
221        assert_eq!(Standard14::Courier.encode("\u{20AC}").unwrap(), [0x80]);
222        assert_eq!(Standard14::Helvetica.encode("\u{201C}").unwrap(), [0x93]);
223    }
224
225    #[test]
226    fn encode_rejects_unencodable_chars() {
227        match Standard14::HelveticaBold.encode("\u{2318}").unwrap_err() {
228            Error::Unencodable { ch, font } => {
229                assert_eq!(ch, '\u{2318}');
230                assert_eq!(font, "Helvetica-Bold");
231            }
232            other => panic!("expected Unencodable, got {other:?}"),
233        }
234    }
235
236    #[test]
237    fn symbol_faces_encode_through_their_built_in_encodings() {
238        // Greek through Symbol's table, a dingbat through ZapfDingbats', and
239        // a character neither table has is still refused; the two faces
240        // have no bundled metrics, so widths stay unknown.
241        assert_eq!(
242            Standard14::Symbol.encode("\u{03B1}\u{2126}").unwrap(),
243            [0o141, 0o127]
244        );
245        assert_eq!(
246            Standard14::ZapfDingbats.encode("\u{2701}").unwrap(),
247            [0o041]
248        );
249        for font in [Standard14::Symbol, Standard14::ZapfDingbats] {
250            assert!(matches!(
251                font.encode("a"),
252                Err(Error::Unencodable { ch: 'a', .. })
253            ));
254            assert_eq!(font.width('\u{03B1}'), None);
255        }
256        assert_eq!(Standard14::Symbol.encode("").unwrap(), Vec::<u8>::new());
257    }
258
259    // Covers ISO 32000-1 §9.6.2.2.
260    #[test]
261    fn width_matches_direct_afm_lookups() {
262        let font = Standard14::Helvetica;
263        for (ch, glyph) in [('H', "H"), ('e', "e"), ('l', "l"), ('o', "o")] {
264            assert_eq!(font.width(ch), standard_14_width("Helvetica", glyph));
265            assert!(font.width(ch).is_some());
266        }
267        assert_eq!(font.width('\u{2318}'), None); // unencodable
268        assert_eq!(font.width('\u{20AC}'), None); // pre-Euro AFMs carry no metric
269    }
270
271    #[test]
272    fn text_width_scales_by_size() {
273        let font = Standard14::TimesBold;
274        let sum: f32 = "Hello".chars().map(|ch| font.width(ch).unwrap()).sum();
275        assert_eq!(font.text_width("Hello", 12.0).unwrap(), sum * 12.0 / 1000.0);
276        assert_eq!(
277            font.text_width("Hello", 1000.0).unwrap(),
278            font.text_width("Hello", 500.0).unwrap() * 2.0
279        );
280        assert_eq!(font.text_width("", 12.0).unwrap(), 0.0);
281        assert!(matches!(
282            font.text_width("a\u{2318}", 12.0),
283            Err(Error::Unencodable { ch: '\u{2318}', .. })
284        ));
285        assert!(matches!(
286            font.text_width("\u{20AC}", 12.0),
287            Err(Error::Other(msg)) if msg.contains("Euro")
288        ));
289    }
290
291    // Covers ISO 32000-1 §9.5 and §9.6.2.1.
292    #[test]
293    fn font_dict_win_ansi_and_symbol() {
294        let dict = Standard14::HelveticaOblique.font_dict();
295        assert_eq!(dict.len(), 4);
296        assert_eq!(dict.get_name("Type").map(|n| n.0.as_str()), Some("Font"));
297        assert_eq!(
298            dict.get_name("Subtype").map(|n| n.0.as_str()),
299            Some("Type1")
300        );
301        assert_eq!(
302            dict.get_name("BaseFont").map(|n| n.0.as_str()),
303            Some("Helvetica-Oblique")
304        );
305        assert_eq!(
306            dict.get_name("Encoding").map(|n| n.0.as_str()),
307            Some("WinAnsiEncoding")
308        );
309
310        let dict = Standard14::Symbol.font_dict();
311        assert_eq!(dict.len(), 3);
312        assert_eq!(
313            dict.get_name("BaseFont").map(|n| n.0.as_str()),
314            Some("Symbol")
315        );
316        assert!(dict.get("Encoding").is_none());
317    }
318}