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 = self.glyph_name(code)?;
136        pdfboss_encoding::standard_14_width(self.base_font(), glyph)
137    }
138
139    fn glyph_name(self, code: u8) -> Option<&'static str> {
140        match self {
141            Standard14::Symbol => pdfboss_encoding::symbol_glyph_name(code),
142            Standard14::ZapfDingbats => pdfboss_encoding::zapf_dingbats_glyph_name(code),
143            _ => pdfboss_encoding::win_ansi_glyph_name(code),
144        }
145    }
146
147    /// Width of a whole string at `size`, in text-space units. Errors on
148    /// unencodable characters, like [`encode`](Standard14::encode); an
149    /// encodable character whose glyph has no AFM metric is an
150    /// [`Error::Other`] naming the glyph. No kerning — the AFM kern pairs
151    /// are not bundled, so this is the sum of bare advance widths.
152    pub fn text_width(self, text: &str, size: f32) -> Result<f32> {
153        let mut sum = 0.0f32;
154        for ch in text.chars() {
155            let code = self.encode_char(ch)?;
156            let glyph = self.glyph_name(code).ok_or_else(|| {
157                Error::Other(format!(
158                    "{} code {code:#04x} has no glyph name",
159                    self.base_font()
160                ))
161            })?;
162            let width =
163                pdfboss_encoding::standard_14_width(self.base_font(), glyph).ok_or_else(|| {
164                    Error::Other(format!(
165                        "{} has no metric for glyph {glyph:?}",
166                        self.base_font()
167                    ))
168                })?;
169            sum += width;
170        }
171        Ok(sum * size / 1000.0)
172    }
173
174    /// The font dictionary describing this face (`/Type /Font`,
175    /// `/Subtype /Type1`, `/BaseFont`, and `/Encoding /WinAnsiEncoding`
176    /// for the twelve text faces).
177    pub(crate) fn font_dict(self) -> Dict {
178        let mut dict = Dict::new();
179        dict.insert(Name("Type".into()), Object::Name(Name("Font".into())));
180        dict.insert(Name("Subtype".into()), Object::Name(Name("Type1".into())));
181        dict.insert(
182            Name("BaseFont".into()),
183            Object::Name(Name(self.base_font().into())),
184        );
185        if self.is_win_ansi() {
186            dict.insert(
187                Name("Encoding".into()),
188                Object::Name(Name("WinAnsiEncoding".into())),
189            );
190        }
191        dict
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use pdfboss_encoding::standard_14_width;
198
199    use super::*;
200    use crate::error::Error;
201
202    // Covers ISO 32000-1 §9.6.2.2.
203    #[test]
204    fn base_font_round_trips_all_fourteen() {
205        for font in Standard14::ALL {
206            assert_eq!(Standard14::from_base_font(font.base_font()), Some(font));
207        }
208        assert_eq!(Standard14::Helvetica.base_font(), "Helvetica");
209        assert_eq!(
210            Standard14::HelveticaBoldOblique.base_font(),
211            "Helvetica-BoldOblique"
212        );
213        assert_eq!(Standard14::TimesRoman.base_font(), "Times-Roman");
214        assert_eq!(Standard14::TimesBoldItalic.base_font(), "Times-BoldItalic");
215        assert_eq!(Standard14::CourierOblique.base_font(), "Courier-Oblique");
216        assert_eq!(Standard14::Symbol.base_font(), "Symbol");
217        assert_eq!(Standard14::ZapfDingbats.base_font(), "ZapfDingbats");
218        assert_eq!(Standard14::from_base_font("helvetica"), None);
219        assert_eq!(Standard14::from_base_font("Arial"), None);
220        assert_eq!(Standard14::from_base_font(""), None);
221    }
222
223    // Covers ISO 32000-1 Annex D.2.
224    #[test]
225    fn encode_ascii_and_win_ansi_specials() {
226        assert_eq!(Standard14::Helvetica.encode("Hi").unwrap(), b"Hi");
227        assert_eq!(Standard14::TimesRoman.encode("\u{E9}").unwrap(), [0xE9]);
228        assert_eq!(Standard14::Courier.encode("\u{20AC}").unwrap(), [0x80]);
229        assert_eq!(Standard14::Helvetica.encode("\u{201C}").unwrap(), [0x93]);
230    }
231
232    #[test]
233    fn encode_rejects_unencodable_chars() {
234        match Standard14::HelveticaBold.encode("\u{2318}").unwrap_err() {
235            Error::Unencodable { ch, font } => {
236                assert_eq!(ch, '\u{2318}');
237                assert_eq!(font, "Helvetica-Bold");
238            }
239            other => panic!("expected Unencodable, got {other:?}"),
240        }
241    }
242
243    #[test]
244    fn symbol_faces_encode_through_their_built_in_encodings() {
245        // Greek through Symbol's table, a dingbat through ZapfDingbats', and
246        // a character neither table has is still refused; the two faces
247        // have no bundled metrics, so widths stay unknown.
248        assert_eq!(
249            Standard14::Symbol.encode("\u{03B1}\u{2126}").unwrap(),
250            [0o141, 0o127]
251        );
252        assert_eq!(
253            Standard14::ZapfDingbats.encode("\u{2701}").unwrap(),
254            [0o041]
255        );
256        for font in [Standard14::Symbol, Standard14::ZapfDingbats] {
257            assert!(matches!(
258                font.encode("a"),
259                Err(Error::Unencodable { ch: 'a', .. })
260            ));
261            assert_eq!(font.width('\u{03B1}'), None);
262        }
263        assert_eq!(Standard14::Symbol.encode("").unwrap(), Vec::<u8>::new());
264    }
265
266    // Covers ISO 32000-1 §9.6.2.2.
267    #[test]
268    fn width_matches_direct_afm_lookups() {
269        let font = Standard14::Helvetica;
270        for (ch, glyph) in [('H', "H"), ('e', "e"), ('l', "l"), ('o', "o")] {
271            assert_eq!(font.width(ch), standard_14_width("Helvetica", glyph));
272            assert!(font.width(ch).is_some());
273        }
274        assert_eq!(font.width('\u{2318}'), None); // unencodable
275        assert_eq!(font.width('\u{20AC}'), None); // pre-Euro AFMs carry no metric
276    }
277
278    #[test]
279    fn text_width_scales_by_size() {
280        let font = Standard14::TimesBold;
281        let sum: f32 = "Hello".chars().map(|ch| font.width(ch).unwrap()).sum();
282        assert_eq!(font.text_width("Hello", 12.0).unwrap(), sum * 12.0 / 1000.0);
283        assert_eq!(
284            font.text_width("Hello", 1000.0).unwrap(),
285            font.text_width("Hello", 500.0).unwrap() * 2.0
286        );
287        assert_eq!(font.text_width("", 12.0).unwrap(), 0.0);
288        assert!(matches!(
289            font.text_width("a\u{2318}", 12.0),
290            Err(Error::Unencodable { ch: '\u{2318}', .. })
291        ));
292        assert!(matches!(
293            font.text_width("\u{20AC}", 12.0),
294            Err(Error::Other(msg)) if msg.contains("Euro")
295        ));
296    }
297
298    #[test]
299    fn text_width_names_symbol_and_zapf_dingbats_glyphs_from_their_own_encodings() {
300        assert!(matches!(
301            Standard14::Symbol.text_width("\u{03B1}", 12.0),
302            Err(Error::Other(msg)) if msg.contains("\"alpha\"")
303        ));
304        assert!(matches!(
305            Standard14::ZapfDingbats.text_width("\u{2192}", 12.0),
306            Err(Error::Other(msg)) if !msg.contains("Otilde")
307        ));
308    }
309
310    // Covers ISO 32000-1 §9.5 and §9.6.2.1.
311    #[test]
312    fn font_dict_win_ansi_and_symbol() {
313        let dict = Standard14::HelveticaOblique.font_dict();
314        assert_eq!(dict.len(), 4);
315        assert_eq!(dict.get_name("Type").map(|n| n.0.as_str()), Some("Font"));
316        assert_eq!(
317            dict.get_name("Subtype").map(|n| n.0.as_str()),
318            Some("Type1")
319        );
320        assert_eq!(
321            dict.get_name("BaseFont").map(|n| n.0.as_str()),
322            Some("Helvetica-Oblique")
323        );
324        assert_eq!(
325            dict.get_name("Encoding").map(|n| n.0.as_str()),
326            Some("WinAnsiEncoding")
327        );
328
329        let dict = Standard14::Symbol.font_dict();
330        assert_eq!(dict.len(), 3);
331        assert_eq!(
332            dict.get_name("BaseFont").map(|n| n.0.as_str()),
333            Some("Symbol")
334        );
335        assert!(dict.get("Encoding").is_none());
336    }
337}