Skip to main content

pdfboss_render/
lib.rs

1//! Page rasterization for pdfboss: paths, fills, strokes, clipping, color
2//! spaces, images and glyph outlines, rendered to an RGBA8 pixmap and
3//! encodable as PNG.
4//!
5//! Glyph painting is staged behind [`GlyphPainting`] tiers: embedded
6//! TrueType only, then every embedded font program (TrueType, CFF, Type1,
7//! Type3), and finally `Full`, which additionally substitutes a
8//! replacement face for a non-embedded simple font (see `crate::glyph` and
9//! `crate::substitute` for the loader and the request/provider plumbing).
10//! A substitute face comes from either a caller-supplied directory
11//! ([`SubstituteSource::Dir`]) or the compiled-in OFL Croscore set
12//! ([`SubstituteSource::Builtin`]), the latter gated behind this crate's
13//! `substitute-fonts` Cargo feature and queryable at runtime via
14//! [`builtin_fonts_available`]. Advance widths for a substituted
15//! standard-14 font additionally consult Adobe Core-14 AFM tables
16//! (`pdfboss_encoding::standard_14_width`) ahead of the substitute's own
17//! `hmtx`, behind only the PDF's own `/Widths`.
18//!
19//! v1 limitations: `/Symbol` and `/ZapfDingbats` have no license-clean
20//! substitute, so they stay unpainted at every tier rather than borrowing
21//! an unrelated face's glyphs; a "bold" *sans* substitute request is not
22//! visually distinct from regular weight (Arimo is a `[wght]` variable
23//! font, rendered at its Regular instance -- only italic varies, via a
24//! separate static face); and advancing *unpainted* non-embedded text at
25//! `AllEmbedded` via the AFM tables is deferred to a later plan.
26
27// The rasterizer modules are consumed by the content-stream executor; the
28// `dead_code` allowances below disappear once it is wired up.
29mod cff;
30#[allow(dead_code)]
31mod color;
32mod executor;
33mod glyph;
34mod image;
35#[allow(dead_code)]
36mod path;
37#[allow(dead_code)]
38mod raster;
39#[allow(dead_code)]
40mod stroke;
41#[allow(dead_code)]
42mod substitute;
43mod truetype;
44mod type1;
45mod type3;
46
47use std::path::{Path, PathBuf};
48
49use pdfboss_core::{Document, Error, Page, Result};
50
51/// An RGBA8 raster image with straight (non-premultiplied) alpha, row-major
52/// from the top-left.
53#[derive(Debug, Clone, PartialEq)]
54pub struct Pixmap {
55    pub width: u32,
56    pub height: u32,
57    /// Pixel data, `width * height * 4` bytes (RGBA per pixel).
58    pub data: Vec<u8>,
59}
60
61impl Pixmap {
62    /// Creates a fully transparent pixmap.
63    pub fn new(w: u32, h: u32) -> Pixmap {
64        Pixmap {
65            width: w,
66            height: h,
67            data: vec![0; w as usize * h as usize * 4],
68        }
69    }
70
71    /// Fills every pixel with `rgba`.
72    pub fn fill(&mut self, rgba: [u8; 4]) {
73        for px in self.data.chunks_exact_mut(4) {
74            px.copy_from_slice(&rgba);
75        }
76    }
77
78    /// Encodes the pixmap as a PNG image.
79    pub fn encode_png(&self) -> Result<Vec<u8>> {
80        fn err(e: png::EncodingError) -> Error {
81            Error::Other(format!("png encode: {e}"))
82        }
83        let mut out = Vec::new();
84        let mut enc = png::Encoder::new(&mut out, self.width, self.height);
85        enc.set_color(png::ColorType::Rgba);
86        enc.set_depth(png::BitDepth::Eight);
87        let mut writer = enc.write_header().map_err(err)?;
88        writer.write_image_data(&self.data).map_err(err)?;
89        writer.finish().map_err(err)?;
90        Ok(out)
91    }
92
93    /// Encodes the pixmap as PNG and writes it to `path`.
94    pub fn save_png(&self, path: impl AsRef<Path>) -> Result<()> {
95        std::fs::write(path, self.encode_png()?)?;
96        Ok(())
97    }
98}
99
100/// How aggressively the rasterizer turns text into filled outlines. Each tier is
101/// a strict superset of the previous one; the difference is only observable once
102/// the corresponding glyph loaders exist.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104pub enum GlyphPainting {
105    /// Only embedded TrueType (`glyf`) outlines — the cheapest tier.
106    EmbeddedTrueTypeOnly,
107    /// Every embedded program: TrueType, CFF, Type1 and Type3. No bundled assets.
108    #[default]
109    AllEmbedded,
110    /// Also substitute bundled or caller-provided faces for non-embedded fonts.
111    Full,
112}
113
114impl GlyphPainting {
115    /// Whether this tier paints every embedded program (CFF, Type1, Type3),
116    /// not just embedded TrueType.
117    pub fn paints_all_embedded(self) -> bool {
118        !matches!(self, GlyphPainting::EmbeddedTrueTypeOnly)
119    }
120}
121
122/// Where non-embedded glyph substitution (the `Full` [`GlyphPainting`] tier)
123/// draws replacement faces from. The default, `None`, substitutes nothing --
124/// `Full` behaves exactly like `AllEmbedded` until a caller opts in.
125#[derive(Clone, Debug, Default)]
126pub enum SubstituteSource {
127    /// No substitution: non-embedded fonts stay unpainted.
128    #[default]
129    None,
130    /// Compiled-in faces: the OFL Croscore set (Arimo/Tinos/Cousine,
131    /// metric-compatible with Helvetica/Times/Courier) bundled via
132    /// `include_bytes!` behind the `substitute-fonts` Cargo feature -- see
133    /// [`builtin_fonts_available`] and `crate::substitute::BuiltinProvider`.
134    /// Built without that feature, there are no compiled-in faces to hand
135    /// out: `Builtin` degrades to no provider at all, so `Full` behaves
136    /// exactly like `AllEmbedded` for non-embedded fonts, the same as
137    /// `SubstituteSource::None`.
138    Builtin,
139    /// Faces read from a directory at render time (e.g. an installed
140    /// `pdfboss-fonts` package), one file per style -- see
141    /// `substitute::face_filename`.
142    Dir(PathBuf),
143}
144
145/// Options controlling a single page render.
146#[derive(Clone, Debug, Default)]
147pub struct RenderOptions {
148    /// Which font programs the rasterizer will paint.
149    pub glyph_painting: GlyphPainting,
150    /// Where `Full`-tier substitution draws replacement faces from. Ignored
151    /// at every other tier.
152    pub substitutes: SubstituteSource,
153}
154
155/// Whether this binary was built with the `substitute-fonts` feature, i.e.
156/// whether `SubstituteSource::Builtin` has compiled-in faces to hand out.
157/// Callers (e.g. the CLI) use this to give an actionable message when `Full`
158/// is requested with no `--font-dir` and no compiled-in set, rather than
159/// silently rendering as if `Full` had never been asked for.
160pub fn builtin_fonts_available() -> bool {
161    cfg!(feature = "substitute-fonts")
162}
163
164/// Renders a page at `scale` onto a white background. The pixel size is
165/// `ceil(crop_w * scale) x ceil(crop_h * scale)` (after `/Rotate`), and the
166/// base transform maps the crop box to device space with a y-flip and the
167/// page rotation applied.
168///
169/// Rendering is lenient: content pdfboss cannot read is skipped rather than
170/// failing the render, so a page can come back blank without an error. Use
171/// [`render_page_reporting`] to find out what was dropped.
172pub fn render_page(doc: &Document, page: &Page, scale: f32) -> Result<Pixmap> {
173    render_page_with_options(doc, page, scale, &RenderOptions::default())
174}
175
176/// Renders a page like [`render_page`], honoring `opts` (currently the glyph
177/// painting tier). See [`render_page`] for the geometry contract and for
178/// what leniency means for the pixels you get back.
179pub fn render_page_with_options(
180    doc: &Document,
181    page: &Page,
182    scale: f32,
183    opts: &RenderOptions,
184) -> Result<Pixmap> {
185    executor::render_page_reporting(doc, page, scale, opts).map(|(pix, _)| pix)
186}
187
188/// Renders a page like [`render_page_with_options`], additionally returning
189/// a [`RenderReport`] describing any content that had to be dropped or
190/// approximated. Use this when a silently blank page would be misleading.
191pub fn render_page_reporting(
192    doc: &Document,
193    page: &Page,
194    scale: f32,
195    opts: &RenderOptions,
196) -> Result<(Pixmap, RenderReport)> {
197    executor::render_page_reporting(doc, page, scale, opts)
198}
199
200/// Upper bound on the distinct entries a [`RenderReport`] keeps. Repeats of
201/// the same kind and reason only raise an existing entry's count, so this
202/// bounds the report's memory for any page: a stream drawing the same
203/// undecodable image a million times costs one entry, and a stream inventing
204/// endlessly *different* failures stops growing the list here and counts the
205/// rest in [`RenderReport::unlisted`].
206const MAX_SKIPPED: usize = 64;
207
208/// Which piece of page content a render could not reproduce.
209#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
210#[non_exhaustive]
211pub enum SkippedKind {
212    /// The page's own content stream: nothing on the page was drawn.
213    PageContents,
214    /// An image XObject or an inline image.
215    Image,
216    /// A form XObject, and with it everything nested inside it.
217    Form,
218    /// A `Do` whose XObject resource is missing, is not a stream, or has no
219    /// subtype this renderer knows how to draw.
220    XObject,
221    /// A shading (`sh`), which this renderer does not paint.
222    Shading,
223    /// A pattern fill or stroke, painted as flat mid-gray instead of the
224    /// pattern's own content.
225    Pattern,
226    /// A mask that was ignored, so content the author masked out painted
227    /// solid: an image `/SMask` or `/Mask`, or an `/ExtGState` `/SMask`.
228    SoftMask,
229    /// A blend mode other than `Normal`, painted as `Normal`.
230    BlendMode,
231    /// An annotation appearance stream: annotations are not painted.
232    Annotation,
233}
234
235impl SkippedKind {
236    /// The noun this kind reads as in [`RenderReport::summary`] and
237    /// [`RenderReport::warnings`], pluralized for `n`.
238    fn noun(self, n: u64) -> &'static str {
239        let one = n == 1;
240        match self {
241            SkippedKind::PageContents if one => "content stream",
242            SkippedKind::PageContents => "content streams",
243            SkippedKind::Image if one => "image",
244            SkippedKind::Image => "images",
245            SkippedKind::Form if one => "form XObject",
246            SkippedKind::Form => "form XObjects",
247            SkippedKind::XObject if one => "XObject",
248            SkippedKind::XObject => "XObjects",
249            SkippedKind::Shading if one => "shading",
250            SkippedKind::Shading => "shadings",
251            SkippedKind::Pattern if one => "pattern",
252            SkippedKind::Pattern => "patterns",
253            SkippedKind::SoftMask if one => "mask",
254            SkippedKind::SoftMask => "masks",
255            SkippedKind::BlendMode if one => "blend mode",
256            SkippedKind::BlendMode => "blend modes",
257            SkippedKind::Annotation if one => "annotation",
258            SkippedKind::Annotation => "annotations",
259        }
260    }
261}
262
263/// Why a piece of page content was dropped or approximated during
264/// rasterization.
265///
266/// Rendering is lenient: content pdfboss cannot read is skipped so the rest
267/// of the page still rasterizes. This enum records *why*, so callers can
268/// tell an intentionally blank page from a page whose content pdfboss could
269/// not read.
270#[derive(Clone, Debug, PartialEq, Eq)]
271#[non_exhaustive]
272pub enum SkipReason {
273    /// The stream's `/Filter` chain names a filter pdfboss does not decode.
274    UnsupportedFilter(String),
275    /// Reading the stream failed, carrying the underlying message: a filter
276    /// that ran but gave up (corrupt data, size limit, ...), or a syntax
277    /// error in a content stream.
278    DecodeFailed(String),
279    /// Filters applied cleanly but the bytes could not be interpreted (bad
280    /// image dimensions, unparsable content stream, unsupported JPEG, ...).
281    Undecodable,
282    /// The stream held fewer samples than the image's dimensions and bit
283    /// depth demand; the missing region painted as zero samples.
284    Truncated,
285    /// A resource the operator names is absent, or is not the kind of object
286    /// the operator needs.
287    Missing,
288    /// pdfboss understands the construct but does not paint it yet, so it
289    /// was omitted or approximated.
290    Unsupported,
291    /// A nesting or size guard stopped the render at this point.
292    LimitExceeded,
293}
294
295impl std::fmt::Display for SkipReason {
296    /// The reason as the clause after the colon of a warning line, e.g.
297    /// `unsupported filter /JPXDecode`.
298    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
299        match self {
300            SkipReason::UnsupportedFilter(name) => write!(f, "unsupported filter /{name}"),
301            SkipReason::DecodeFailed(msg) => f.write_str(msg),
302            SkipReason::Undecodable => f.write_str("the data could not be interpreted"),
303            SkipReason::Truncated => f.write_str("sample data ended early; the rest painted blank"),
304            SkipReason::Missing => f.write_str("the resource is missing"),
305            SkipReason::Unsupported => f.write_str("not supported yet"),
306            SkipReason::LimitExceeded => f.write_str("a nesting limit stopped the render here"),
307        }
308    }
309}
310
311/// One kind of content dropped for one reason, with how often it happened.
312#[derive(Clone, Debug, PartialEq, Eq)]
313#[non_exhaustive]
314pub struct SkippedContent {
315    /// What was dropped.
316    pub kind: SkippedKind,
317    /// Why it was dropped.
318    pub reason: SkipReason,
319    /// How many times this exact kind/reason pair came up in the render.
320    pub count: u64,
321}
322
323/// What a page render could not reproduce faithfully: content dropped
324/// outright (an undecodable image, an unreadable form) and content painted
325/// as an approximation (a pattern fill as flat gray). Empty means every
326/// construct the render encountered was painted as the page describes it.
327///
328/// Two things are deliberately *not* reported, because they are configured
329/// behavior rather than a failure: text left unpainted by the requested
330/// [`GlyphPainting`] tier, and content clipped or transformed off the page.
331#[derive(Clone, Debug, Default, PartialEq, Eq)]
332#[non_exhaustive]
333pub struct RenderReport {
334    /// Distinct drops in the order first encountered, at most 64 entries
335    /// (see `count` for repeats and [`RenderReport::unlisted`] for the
336    /// overflow).
337    pub skipped: Vec<SkippedContent>,
338    /// Drops that arrived after `skipped` reached its 64-entry cap and so
339    /// are counted but not described.
340    pub unlisted: u64,
341}
342
343impl RenderReport {
344    /// Whether the page rasterized with nothing dropped or approximated.
345    pub fn is_empty(&self) -> bool {
346        self.skipped.is_empty() && self.unlisted == 0
347    }
348
349    /// A one-line human summary counting drops per kind, or `None` when
350    /// nothing was dropped: `"2 images, 1 shading skipped"`.
351    pub fn summary(&self) -> Option<String> {
352        if self.is_empty() {
353            return None;
354        }
355        let mut totals: Vec<(SkippedKind, u64)> = Vec::new();
356        for item in &self.skipped {
357            match totals.iter_mut().find(|(kind, _)| *kind == item.kind) {
358                Some((_, n)) => *n = n.saturating_add(item.count),
359                None => totals.push((item.kind, item.count)),
360            }
361        }
362        let mut parts: Vec<String> = totals
363            .iter()
364            .map(|(kind, n)| format!("{n} {}", kind.noun(*n)))
365            .collect();
366        if self.unlisted > 0 {
367            parts.push(format!("{} more", self.unlisted));
368        }
369        Some(format!("{} skipped", parts.join(", ")))
370    }
371
372    /// One human-readable line per distinct drop, for callers that warn
373    /// about them: `"1 image skipped: unsupported filter /JPXDecode"`.
374    pub fn warnings(&self) -> Vec<String> {
375        let mut out: Vec<String> = self
376            .skipped
377            .iter()
378            .map(|item| {
379                format!(
380                    "{} {} skipped: {}",
381                    item.count,
382                    item.kind.noun(item.count),
383                    item.reason
384                )
385            })
386            .collect();
387        if self.unlisted > 0 {
388            out.push(format!(
389                "{} further drops not described (report limit reached)",
390                self.unlisted
391            ));
392        }
393        out
394    }
395
396    /// Records one drop, merging it into an existing entry when the same
397    /// kind and reason already happened. Beyond [`MAX_SKIPPED`] distinct
398    /// entries the drop is only counted, so a page drawing endlessly varied
399    /// broken content cannot grow this report without bound.
400    pub(crate) fn record(&mut self, kind: SkippedKind, reason: SkipReason) {
401        if let Some(item) = self
402            .skipped
403            .iter_mut()
404            .find(|item| item.kind == kind && item.reason == reason)
405        {
406            item.count = item.count.saturating_add(1);
407            return;
408        }
409        if self.skipped.len() >= MAX_SKIPPED {
410            self.unlisted = self.unlisted.saturating_add(1);
411            return;
412        }
413        self.skipped.push(SkippedContent {
414            kind,
415            reason,
416            count: 1,
417        });
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn new_pixmap_is_transparent() {
427        let pix = Pixmap::new(3, 2);
428        assert_eq!(pix.width, 3);
429        assert_eq!(pix.height, 2);
430        assert_eq!(pix.data.len(), 24);
431        assert!(pix.data.iter().all(|&b| b == 0));
432    }
433
434    #[test]
435    fn fill_sets_every_pixel() {
436        let mut pix = Pixmap::new(2, 2);
437        pix.fill([1, 2, 3, 4]);
438        assert_eq!(pix.data, [1, 2, 3, 4].repeat(4));
439    }
440
441    #[test]
442    fn png_round_trip_preserves_pixels() {
443        let mut pix = Pixmap::new(3, 2);
444        for (i, b) in pix.data.iter_mut().enumerate() {
445            *b = (i * 11 % 256) as u8;
446        }
447        let bytes = pix.encode_png().expect("encode");
448        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
449
450        let decoder = png::Decoder::new(std::io::Cursor::new(&bytes));
451        let mut reader = decoder.read_info().expect("read_info");
452        let mut buf = vec![0u8; reader.output_buffer_size().expect("size")];
453        let info = reader.next_frame(&mut buf).expect("frame");
454        assert_eq!(info.width, 3);
455        assert_eq!(info.height, 2);
456        assert_eq!(info.color_type, png::ColorType::Rgba);
457        assert_eq!(info.bit_depth, png::BitDepth::Eight);
458        assert_eq!(&buf[..info.buffer_size()], &pix.data[..]);
459    }
460
461    #[test]
462    fn report_merges_repeats_and_counts_per_kind() {
463        let mut report = RenderReport::default();
464        assert!(report.is_empty());
465        report.record(SkippedKind::Image, SkipReason::Undecodable);
466        report.record(SkippedKind::Image, SkipReason::Undecodable);
467        report.record(
468            SkippedKind::Image,
469            SkipReason::UnsupportedFilter("JPXDecode".to_string()),
470        );
471        report.record(SkippedKind::Shading, SkipReason::Unsupported);
472
473        assert!(!report.is_empty());
474        assert_eq!(report.skipped.len(), 3, "same kind and reason merge");
475        assert_eq!(report.skipped[0].count, 2);
476        // The summary counts per kind, so the two image reasons add up.
477        assert_eq!(
478            report.summary().as_deref(),
479            Some("3 images, 1 shading skipped"),
480        );
481        assert_eq!(
482            report.warnings(),
483            vec![
484                "2 images skipped: the data could not be interpreted".to_string(),
485                "1 image skipped: unsupported filter /JPXDecode".to_string(),
486                "1 shading skipped: not supported yet".to_string(),
487            ],
488        );
489    }
490
491    #[test]
492    fn report_stops_listing_at_the_cap_but_keeps_counting() {
493        let mut report = RenderReport::default();
494        for i in 0..MAX_SKIPPED + 5 {
495            report.record(SkippedKind::Image, SkipReason::DecodeFailed(i.to_string()));
496        }
497        assert_eq!(report.skipped.len(), MAX_SKIPPED);
498        assert_eq!(report.unlisted, 5);
499        assert_eq!(
500            report.summary().as_deref(),
501            Some("64 images, 5 more skipped"),
502        );
503    }
504
505    #[test]
506    fn save_png_writes_decodable_file() {
507        let mut pix = Pixmap::new(4, 4);
508        pix.fill([10, 20, 30, 255]);
509        let dir = std::env::temp_dir().join("pdfboss-render-test");
510        std::fs::create_dir_all(&dir).unwrap();
511        let path = dir.join("pix.png");
512        pix.save_png(&path).expect("save");
513        let bytes = std::fs::read(&path).unwrap();
514        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
515        std::fs::remove_file(&path).ok();
516    }
517}