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::{AsyncObjectSource, 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/// Renders a page like [`render_page_reporting`] against any object source,
201/// awaiting whatever I/O the source needs — this is the asynchronous entry
202/// point, and the synchronous ones above are this implementation over
203/// `pdfboss_core::Immediate`, so the two APIs cannot render differently.
204///
205/// The source is taken by value and the page by reference, which is the
206/// combination a consumer needs to spawn the result: the future is `Send`
207/// over a source that is `Send + Sync`, and `'static` as long as the borrow
208/// of `page` is created inside the consumer's own `async move` block, which
209/// owns the page. See `pdfboss_core::source`'s "Signing a shared algorithm".
210pub async fn render_page_reporting_with<S: AsyncObjectSource>(
211    src: S,
212    page: &Page,
213    scale: f32,
214    opts: &RenderOptions,
215) -> Result<(Pixmap, RenderReport)> {
216    executor::render_page_reporting_with(src, page, scale, opts).await
217}
218
219/// Upper bound on the distinct entries a [`RenderReport`] keeps. Repeats of
220/// the same kind and reason only raise an existing entry's count, so this
221/// bounds the report's memory for any page: a stream drawing the same
222/// undecodable image a million times costs one entry, and a stream inventing
223/// endlessly *different* failures stops growing the list here and counts the
224/// rest in [`RenderReport::unlisted`].
225const MAX_SKIPPED: usize = 64;
226
227/// Which piece of page content a render could not reproduce.
228#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
229#[non_exhaustive]
230pub enum SkippedKind {
231    /// The page's own content stream: nothing on the page was drawn.
232    PageContents,
233    /// An image XObject or an inline image.
234    Image,
235    /// A form XObject, and with it everything nested inside it.
236    Form,
237    /// A `Do` whose XObject resource is missing, is not a stream, or has no
238    /// subtype this renderer knows how to draw.
239    XObject,
240    /// A shading (`sh`), which this renderer does not paint.
241    Shading,
242    /// A pattern fill or stroke, painted as flat mid-gray instead of the
243    /// pattern's own content.
244    Pattern,
245    /// A mask that was ignored, so content the author masked out painted
246    /// solid: an image `/SMask` or `/Mask`, or an `/ExtGState` `/SMask`.
247    SoftMask,
248    /// A blend mode other than `Normal`, painted as `Normal`.
249    BlendMode,
250    /// An annotation appearance stream: annotations are not painted.
251    Annotation,
252    /// A character code a *loaded* font has no glyph for: the code advanced
253    /// the text position but painted nothing. A single-byte code 0x20 is
254    /// exempt — a space paints nothing whether or not the font maps it —
255    /// while a two-byte 0x20 is a real CID and is reported. Text whose font
256    /// never loaded at all (the [`GlyphPainting`] tier, or a load failure)
257    /// is configured behavior and stays unreported.
258    Glyph,
259}
260
261impl SkippedKind {
262    /// The noun this kind reads as in [`RenderReport::summary`] and
263    /// [`RenderReport::warnings`], pluralized for `n`.
264    fn noun(self, n: u64) -> &'static str {
265        let one = n == 1;
266        match self {
267            SkippedKind::PageContents if one => "content stream",
268            SkippedKind::PageContents => "content streams",
269            SkippedKind::Image if one => "image",
270            SkippedKind::Image => "images",
271            SkippedKind::Form if one => "form XObject",
272            SkippedKind::Form => "form XObjects",
273            SkippedKind::XObject if one => "XObject",
274            SkippedKind::XObject => "XObjects",
275            SkippedKind::Shading if one => "shading",
276            SkippedKind::Shading => "shadings",
277            SkippedKind::Pattern if one => "pattern",
278            SkippedKind::Pattern => "patterns",
279            SkippedKind::SoftMask if one => "mask",
280            SkippedKind::SoftMask => "masks",
281            SkippedKind::BlendMode if one => "blend mode",
282            SkippedKind::BlendMode => "blend modes",
283            SkippedKind::Annotation if one => "annotation",
284            SkippedKind::Annotation => "annotations",
285            SkippedKind::Glyph if one => "glyph",
286            SkippedKind::Glyph => "glyphs",
287        }
288    }
289}
290
291/// Why a piece of page content was dropped or approximated during
292/// rasterization.
293///
294/// Rendering is lenient: content pdfboss cannot read is skipped so the rest
295/// of the page still rasterizes. This enum records *why*, so callers can
296/// tell an intentionally blank page from a page whose content pdfboss could
297/// not read.
298#[derive(Clone, Debug, PartialEq, Eq)]
299#[non_exhaustive]
300pub enum SkipReason {
301    /// The stream's `/Filter` chain names a filter pdfboss does not decode.
302    UnsupportedFilter(String),
303    /// Reading the stream failed, carrying the underlying message: a filter
304    /// that ran but gave up (corrupt data, size limit, ...), or a syntax
305    /// error in a content stream.
306    DecodeFailed(String),
307    /// Filters applied cleanly but the bytes could not be interpreted (bad
308    /// image dimensions, unparsable content stream, unsupported JPEG, ...).
309    Undecodable,
310    /// The stream held fewer samples than the image's dimensions and bit
311    /// depth demand; the missing region painted as zero samples.
312    Truncated,
313    /// A resource the operator names is absent, or is not the kind of object
314    /// the operator needs.
315    Missing,
316    /// pdfboss understands the construct but does not paint it yet, so it
317    /// was omitted or approximated.
318    Unsupported,
319    /// A nesting or size guard stopped the render at this point.
320    LimitExceeded,
321    /// A loaded font has no glyph for a character code the page draws, so
322    /// the code advanced the text position without painting. One value per
323    /// distinct `(font, code)` pair, so the report counts occurrences
324    /// instead of listing them.
325    NoGlyph {
326        /// The character code exactly as the show operator carried it.
327        code: u32,
328        /// The font's `/BaseFont` name, or its `Tf` resource name when the
329        /// dictionary has none.
330        font: String,
331    },
332}
333
334impl std::fmt::Display for SkipReason {
335    /// The reason as the clause after the colon of a warning line, e.g.
336    /// `unsupported filter /JPXDecode`.
337    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338        match self {
339            SkipReason::UnsupportedFilter(name) => write!(f, "unsupported filter /{name}"),
340            SkipReason::DecodeFailed(msg) => f.write_str(msg),
341            SkipReason::Undecodable => f.write_str("the data could not be interpreted"),
342            SkipReason::Truncated => f.write_str("sample data ended early; the rest painted blank"),
343            SkipReason::Missing => f.write_str("the resource is missing"),
344            SkipReason::Unsupported => f.write_str("not supported yet"),
345            SkipReason::LimitExceeded => f.write_str("a nesting limit stopped the render here"),
346            SkipReason::NoGlyph { code, font } => {
347                write!(f, "no glyph for code {code} in /{font}")
348            }
349        }
350    }
351}
352
353/// One kind of content dropped for one reason, with how often it happened.
354#[derive(Clone, Debug, PartialEq, Eq)]
355#[non_exhaustive]
356pub struct SkippedContent {
357    /// What was dropped.
358    pub kind: SkippedKind,
359    /// Why it was dropped.
360    pub reason: SkipReason,
361    /// How many times this exact kind/reason pair came up in the render.
362    pub count: u64,
363}
364
365/// What a page render could not reproduce faithfully: content dropped
366/// outright (an undecodable image, an unreadable form) and content painted
367/// as an approximation (a pattern fill as flat gray). Empty means every
368/// construct the render encountered was painted as the page describes it.
369///
370/// Two things are deliberately *not* reported, because they are configured
371/// behavior rather than a failure: text left unpainted by the requested
372/// [`GlyphPainting`] tier — its font never loaded — and content clipped or
373/// transformed off the page. A code a *loaded* font has no glyph for is a
374/// real loss and IS reported, as [`SkippedKind::Glyph`].
375#[derive(Clone, Debug, Default, PartialEq, Eq)]
376#[non_exhaustive]
377pub struct RenderReport {
378    /// Distinct drops in the order first encountered, at most 64 entries
379    /// (see `count` for repeats and [`RenderReport::unlisted`] for the
380    /// overflow).
381    pub skipped: Vec<SkippedContent>,
382    /// Drops that arrived after `skipped` reached its 64-entry cap and so
383    /// are counted but not described.
384    pub unlisted: u64,
385}
386
387impl RenderReport {
388    /// Whether the page rasterized with nothing dropped or approximated.
389    pub fn is_empty(&self) -> bool {
390        self.skipped.is_empty() && self.unlisted == 0
391    }
392
393    /// A one-line human summary counting drops per kind, or `None` when
394    /// nothing was dropped: `"2 images, 1 shading skipped"`.
395    pub fn summary(&self) -> Option<String> {
396        if self.is_empty() {
397            return None;
398        }
399        let mut totals: Vec<(SkippedKind, u64)> = Vec::new();
400        for item in &self.skipped {
401            match totals.iter_mut().find(|(kind, _)| *kind == item.kind) {
402                Some((_, n)) => *n = n.saturating_add(item.count),
403                None => totals.push((item.kind, item.count)),
404            }
405        }
406        let mut parts: Vec<String> = totals
407            .iter()
408            .map(|(kind, n)| format!("{n} {}", kind.noun(*n)))
409            .collect();
410        if self.unlisted > 0 {
411            parts.push(format!("{} more", self.unlisted));
412        }
413        Some(format!("{} skipped", parts.join(", ")))
414    }
415
416    /// One human-readable line per distinct drop, for callers that warn
417    /// about them: `"1 image skipped: unsupported filter /JPXDecode"`.
418    pub fn warnings(&self) -> Vec<String> {
419        let mut out: Vec<String> = self
420            .skipped
421            .iter()
422            .map(|item| {
423                format!(
424                    "{} {} skipped: {}",
425                    item.count,
426                    item.kind.noun(item.count),
427                    item.reason
428                )
429            })
430            .collect();
431        if self.unlisted > 0 {
432            out.push(format!(
433                "{} further drops not described (report limit reached)",
434                self.unlisted
435            ));
436        }
437        out
438    }
439
440    /// Records one drop, merging it into an existing entry when the same
441    /// kind and reason already happened. Beyond [`MAX_SKIPPED`] distinct
442    /// entries the drop is only counted, so a page drawing endlessly varied
443    /// broken content cannot grow this report without bound.
444    pub(crate) fn record(&mut self, kind: SkippedKind, reason: SkipReason) {
445        if let Some(item) = self
446            .skipped
447            .iter_mut()
448            .find(|item| item.kind == kind && item.reason == reason)
449        {
450            item.count = item.count.saturating_add(1);
451            return;
452        }
453        if self.skipped.len() >= MAX_SKIPPED {
454            self.unlisted = self.unlisted.saturating_add(1);
455            return;
456        }
457        self.skipped.push(SkippedContent {
458            kind,
459            reason,
460            count: 1,
461        });
462    }
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn new_pixmap_is_transparent() {
471        let pix = Pixmap::new(3, 2);
472        assert_eq!(pix.width, 3);
473        assert_eq!(pix.height, 2);
474        assert_eq!(pix.data.len(), 24);
475        assert!(pix.data.iter().all(|&b| b == 0));
476    }
477
478    #[test]
479    fn fill_sets_every_pixel() {
480        let mut pix = Pixmap::new(2, 2);
481        pix.fill([1, 2, 3, 4]);
482        assert_eq!(pix.data, [1, 2, 3, 4].repeat(4));
483    }
484
485    #[test]
486    fn png_round_trip_preserves_pixels() {
487        let mut pix = Pixmap::new(3, 2);
488        for (i, b) in pix.data.iter_mut().enumerate() {
489            *b = (i * 11 % 256) as u8;
490        }
491        let bytes = pix.encode_png().expect("encode");
492        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
493
494        let decoder = png::Decoder::new(std::io::Cursor::new(&bytes));
495        let mut reader = decoder.read_info().expect("read_info");
496        let mut buf = vec![0u8; reader.output_buffer_size().expect("size")];
497        let info = reader.next_frame(&mut buf).expect("frame");
498        assert_eq!(info.width, 3);
499        assert_eq!(info.height, 2);
500        assert_eq!(info.color_type, png::ColorType::Rgba);
501        assert_eq!(info.bit_depth, png::BitDepth::Eight);
502        assert_eq!(&buf[..info.buffer_size()], &pix.data[..]);
503    }
504
505    #[test]
506    fn report_merges_repeats_and_counts_per_kind() {
507        let mut report = RenderReport::default();
508        assert!(report.is_empty());
509        report.record(SkippedKind::Image, SkipReason::Undecodable);
510        report.record(SkippedKind::Image, SkipReason::Undecodable);
511        report.record(
512            SkippedKind::Image,
513            SkipReason::UnsupportedFilter("JPXDecode".to_string()),
514        );
515        report.record(SkippedKind::Shading, SkipReason::Unsupported);
516
517        assert!(!report.is_empty());
518        assert_eq!(report.skipped.len(), 3, "same kind and reason merge");
519        assert_eq!(report.skipped[0].count, 2);
520        // The summary counts per kind, so the two image reasons add up.
521        assert_eq!(
522            report.summary().as_deref(),
523            Some("3 images, 1 shading skipped"),
524        );
525        assert_eq!(
526            report.warnings(),
527            vec![
528                "2 images skipped: the data could not be interpreted".to_string(),
529                "1 image skipped: unsupported filter /JPXDecode".to_string(),
530                "1 shading skipped: not supported yet".to_string(),
531            ],
532        );
533    }
534
535    #[test]
536    fn report_stops_listing_at_the_cap_but_keeps_counting() {
537        let mut report = RenderReport::default();
538        for i in 0..MAX_SKIPPED + 5 {
539            report.record(SkippedKind::Image, SkipReason::DecodeFailed(i.to_string()));
540        }
541        assert_eq!(report.skipped.len(), MAX_SKIPPED);
542        assert_eq!(report.unlisted, 5);
543        assert_eq!(
544            report.summary().as_deref(),
545            Some("64 images, 5 more skipped"),
546        );
547    }
548
549    #[test]
550    fn save_png_writes_decodable_file() {
551        let mut pix = Pixmap::new(4, 4);
552        pix.fill([10, 20, 30, 255]);
553        let dir = std::env::temp_dir().join("pdfboss-render-test");
554        std::fs::create_dir_all(&dir).unwrap();
555        let path = dir.join("pix.png");
556        pix.save_png(&path).expect("save");
557        let bytes = std::fs::read(&path).unwrap();
558        assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
559        std::fs::remove_file(&path).ok();
560    }
561}