pdfboss-render 0.11.0

Page rasterization to RGBA pixmaps and PNG for pdfboss
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
464
465
466
467
468
469
470
//! Non-embedded font substitution: deriving a face request from a PDF font
//! dictionary (ISO 32000-1 Table 121, `/FontDescriptor /Flags`) and mapping
//! that request onto a replacement face, either compiled in or read from a
//! directory at render time.
//!
//! `GlyphFont::load` (`glyph.rs`) consults [`FaceRequest`] and
//! [`SubstituteProvider`] as the last resort for a SIMPLE font (`/TrueType`,
//! `/Type1`, `/MMType1`) with no embedded program of its own -- but only at
//! the `Full` [`crate::GlyphPainting`] tier, and only when
//! [`crate::RenderOptions::substitutes`] actually names a source; `Full`
//! with `SubstituteSource::None` behaves exactly like `AllEmbedded`. Two
//! providers exist: [`DirProvider`] reads faces from a caller-supplied
//! directory at render time (works in any build), and [`BuiltinProvider`]
//! hands out faces bundled into the binary via `include_bytes!`, compiled
//! in only behind the `substitute-fonts` Cargo feature (see
//! [`crate::builtin_fonts_available`]) so the default build stays free of
//! the ~4 MB of font data.
//!
//! The bundled set is the OFL 1.1 Croscore family -- Arimo (sans), Tinos
//! (serif) and Cousine (mono), metric-compatible substitutes for
//! Helvetica, Times and Courier respectively (licensing: `assets/fonts/
//! OFL.txt` and `NOTICE`). Advance widths for a recognized standard-14
//! `/BaseFont` prefer the Adobe Core-14 AFM tables
//! (`pdfboss_encoding::standard_14_width`) over the substitute's own
//! `hmtx`, behind only the PDF's own `/Widths` -- see `glyph.rs`'s
//! `GlyphFont::advance` for the full three-tier order.
//!
//! v1 limitations, none of which are guessed around: `FaceRequest::
//! from_font_dict` returns `None` for `/Symbol` and `/ZapfDingbats`, which
//! have no license-clean substitute in the bundled set, so that text stays
//! unpainted at every tier rather than borrowing an unrelated face's
//! glyphs; a "bold" *sans* request is not visually distinct from the
//! regular weight, because Arimo ships only as a `[wght]` variable font
//! and is rendered at its default (Regular) instance -- only italic varies,
//! via a separate static face; and advancing *unpainted* non-embedded text
//! at `AllEmbedded` (giving that tier the AFM-14 benefit even though it
//! paints nothing) is deferred -- the AFM tables exist and feed the
//! `Full`-tier substitute advance now, not any earlier tier.

use pdfboss_core::{AsyncObjectSource, Dict};

/// The three families a substitute request maps a non-embedded font to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Family {
    Serif,
    Sans,
    Mono,
}

/// A style request derived from a font's `/BaseFont` name and
/// `/FontDescriptor /Flags`, used to pick a substitute face.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FaceRequest {
    pub family: Family,
    pub bold: bool,
    pub italic: bool,
}

/// A source of substitute face programs, keyed by [`FaceRequest`].
///
/// Providers must be shareable across threads. A provider is held by the
/// executor for the whole of a page render and consulted whenever a
/// non-embedded font needs a face, so it travels inside the render future and
/// has to survive being handed to a thread pool. Stating the requirement as a
/// supertrait is what keeps it a single-point contract: `&dyn
/// SubstituteProvider` and `Box<dyn SubstituteProvider>` then carry it
/// implicitly, and no parameter or field has to spell it out.
pub(crate) trait SubstituteProvider: Send + Sync {
    /// Returns the face's raw font program bytes, or `None` if this provider
    /// has no face for `req` (a missing directory or file, say).
    fn face(&self, req: &FaceRequest) -> Option<Vec<u8>>;
}

/// `/FontDescriptor /Flags` bits consulted here (ISO 32000-1 Table 121).
const FLAG_FIXED_PITCH: i64 = 0x1;
const FLAG_SERIF: i64 = 0x2;
const FLAG_ITALIC: i64 = 0x40;
const FLAG_FORCE_BOLD: i64 = 0x40000;

/// Strips a subset prefix (`ABCDEF+Name` -> `Name`, ISO 32000-1 9.6.4): six
/// uppercase ASCII letters followed by `+`. Names that don't match this exact
/// shape (wrong length, non-uppercase, no `+`) pass through unchanged.
fn strip_subset_prefix(name: &str) -> &str {
    let bytes = name.as_bytes();
    if bytes.len() > 7 && bytes[6] == b'+' && bytes[..6].iter().all(u8::is_ascii_uppercase) {
        &name[7..]
    } else {
        name
    }
}

impl FaceRequest {
    /// Derives a request from `/BaseFont` (subset prefix stripped, matched
    /// case-insensitively) and the font's `FontDescriptor /Flags`. `None` for
    /// Symbol/ZapfDingbats, which have no license-clean substitute in v1.
    pub(crate) async fn from_font_dict<S: AsyncObjectSource>(
        src: &S,
        font: &Dict,
    ) -> Option<FaceRequest> {
        let base = font
            .get_name("BaseFont")
            .map(|n| n.0.as_str())
            .unwrap_or("");
        let stripped = strip_subset_prefix(base);
        let lower = stripped.to_lowercase();
        // Prefix match, not exact equality: vendor variants like `SymbolMT`
        // or `ZapfDingbatsITC` are still Symbol/ZapfDingbats under the hood
        // and have the same no-license-clean-substitute problem as the bare
        // names -- an exact match would let them fall through to an
        // unrelated Arimo/Tinos/Cousine substitute instead of staying
        // unpainted.
        if lower.starts_with("symbol") || lower.starts_with("zapfdingbats") {
            return None;
        }

        let descriptor = match font.get("FontDescriptor") {
            Some(o) => src.resolve(o).await.ok().and_then(|o| o.as_dict().cloned()),
            None => None,
        };
        let flags = descriptor.and_then(|fd| fd.get_int("Flags")).unwrap_or(0);

        let family = if flags & FLAG_FIXED_PITCH != 0
            || lower.contains("courier")
            || lower.contains("mono")
            || lower.contains("consol")
        {
            Family::Mono
        } else if flags & FLAG_SERIF != 0
            || lower.contains("times")
            || lower.contains("georgia")
            || lower.contains("serif")
            || lower.contains("roman")
            || lower.contains("minion")
        {
            Family::Serif
        } else {
            Family::Sans
        };

        let bold = flags & FLAG_FORCE_BOLD != 0 || lower.contains("bold");
        let italic =
            flags & FLAG_ITALIC != 0 || lower.contains("italic") || lower.contains("oblique");

        Some(FaceRequest {
            family,
            bold,
            italic,
        })
    }
}

/// The bundled-substitute filename for `req`: Arimo (sans), Tinos (serif) or
/// Cousine (mono) -- the metric-compatible Liberation-family faces used as
/// the standard substitute set. Sans only varies by italic (weight rides the
/// variable-font axis, `[wght]`); serif and mono pick one of the four static
/// styles.
pub(crate) fn face_filename(req: &FaceRequest) -> &'static str {
    match req.family {
        Family::Sans => {
            if req.italic {
                "Arimo-Italic[wght].ttf"
            } else {
                "Arimo[wght].ttf"
            }
        }
        Family::Serif => match (req.bold, req.italic) {
            (false, false) => "Tinos-Regular.ttf",
            (true, false) => "Tinos-Bold.ttf",
            (false, true) => "Tinos-Italic.ttf",
            (true, true) => "Tinos-BoldItalic.ttf",
        },
        Family::Mono => match (req.bold, req.italic) {
            (false, false) => "Cousine-Regular.ttf",
            (true, false) => "Cousine-Bold.ttf",
            (false, true) => "Cousine-Italic.ttf",
            (true, true) => "Cousine-BoldItalic.ttf",
        },
    }
}

/// Reads substitute faces from a runtime directory (e.g. an installed
/// `pdfboss-fonts` package), one file per [`face_filename`].
pub(crate) struct DirProvider {
    pub dir: std::path::PathBuf,
}

impl SubstituteProvider for DirProvider {
    fn face(&self, req: &FaceRequest) -> Option<Vec<u8>> {
        std::fs::read(self.dir.join(face_filename(req))).ok()
    }
}

/// Compiled-in substitute faces: the OFL Croscore set (Arimo/Tinos/Cousine,
/// metric-compatible with Helvetica/Times/Courier) bundled via
/// `include_bytes!` under `assets/fonts/`. Gated behind the `substitute-fonts`
/// feature so the default build stays free of the ~4 MB of font data; see
/// `assets/fonts/NOTICE` and `OFL.txt` for licensing.
#[cfg(feature = "substitute-fonts")]
pub(crate) struct BuiltinProvider;

#[cfg(feature = "substitute-fonts")]
impl SubstituteProvider for BuiltinProvider {
    fn face(&self, req: &FaceRequest) -> Option<Vec<u8>> {
        let bytes: &[u8] = match face_filename(req) {
            "Arimo[wght].ttf" => include_bytes!("../assets/fonts/Arimo[wght].ttf"),
            "Arimo-Italic[wght].ttf" => include_bytes!("../assets/fonts/Arimo-Italic[wght].ttf"),
            "Tinos-Regular.ttf" => include_bytes!("../assets/fonts/Tinos-Regular.ttf"),
            "Tinos-Bold.ttf" => include_bytes!("../assets/fonts/Tinos-Bold.ttf"),
            "Tinos-Italic.ttf" => include_bytes!("../assets/fonts/Tinos-Italic.ttf"),
            "Tinos-BoldItalic.ttf" => include_bytes!("../assets/fonts/Tinos-BoldItalic.ttf"),
            "Cousine-Regular.ttf" => include_bytes!("../assets/fonts/Cousine-Regular.ttf"),
            "Cousine-Bold.ttf" => include_bytes!("../assets/fonts/Cousine-Bold.ttf"),
            "Cousine-Italic.ttf" => include_bytes!("../assets/fonts/Cousine-Italic.ttf"),
            "Cousine-BoldItalic.ttf" => include_bytes!("../assets/fonts/Cousine-BoldItalic.ttf"),
            _ => return None,
        };
        Some(bytes.to_vec())
    }
}

#[cfg(test)]
mod tests {
    use pdfboss_core::{Document, ObjRef, Object};
    use pdfboss_testkit::PdfBuilder;

    use super::*;

    /// A provider is consulted from inside the render future, so the trait
    /// object it is reached through has to be shareable across threads. Both
    /// implementors satisfy this already; asserting it on the `dyn` form is
    /// what turns that coincidence into a contract a future implementor
    /// cannot quietly break.
    #[test]
    fn providers_are_shareable_across_threads() {
        fn assert_send_sync<T: Send + Sync + ?Sized>() {}
        assert_send_sync::<dyn SubstituteProvider>();
        assert_send_sync::<Box<dyn SubstituteProvider>>();
        assert_send_sync::<DirProvider>();
    }

    /// Builds a minimal one-page PDF with a simple font (object 5, the given
    /// `/BaseFont`) whose `FontDescriptor` (object 6) carries `flags`, and
    /// returns `FaceRequest::from_font_dict`'s result for that font dict.
    fn req_for(base: &str, flags: i64) -> Option<FaceRequest> {
        let mut b = PdfBuilder::new();
        b.object(1, "<< /Type /Catalog /Pages 2 0 R >>");
        b.object(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
        b.object(
            3,
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] \
             /Resources << /Font << /F0 5 0 R >> >> /Contents 4 0 R >>",
        );
        b.stream(4, "", b"");
        b.object(
            5,
            &format!(
                "<< /Type /Font /Subtype /TrueType /BaseFont /{base} \
                 /FontDescriptor 6 0 R >>"
            ),
        );
        b.object(
            6,
            &format!("<< /Type /FontDescriptor /FontName /{base} /Flags {flags} >>"),
        );
        let bytes = b.build(1);
        let doc = Document::load(bytes).expect("load");
        let font = doc
            .resolve(&Object::Ref(ObjRef { num: 5, gen: 0 }))
            .expect("resolve font")
            .as_dict()
            .cloned()
            .expect("font is a dict");
        pdfboss_core::block_on(FaceRequest::from_font_dict(
            &pdfboss_core::Immediate(&doc),
            &font,
        ))
    }

    #[test]
    fn times_bold_is_serif_and_bold() {
        let req = req_for("Times-Bold", 0).expect("some request");
        assert_eq!(req.family, Family::Serif);
        assert!(req.bold);
        assert!(!req.italic);
    }

    #[test]
    fn courier_is_mono() {
        let req = req_for("Courier", 0).expect("some request");
        assert_eq!(req.family, Family::Mono);
        assert!(!req.bold);
        assert!(!req.italic);
    }

    #[test]
    fn helvetica_oblique_is_sans_and_italic() {
        let req = req_for("Helvetica-Oblique", 0).expect("some request");
        assert_eq!(req.family, Family::Sans);
        assert!(!req.bold);
        assert!(req.italic);
    }

    #[test]
    fn subset_prefix_stripped_before_matching_and_serif_flag_wins() {
        // "Garamond" matches no name keyword; only the /Flags Serif bit (0x2)
        // makes this Serif. The ABCDEF+ subset prefix must not leak into the
        // match (e.g. by defeating the lowercase name check).
        let req = req_for("ABCDEF+Garamond", 0x2).expect("some request");
        assert_eq!(req.family, Family::Serif);
    }

    #[test]
    fn symbol_and_zapfdingbats_have_no_substitute() {
        assert_eq!(req_for("Symbol", 0), None);
        assert_eq!(req_for("ZapfDingbats", 0), None);
    }

    #[test]
    fn symbol_and_zapfdingbats_vendor_variants_have_no_substitute() {
        // Vendor-suffixed variants (e.g. Windows' "SymbolMT", ITC's
        // "ZapfDingbatsITC") are still Symbol/ZapfDingbats under the hood --
        // an exact-equality match would miss these and hand back an
        // unrelated Arimo/Tinos/Cousine substitute instead of leaving the
        // text unpainted.
        assert_eq!(req_for("SymbolMT", 0), None);
        assert_eq!(req_for("ZapfDingbatsITC", 0), None);
    }

    #[test]
    fn force_bold_flag_without_name_hint_is_bold() {
        let req = req_for("SomeFace", 0x40000).expect("some request");
        assert!(req.bold);
    }

    #[test]
    fn italic_flag_without_name_hint_is_italic() {
        let req = req_for("SomeFace", 0x40).expect("some request");
        assert!(req.italic);
    }

    #[test]
    fn fixed_pitch_flag_without_name_hint_is_mono() {
        let req = req_for("SomeFace", 0x1).expect("some request");
        assert_eq!(req.family, Family::Mono);
    }

    fn req(family: Family, bold: bool, italic: bool) -> FaceRequest {
        FaceRequest {
            family,
            bold,
            italic,
        }
    }

    #[test]
    fn face_filename_sans_ignores_bold_varies_by_italic() {
        assert_eq!(
            face_filename(&req(Family::Sans, false, false)),
            "Arimo[wght].ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Sans, true, false)),
            "Arimo[wght].ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Sans, false, true)),
            "Arimo-Italic[wght].ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Sans, true, true)),
            "Arimo-Italic[wght].ttf"
        );
    }

    #[test]
    fn face_filename_serif_every_style() {
        assert_eq!(
            face_filename(&req(Family::Serif, false, false)),
            "Tinos-Regular.ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Serif, true, false)),
            "Tinos-Bold.ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Serif, false, true)),
            "Tinos-Italic.ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Serif, true, true)),
            "Tinos-BoldItalic.ttf"
        );
    }

    #[test]
    fn face_filename_mono_every_style() {
        assert_eq!(
            face_filename(&req(Family::Mono, false, false)),
            "Cousine-Regular.ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Mono, true, false)),
            "Cousine-Bold.ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Mono, false, true)),
            "Cousine-Italic.ttf"
        );
        assert_eq!(
            face_filename(&req(Family::Mono, true, true)),
            "Cousine-BoldItalic.ttf"
        );
    }

    #[test]
    fn dir_provider_reads_matching_file() {
        let dir = std::env::temp_dir().join(format!(
            "pdfboss-substitute-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let r = req(Family::Serif, true, false);
        let filename = face_filename(&r);
        std::fs::write(dir.join(filename), b"fake face bytes").expect("write fixture face");

        let provider = DirProvider { dir: dir.clone() };
        assert_eq!(provider.face(&r), Some(b"fake face bytes".to_vec()));

        // A style with no file on disk yields None, not a panic.
        let missing = req(Family::Mono, false, true);
        assert_eq!(provider.face(&missing), None);

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn dir_provider_missing_dir_yields_none() {
        let provider = DirProvider {
            dir: std::path::PathBuf::from("/no/such/pdfboss-substitute-dir"),
        };
        assert_eq!(provider.face(&req(Family::Sans, false, false)), None);
    }

    /// Every bundled face (all `Family` x bold x italic combinations) is a
    /// `glyf`-based sfnt with a `cmap` that maps 'A' to a nonempty outline --
    /// a parse-level smoke test for the compiled-in font bytes themselves,
    /// independent of the request-derivation logic tested above.
    #[cfg(feature = "substitute-fonts")]
    #[test]
    fn every_builtin_face_parses_and_renders_a() {
        let p = BuiltinProvider;
        let families = [Family::Serif, Family::Sans, Family::Mono];
        let bools = [false, true];
        for family in families {
            for bold in bools {
                for italic in bools {
                    let r = req(family, bold, italic);
                    let bytes = p.face(&r).expect("builtin face present");
                    let tt = crate::truetype::TrueType::parse(bytes).expect("glyf sfnt");
                    let g = tt.gid_for_unicode('A' as u32).expect("cmap has A");
                    assert!(!tt.glyph_path(g).is_empty(), "renders A for {r:?}");
                }
            }
        }
    }
}