rpdfium-doc 7676.6.2

Document-level features for rpdfium
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Derived from PDFium's cba_fontmap.cpp
// Original: Copyright 2014 The PDFium Authors
// Licensed under BSD-3-Clause / Apache-2.0
// See pdfium-upstream/LICENSE for the original license.

//! Form field font mapping (`/DR` + `/DA` resolution).
//!
//! `BaFontMap` resolves the fonts available for form field appearance streams
//! by parsing the interactive form's default resource dictionary (`/DR`) and
//! the field's default appearance string (`/DA`).

use std::collections::HashMap;

use rpdfium_core::{Name, PdfSource};
use rpdfium_parser::{Object, ObjectStore};

/// A single entry in the form font map.
#[derive(Debug, Clone)]
pub struct BaFontMapEntry {
    /// The font resource name (e.g., "Helv", "Cour", "ZaDb").
    pub font_name: String,
    /// Charset identifier (0 = ANSI, 1 = Symbol, etc.).
    pub charset: u8,
}

/// Font map for form field appearance streams.
///
/// Resolves font resources from the interactive form's `/DR` dictionary
/// and the field's `/DA` (default appearance) string.
#[derive(Debug, Clone)]
pub struct BaFontMap {
    /// Available font entries from `/DR`.
    entries: Vec<BaFontMapEntry>,
    /// Default font name extracted from `/DA`.
    default_font: Option<String>,
    /// Default font size extracted from `/DA`.
    default_size: f32,
}

impl BaFontMap {
    /// Build a font map from the form's `/DR` dictionary and `/DA` string.
    ///
    /// `dr_dict` is the Font sub-dictionary from `/DR` → `/Font`.
    /// `da_string` is the default appearance string (e.g., "0 g /Helv 12 Tf").
    pub fn from_resources<S: PdfSource>(
        dr_dict: Option<&HashMap<Name, Object>>,
        da_string: Option<&str>,
        store: &ObjectStore<S>,
    ) -> Self {
        let mut entries = Vec::new();

        // Parse /DR → /Font entries
        if let Some(font_dict) = dr_dict {
            for (name, obj) in font_dict {
                let font_name = name.as_str().into_owned();

                // Try to extract charset from the font dictionary
                let charset = if let Ok(resolved) = store.deep_resolve(obj) {
                    extract_charset(resolved)
                } else {
                    0 // default ANSI
                };

                entries.push(BaFontMapEntry { font_name, charset });
            }
        }

        // Parse /DA string
        let (default_font, default_size) = if let Some(da) = da_string {
            parse_default_appearance_font(da)
        } else {
            (None, 0.0)
        };

        Self {
            entries,
            default_font,
            default_size,
        }
    }

    /// Return the default font name from `/DA`.
    pub fn default_font_name(&self) -> Option<&str> {
        self.default_font.as_deref()
    }

    /// Return the default font size from `/DA`.
    pub fn default_font_size(&self) -> f32 {
        self.default_size
    }

    /// Return the number of available fonts.
    pub fn font_count(&self) -> usize {
        self.entries.len()
    }

    /// Return the font name at the given index.
    pub fn font_name(&self, index: usize) -> Option<&str> {
        self.entries.get(index).map(|e| e.font_name.as_str())
    }

    /// Upstream-aligned alias for [`font_name`](Self::font_name).
    #[inline]
    pub fn get_font_name(&self, index: usize) -> Option<&str> {
        self.font_name(index)
    }

    /// Return the charset of the font at the given index.
    pub fn charset(&self, index: usize) -> Option<u8> {
        self.entries.get(index).map(|e| e.charset)
    }

    /// Upstream-aligned alias for [`charset`](Self::charset).
    #[inline]
    pub fn get_charset(&self, index: usize) -> Option<u8> {
        self.charset(index)
    }

    /// Find a font entry by name.
    pub fn find_font(&self, name: &str) -> Option<&BaFontMapEntry> {
        self.entries.iter().find(|e| e.font_name == name)
    }

    /// Return all font entries.
    pub fn entries(&self) -> &[BaFontMapEntry] {
        &self.entries
    }

    /// Find a font entry by name, falling back to standard font name aliases.
    ///
    /// Tries the exact name first, then checks common abbreviation/alias mappings:
    /// - "Helv" ↔ "Helvetica"
    /// - "Cour" ↔ "Courier"
    /// - "TiRo" ↔ "TimesNewRoman" / "Times-Roman"
    /// - "ZaDb" ↔ "ZapfDingbats"
    pub fn find_font_or_fallback(&self, name: &str) -> Option<&BaFontMapEntry> {
        // Try exact match first
        if let Some(entry) = self.find_font(name) {
            return Some(entry);
        }

        // Try aliases
        let aliases = match name {
            "Helv" | "Helvetica" => &["Helv", "Helvetica", "Helvetica-Bold", "Arial"][..],
            "Cour" | "Courier" => &["Cour", "Courier", "Courier-Bold"][..],
            "TiRo" | "TimesNewRoman" | "Times-Roman" => {
                &["TiRo", "TimesNewRoman", "Times-Roman", "Times"][..]
            }
            "ZaDb" | "ZapfDingbats" => &["ZaDb", "ZapfDingbats"][..],
            "Symb" | "Symbol" => &["Symb", "Symbol"][..],
            _ => &[][..],
        };

        for alias in aliases {
            if let Some(entry) = self.find_font(alias) {
                return Some(entry);
            }
        }

        None
    }
}

/// Parse the font name and size from a `/DA` string.
///
/// DA strings look like: `"0 g /Helv 12 Tf"` or `"/Cour 10 Tf 0 0 0 rg"`
pub fn parse_default_appearance_font(da: &str) -> (Option<String>, f32) {
    let mut font_name: Option<String> = None;
    let mut font_size = 0.0_f32;
    let mut last_number: Option<f32> = None;

    for token in da.split_whitespace() {
        if let Some(stripped) = token.strip_prefix('/') {
            font_name = Some(stripped.to_string());
            last_number = None;
        } else if token == "Tf" {
            if let Some(size) = last_number {
                font_size = size;
            }
            last_number = None;
        } else if let Ok(n) = token.parse::<f32>() {
            last_number = Some(n);
        } else {
            last_number = None;
        }
    }

    (font_name, font_size)
}

/// Detect charset from a font dictionary's encoding or flags.
fn extract_charset(obj: &Object) -> u8 {
    let dict = match obj {
        Object::Dictionary(d) => d,
        Object::Stream { dict, .. } => dict,
        _ => return 0,
    };

    // Check /Encoding for Symbol or ZapfDingbats
    if let Some(enc_obj) = dict.get(&Name::encoding()) {
        if let Some(name) = enc_obj.as_name() {
            let s = name.as_str();
            if s.contains("Symbol") {
                return 2; // Symbol charset
            }
        }
    }

    // Check /BaseFont for known symbol fonts
    if let Some(bf_obj) = dict.get(&Name::base_font()) {
        if let Some(name) = bf_obj.as_name() {
            let s = name.as_str();
            if s.contains("Symbol") {
                return 2;
            }
            if s.contains("ZapfDingbats") {
                return 2;
            }
        }
    }

    0 // ANSI default
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_da_font_basic() {
        let (name, size) = parse_default_appearance_font("0 g /Helv 12 Tf");
        assert_eq!(name.as_deref(), Some("Helv"));
        assert_eq!(size, 12.0);
    }

    #[test]
    fn test_parse_da_font_courier() {
        let (name, size) = parse_default_appearance_font("/Cour 10 Tf 0 0 0 rg");
        assert_eq!(name.as_deref(), Some("Cour"));
        assert_eq!(size, 10.0);
    }

    #[test]
    fn test_parse_da_no_font() {
        let (name, size) = parse_default_appearance_font("0 g");
        assert!(name.is_none());
        assert_eq!(size, 0.0);
    }

    #[test]
    fn test_parse_da_empty() {
        let (name, size) = parse_default_appearance_font("");
        assert!(name.is_none());
        assert_eq!(size, 0.0);
    }

    #[test]
    fn test_parse_da_zero_size() {
        let (name, size) = parse_default_appearance_font("/Helv 0 Tf");
        assert_eq!(name.as_deref(), Some("Helv"));
        assert_eq!(size, 0.0);
    }

    fn build_store() -> ObjectStore<Vec<u8>> {
        let pdf = build_minimal_pdf();
        ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap()
    }

    fn build_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let obj1_offset = pdf.len();
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let obj2_offset = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
        let xref_offset = pdf.len();
        pdf.extend_from_slice(b"xref\n0 3\n");
        pdf.extend_from_slice(b"0000000000 65535 f \r\n");
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj1_offset).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj2_offset).as_bytes());
        pdf.extend_from_slice(b"trailer\n<< /Size 3 /Root 1 0 R >>\n");
        pdf.extend_from_slice(format!("startxref\n{}\n%%EOF", xref_offset).as_bytes());
        pdf
    }

    #[test]
    fn test_empty_font_map() {
        let store = build_store();
        let map = BaFontMap::from_resources(None, None, &store);
        assert_eq!(map.font_count(), 0);
        assert!(map.default_font_name().is_none());
        assert_eq!(map.default_font_size(), 0.0);
    }

    #[test]
    fn test_font_map_with_dr() {
        let store = build_store();

        let mut font_dict = HashMap::new();
        // Simple font entry
        let mut helv_dict = HashMap::new();
        helv_dict.insert(Name::base_font(), Object::Name(Name::from("Helvetica")));
        font_dict.insert(Name::from("Helv"), Object::Dictionary(helv_dict));

        let mut cour_dict = HashMap::new();
        cour_dict.insert(Name::base_font(), Object::Name(Name::from("Courier")));
        font_dict.insert(Name::from("Cour"), Object::Dictionary(cour_dict));

        let map = BaFontMap::from_resources(Some(&font_dict), Some("/Helv 12 Tf"), &store);
        assert_eq!(map.font_count(), 2);
        assert_eq!(map.default_font_name(), Some("Helv"));
        assert_eq!(map.default_font_size(), 12.0);
    }

    #[test]
    fn test_font_map_find_font() {
        let store = build_store();

        let mut font_dict = HashMap::new();
        let helv_dict = HashMap::new();
        font_dict.insert(Name::from("Helv"), Object::Dictionary(helv_dict));

        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        assert!(map.find_font("Helv").is_some());
        assert!(map.find_font("Missing").is_none());
    }

    #[test]
    fn test_font_map_standard_fonts() {
        let store = build_store();

        let standard_names = ["Helv", "Cour", "TiRo", "ZaDb"];
        let mut font_dict = HashMap::new();
        for name in &standard_names {
            font_dict.insert(Name::from(*name), Object::Dictionary(HashMap::new()));
        }

        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        assert_eq!(map.font_count(), 4);
        for (i, name) in standard_names.iter().enumerate() {
            assert_eq!(map.font_name(i).is_some(), true);
            // Entries may be in any order since HashMap doesn't preserve order
            assert!(map.find_font(name).is_some());
        }
    }

    #[test]
    fn test_font_map_symbol_charset() {
        let store = build_store();

        let mut font_dict = HashMap::new();
        let mut zadb_dict = HashMap::new();
        zadb_dict.insert(Name::base_font(), Object::Name(Name::from("ZapfDingbats")));
        font_dict.insert(Name::from("ZaDb"), Object::Dictionary(zadb_dict));

        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        let entry = map.find_font("ZaDb").unwrap();
        assert_eq!(entry.charset, 2); // Symbol
    }

    #[test]
    fn test_get_font_name_out_of_bounds() {
        let store = build_store();
        let map = BaFontMap::from_resources(None, None, &store);
        assert!(map.font_name(0).is_none());
        assert!(map.charset(0).is_none());
    }

    #[test]
    fn test_find_font_or_fallback_exact() {
        let store = build_store();
        let mut font_dict = HashMap::new();
        font_dict.insert(Name::from("Helv"), Object::Dictionary(HashMap::new()));
        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        assert!(map.find_font_or_fallback("Helv").is_some());
    }

    #[test]
    fn test_find_font_or_fallback_alias() {
        let store = build_store();
        let mut font_dict = HashMap::new();
        font_dict.insert(Name::from("Helv"), Object::Dictionary(HashMap::new()));
        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        // Search for "Helvetica" should find "Helv"
        assert!(map.find_font_or_fallback("Helvetica").is_some());
        assert_eq!(
            map.find_font_or_fallback("Helvetica").unwrap().font_name,
            "Helv"
        );
    }

    #[test]
    fn test_find_font_or_fallback_no_match() {
        let store = build_store();
        let mut font_dict = HashMap::new();
        font_dict.insert(Name::from("Helv"), Object::Dictionary(HashMap::new()));
        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        assert!(map.find_font_or_fallback("UnknownFont").is_none());
    }

    #[test]
    fn test_find_font_or_fallback_zadb() {
        let store = build_store();
        let mut font_dict = HashMap::new();
        font_dict.insert(Name::from("ZaDb"), Object::Dictionary(HashMap::new()));
        let map = BaFontMap::from_resources(Some(&font_dict), None, &store);
        assert!(map.find_font_or_fallback("ZapfDingbats").is_some());
    }

    /// Upstream: TEST_F(BAFontMapTest, DefaultFont)
    ///
    /// Without any font resources, the font map should still parse the /DA
    /// string and extract the font name and size. The upstream test verifies
    /// that CPDF_BAFontMap generates a default Helvetica font; here we verify
    /// that from_resources correctly parses the DA string even with no /DR fonts.
    #[test]
    fn test_ba_font_map_default_font() {
        let store = build_store();

        // No /DR font dictionary, only a /DA string referencing /F1
        let map = BaFontMap::from_resources(None, Some("0 0 0 rg /F1 12 Tf"), &store);

        // No font entries from /DR
        assert_eq!(map.font_count(), 0);

        // DA string is still parsed: font name = "F1", size = 12
        assert_eq!(map.default_font_name(), Some("F1"));
        assert_eq!(map.default_font_size(), 12.0);
    }

    /// Upstream: TEST_F(BAFontMapTest, Bug853238)
    ///
    /// When the AcroForm /DR has a font entry matching the /DA font name,
    /// the font map should include that entry. The upstream test verifies
    /// that CPDF_BAFontMap resolves F1 as Times-Roman from the /DR dictionary.
    #[test]
    fn test_ba_font_map_bug_853238() {
        let store = build_store();

        // Build /DR → /Font → /F1 → { /Type /Font, /Subtype /Type1, /BaseFont /Times-Roman }
        let mut f1_dict = HashMap::new();
        f1_dict.insert(Name::r#type(), Object::Name(Name::from("Font")));
        f1_dict.insert(Name::subtype(), Object::Name(Name::from("Type1")));
        f1_dict.insert(Name::base_font(), Object::Name(Name::from("Times-Roman")));

        let mut font_dict = HashMap::new();
        font_dict.insert(Name::from("F1"), Object::Dictionary(f1_dict));

        let map = BaFontMap::from_resources(Some(&font_dict), Some("0 0 0 rg /F1 12 Tf"), &store);

        // Should have one font entry: F1
        assert_eq!(map.font_count(), 1);
        assert!(map.find_font("F1").is_some());

        // DA string parsed correctly
        assert_eq!(map.default_font_name(), Some("F1"));
        assert_eq!(map.default_font_size(), 12.0);

        // The font entry should have ANSI charset (Times-Roman is not Symbol)
        let entry = map.find_font("F1").unwrap();
        assert_eq!(entry.charset, 0);
    }
}