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 limitation: `/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 (their text still advances, via the
22//! metrics-only loader in `crate::glyph`).
23
24// The rasterizer modules are consumed by the content-stream executor; the
25// `dead_code` allowances below disappear once it is wired up.
26mod annot;
27mod cff;
28#[allow(dead_code)]
29mod color;
30mod encode;
31mod executor;
32mod extract;
33mod glyph;
34mod image;
35mod jpeg;
36#[allow(dead_code)]
37mod path;
38#[allow(dead_code)]
39mod raster;
40mod shading;
41#[allow(dead_code)]
42mod stroke;
43#[allow(dead_code)]
44mod substitute;
45mod truetype;
46mod type1;
47mod type3;
48
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51
52use pdfboss_core::{AsyncObjectSource, Document, Error, OcState, Page, Result};
53
54pub use extract::{extract_page_images, extract_page_images_with};
55
56/// An RGBA8 raster image with straight (non-premultiplied) alpha, row-major
57/// from the top-left.
58#[derive(Debug, Clone, PartialEq)]
59pub struct Pixmap {
60 pub width: u32,
61 pub height: u32,
62 /// Pixel data, `width * height * 4` bytes (RGBA per pixel).
63 pub data: Vec<u8>,
64}
65
66/// How much CPU the PNG encoder spends shrinking the file. Every level
67/// round-trips the exact same pixels; only encode time and file size move.
68/// `Balanced` is what [`Pixmap::encode_png`] has always used.
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum PngCompression {
71 /// Uncompressed: fastest, largest files.
72 None,
73 /// Very fast with a decent ratio.
74 Fast,
75 /// Balances encode speed and file size.
76 #[default]
77 Balanced,
78 /// Smallest files, much slower.
79 Best,
80}
81
82impl PngCompression {
83 fn to_encoding(self) -> png::Compression {
84 match self {
85 PngCompression::None => png::Compression::NoCompression,
86 PngCompression::Fast => png::Compression::Fast,
87 PngCompression::Balanced => png::Compression::Balanced,
88 PngCompression::Best => png::Compression::High,
89 }
90 }
91}
92
93/// The file format [`Pixmap::encode`] writes. PNG keeps every channel and
94/// carries its compression level; PPM and BMP are a header plus one packing
95/// pass over the pixels, dropping alpha; JPEG is lossy at its quality.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum ImageFormat {
98 /// PNG, RGBA 8-bit, at the given compression level.
99 Png(PngCompression),
100 /// Binary PPM (`P6`): RGB rows, top-down, no padding.
101 Ppm,
102 /// Windows BMP: 24-bit BGR rows, bottom-up, padded to four bytes.
103 Bmp,
104 /// Baseline JPEG, 4:4:4, at `quality` 1 to 100 (clamped); alpha dropped.
105 Jpeg {
106 /// The conventional quality knob: 50 uses the standard tables as
107 /// printed, 100 keeps every coefficient, lower values coarsen.
108 quality: u8,
109 },
110}
111
112impl ImageFormat {
113 /// The JPEG quality [`ImageFormat::from_name`] hands out.
114 pub const DEFAULT_JPEG_QUALITY: u8 = 90;
115
116 /// The format a file extension or a Python string names, case
117 /// insensitively: `png` (at the default compression level), `ppm`,
118 /// `bmp`, or `jpeg` / `jpg` (at [`ImageFormat::DEFAULT_JPEG_QUALITY`]).
119 pub fn from_name(name: &str) -> Option<ImageFormat> {
120 match name.to_ascii_lowercase().as_str() {
121 "png" => Some(ImageFormat::Png(PngCompression::default())),
122 "ppm" => Some(ImageFormat::Ppm),
123 "bmp" => Some(ImageFormat::Bmp),
124 "jpeg" | "jpg" => Some(ImageFormat::Jpeg {
125 quality: ImageFormat::DEFAULT_JPEG_QUALITY,
126 }),
127 _ => None,
128 }
129 }
130}
131
132impl Pixmap {
133 /// Creates a fully transparent pixmap.
134 pub fn new(w: u32, h: u32) -> Pixmap {
135 Pixmap {
136 width: w,
137 height: h,
138 data: vec![0; w as usize * h as usize * 4],
139 }
140 }
141
142 /// Fills every pixel with `rgba`.
143 pub fn fill(&mut self, rgba: [u8; 4]) {
144 for px in self.data.as_chunks_mut::<4>().0 {
145 *px = rgba;
146 }
147 }
148
149 /// Encodes the pixmap as a PNG image, at the default compression level.
150 pub fn encode_png(&self) -> Result<Vec<u8>> {
151 self.encode_png_with(PngCompression::default())
152 }
153
154 /// Encodes the pixmap as a PNG image at the given compression level.
155 pub fn encode_png_with(&self, compression: PngCompression) -> Result<Vec<u8>> {
156 fn err(e: png::EncodingError) -> Error {
157 Error::Other(format!("png encode: {e}"))
158 }
159 if compression == PngCompression::Balanced {
160 return Ok(encode::encode_rgba(self.width, self.height, &self.data));
161 }
162 let mut out = Vec::new();
163 let mut enc = png::Encoder::new(&mut out, self.width, self.height);
164 enc.set_color(png::ColorType::Rgba);
165 enc.set_depth(png::BitDepth::Eight);
166 enc.set_compression(compression.to_encoding());
167 let mut writer = enc.write_header().map_err(err)?;
168 writer.write_image_data(&self.data).map_err(err)?;
169 writer.finish().map_err(err)?;
170 Ok(out)
171 }
172
173 /// Encodes the pixmap in `format`.
174 pub fn encode(&self, format: ImageFormat) -> Result<Vec<u8>> {
175 match format {
176 ImageFormat::Png(compression) => self.encode_png_with(compression),
177 ImageFormat::Ppm => Ok(encode::encode_ppm(self.width, self.height, &self.data)),
178 ImageFormat::Bmp => Ok(encode::encode_bmp(self.width, self.height, &self.data)),
179 ImageFormat::Jpeg { quality } => {
180 jpeg::encode_jpeg(self.width, self.height, &self.data, quality)
181 }
182 }
183 }
184
185 /// Encodes the pixmap as PNG and writes it to `path`.
186 pub fn save_png(&self, path: impl AsRef<Path>) -> Result<()> {
187 std::fs::write(path, self.encode_png()?)?;
188 Ok(())
189 }
190}
191
192/// How aggressively the rasterizer turns text into filled outlines. Each tier is
193/// a strict superset of the previous one; the difference is only observable once
194/// the corresponding glyph loaders exist.
195#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
196pub enum GlyphPainting {
197 /// Only embedded TrueType (`glyf`) outlines — the cheapest tier.
198 EmbeddedTrueTypeOnly,
199 /// Every embedded program: TrueType, CFF, Type1 and Type3. No bundled assets.
200 #[default]
201 AllEmbedded,
202 /// Also substitute bundled or caller-provided faces for non-embedded
203 /// fonts, and per glyph for codes an embedded simple font's program
204 /// lacks.
205 Full,
206}
207
208impl GlyphPainting {
209 /// Whether this tier paints every embedded program (CFF, Type1, Type3),
210 /// not just embedded TrueType.
211 pub fn paints_all_embedded(self) -> bool {
212 !matches!(self, GlyphPainting::EmbeddedTrueTypeOnly)
213 }
214}
215
216/// Where non-embedded glyph substitution (the `Full` [`GlyphPainting`] tier)
217/// draws replacement faces from. The default, `None`, substitutes nothing --
218/// `Full` behaves exactly like `AllEmbedded` until a caller opts in.
219#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
220pub enum SubstituteSource {
221 /// No substitution: non-embedded fonts stay unpainted.
222 #[default]
223 None,
224 /// Compiled-in faces: the OFL Croscore set (Arimo/Tinos/Cousine,
225 /// metric-compatible with Helvetica/Times/Courier) bundled via
226 /// `include_bytes!` behind the `substitute-fonts` Cargo feature -- see
227 /// [`builtin_fonts_available`] and `crate::substitute::BuiltinProvider`.
228 /// Built without that feature, there are no compiled-in faces to hand
229 /// out: `Builtin` degrades to no provider at all, so `Full` behaves
230 /// exactly like `AllEmbedded` for non-embedded fonts, the same as
231 /// `SubstituteSource::None`.
232 Builtin,
233 /// Faces read from a directory at render time (e.g. an installed
234 /// `pdfboss-fonts` package), one file per style -- see
235 /// `substitute::face_filename`.
236 Dir(PathBuf),
237}
238
239/// Options controlling a single page render.
240#[derive(Clone, Debug, Default)]
241pub struct RenderOptions {
242 /// Which font programs the rasterizer will paint.
243 pub glyph_painting: GlyphPainting,
244 /// Where `Full`-tier substitution draws replacement faces from. Ignored
245 /// at every other tier.
246 pub substitutes: SubstituteSource,
247 /// The document's optional-content visibility (ISO 32000-1 §8.11):
248 /// content in groups the default configuration turns off is not
249 /// painted, counted in [`RenderReport::hidden`]. The synchronous entry
250 /// points fill this from the document when it is `None`; an
251 /// asynchronous caller builds it itself (e.g.
252 /// `AsyncDocument::oc_state`), and leaving it `None` there renders
253 /// every layer.
254 pub oc: Option<Arc<OcState>>,
255 /// Fonts loaded once for the document instead of once per page: a
256 /// caller rendering a whole document passes one [`RenderCache`] to
257 /// every page, and each font program — outline parsing included —
258 /// loads once. `None` keeps every load page-local. Keyed by the font
259 /// dictionary's object reference, so identical resource names on
260 /// different pages never collide, exactly like text extraction's
261 /// `FontCache`.
262 pub cache: Option<Arc<RenderCache>>,
263}
264
265/// Cross-page render state: fonts by their dictionary's object reference,
266/// and parsed `ICCBased` colorspace outcomes by their profile stream's.
267/// `Send + Sync`, so a parallel page walk may share one.
268#[derive(Default)]
269pub struct RenderCache {
270 fonts: std::sync::Mutex<pdfboss_core::FastMap<FontKey, executor::SharedGlyphFont>>,
271 /// Shared as one handle with every page's executor, which otherwise
272 /// builds a render-local one — the same two-level shape as `fonts`
273 /// without a second lookup tier.
274 colorspaces: Arc<color::IccCache>,
275}
276
277/// What a cached font load depended on besides the dictionary itself: the
278/// painting tier and the substitute source. One cache handle may serve
279/// renders with different options — a load made at `all-embedded` paints
280/// nothing for a non-embedded font and must not be handed to a `full`
281/// render, so the options are part of the key rather than an invariant the
282/// caller polices.
283#[derive(PartialEq, Eq, Hash, Clone)]
284pub(crate) struct FontKey {
285 pub(crate) font: pdfboss_core::ObjRef,
286 pub(crate) painting: GlyphPainting,
287 pub(crate) substitutes: SubstituteSource,
288}
289
290impl std::fmt::Debug for RenderCache {
291 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292 let fonts = self.fonts.lock().map(|m| m.len()).unwrap_or(0);
293 f.debug_struct("RenderCache")
294 .field("fonts", &fonts)
295 .finish()
296 }
297}
298
299impl RenderCache {
300 pub(crate) fn font(&self, key: &FontKey) -> Option<executor::SharedGlyphFont> {
301 self.fonts.lock().ok()?.get(key).cloned()
302 }
303
304 /// First writer wins, exactly like the text-side cache: concurrent
305 /// workers may load the same font twice and the copies are
306 /// interchangeable.
307 pub(crate) fn store(&self, key: FontKey, font: executor::SharedGlyphFont) {
308 if let Ok(mut fonts) = self.fonts.lock() {
309 fonts.entry(key).or_insert(font);
310 }
311 }
312}
313
314/// Whether this binary was built with the `substitute-fonts` feature, i.e.
315/// whether `SubstituteSource::Builtin` has compiled-in faces to hand out.
316/// Callers (e.g. the CLI) use this to give an actionable message when `Full`
317/// is requested with no `--font-dir` and no compiled-in set, rather than
318/// silently rendering as if `Full` had never been asked for.
319pub fn builtin_fonts_available() -> bool {
320 cfg!(feature = "substitute-fonts")
321}
322
323/// Renders a page at `scale` onto a white background. The pixel size is
324/// `ceil(crop_w * scale) x ceil(crop_h * scale)` (after `/Rotate`), and the
325/// base transform maps the crop box to device space with a y-flip and the
326/// page rotation applied.
327///
328/// Rendering is lenient: content pdfboss cannot read is skipped rather than
329/// failing the render, so a page can come back blank without an error. Use
330/// [`render_page_reporting`] to find out what was dropped.
331pub fn render_page(doc: &Document, page: &Page, scale: f32) -> Result<Pixmap> {
332 render_page_with_options(doc, page, scale, &RenderOptions::default())
333}
334
335/// Renders a page like [`render_page`], honoring `opts` (currently the glyph
336/// painting tier). See [`render_page`] for the geometry contract and for
337/// what leniency means for the pixels you get back.
338pub fn render_page_with_options(
339 doc: &Document,
340 page: &Page,
341 scale: f32,
342 opts: &RenderOptions,
343) -> Result<Pixmap> {
344 executor::render_page_reporting(doc, page, scale, opts).map(|(pix, _)| pix)
345}
346
347/// Renders a page like [`render_page_with_options`], additionally returning
348/// a [`RenderReport`] describing any content that had to be dropped or
349/// approximated. Use this when a silently blank page would be misleading.
350pub fn render_page_reporting(
351 doc: &Document,
352 page: &Page,
353 scale: f32,
354 opts: &RenderOptions,
355) -> Result<(Pixmap, RenderReport)> {
356 executor::render_page_reporting(doc, page, scale, opts)
357}
358
359/// Renders a page like [`render_page_reporting`] against any object source,
360/// awaiting whatever I/O the source needs — this is the asynchronous entry
361/// point, and the synchronous ones above are this implementation over
362/// `pdfboss_core::Immediate` (with [`RenderOptions::oc`] filled from the
363/// document when the caller left it unset), so under the same options the
364/// two APIs cannot render differently.
365///
366/// The source is taken by value and the page by reference, which is the
367/// combination a consumer needs to spawn the result: the future is `Send`
368/// over a source that is `Send + Sync`, and `'static` as long as the borrow
369/// of `page` is created inside the consumer's own `async move` block, which
370/// owns the page. See `pdfboss_core::source`'s "Signing a shared algorithm".
371pub async fn render_page_reporting_with<S: AsyncObjectSource>(
372 src: S,
373 page: &Page,
374 scale: f32,
375 opts: &RenderOptions,
376) -> Result<(Pixmap, RenderReport)> {
377 executor::render_page_reporting_with(src, page, scale, opts).await
378}
379
380/// Upper bound on the distinct entries a [`RenderReport`] keeps. Repeats of
381/// the same kind and reason only raise an existing entry's count, so this
382/// bounds the report's memory for any page: a stream drawing the same
383/// undecodable image a million times costs one entry, and a stream inventing
384/// endlessly *different* failures stops growing the list here and counts the
385/// rest in [`RenderReport::unlisted`].
386const MAX_SKIPPED: usize = 64;
387
388/// Which piece of page content a render could not reproduce.
389#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
390#[non_exhaustive]
391pub enum SkippedKind {
392 /// The page's own content stream: nothing on the page was drawn.
393 PageContents,
394 /// An image XObject or an inline image.
395 Image,
396 /// A form XObject, and with it everything nested inside it.
397 Form,
398 /// A `Do` whose XObject resource is missing, is not a stream, or has no
399 /// subtype this renderer knows how to draw.
400 XObject,
401 /// A shading (`sh` or a shading pattern) this renderer could not
402 /// load: a missing resource or a structural failure. All seven
403 /// shading types paint.
404 Shading,
405 /// A pattern fill or stroke, painted as flat mid-gray instead of the
406 /// pattern's own content.
407 Pattern,
408 /// A mask that was ignored, so content the author masked out painted
409 /// solid: an image `/SMask` or `/Mask`, or an `/ExtGState` `/SMask`.
410 SoftMask,
411 /// A `/BM` blend mode painted as `Normal`. No longer produced — every
412 /// ISO 32000 blend mode paints — but retained so report consumers
413 /// keep compiling against the same set of kinds.
414 BlendMode,
415 /// An annotation appearance stream that was declared but could not be
416 /// painted: unreadable, unparsable, or with no selectable state.
417 /// Annotations that declare no appearance, and ones flagged Hidden or
418 /// NoView, paint nothing by design and are not reported.
419 Annotation,
420 /// A character code a *painting* font has no glyph for: the code
421 /// advanced the text position but painted nothing. A single-byte code
422 /// 0x20 is exempt — a space paints nothing whether or not the font maps
423 /// it — while a two-byte 0x20 is a real CID and is reported. Text whose
424 /// font paints at no tier (the [`GlyphPainting`] tier, or a load
425 /// failure) is configured behavior and stays unreported; such a font
426 /// still loads its metrics so the text advances.
427 Glyph,
428 /// Text shown in a clipping rendering mode (`Tr` 4-7, ISO 32000-1
429 /// §9.3.6) used to be reported here while the glyph outlines never
430 /// joined the clipping path. They do now, so no render produces this
431 /// kind any more; it stays so callers matching on it keep compiling.
432 TextClip,
433}
434
435impl SkippedKind {
436 /// The noun this kind reads as in [`RenderReport::summary`] and
437 /// [`RenderReport::warnings`], pluralized for `n`.
438 fn noun(self, n: u64) -> &'static str {
439 let one = n == 1;
440 match self {
441 SkippedKind::PageContents if one => "content stream",
442 SkippedKind::PageContents => "content streams",
443 SkippedKind::Image if one => "image",
444 SkippedKind::Image => "images",
445 SkippedKind::Form if one => "form XObject",
446 SkippedKind::Form => "form XObjects",
447 SkippedKind::XObject if one => "XObject",
448 SkippedKind::XObject => "XObjects",
449 SkippedKind::Shading if one => "shading",
450 SkippedKind::Shading => "shadings",
451 SkippedKind::Pattern if one => "pattern",
452 SkippedKind::Pattern => "patterns",
453 SkippedKind::SoftMask if one => "mask",
454 SkippedKind::SoftMask => "masks",
455 SkippedKind::BlendMode if one => "blend mode",
456 SkippedKind::BlendMode => "blend modes",
457 SkippedKind::Annotation if one => "annotation",
458 SkippedKind::Annotation => "annotations",
459 SkippedKind::Glyph if one => "glyph",
460 SkippedKind::Glyph => "glyphs",
461 SkippedKind::TextClip if one => "text clip",
462 SkippedKind::TextClip => "text clips",
463 }
464 }
465}
466
467/// Why a piece of page content was dropped or approximated during
468/// rasterization.
469///
470/// Rendering is lenient: content pdfboss cannot read is skipped so the rest
471/// of the page still rasterizes. This enum records *why*, so callers can
472/// tell an intentionally blank page from a page whose content pdfboss could
473/// not read.
474#[derive(Clone, Debug, PartialEq, Eq)]
475#[non_exhaustive]
476pub enum SkipReason {
477 /// The stream's `/Filter` chain names a filter pdfboss does not decode.
478 UnsupportedFilter(String),
479 /// Reading the stream failed, carrying the underlying message: a filter
480 /// that ran but gave up (corrupt data, size limit, ...), or a syntax
481 /// error in a content stream.
482 DecodeFailed(String),
483 /// Filters applied cleanly but the bytes could not be interpreted (bad
484 /// image dimensions, unparsable content stream, unsupported JPEG, ...).
485 Undecodable,
486 /// The stream held fewer samples than the image's dimensions and bit
487 /// depth demand; the missing region painted as zero samples.
488 Truncated,
489 /// A resource the operator names is absent, or is not the kind of object
490 /// the operator needs.
491 Missing,
492 /// pdfboss understands the construct but does not paint it yet, so it
493 /// was omitted or approximated.
494 Unsupported,
495 /// A nesting or size guard stopped the render at this point.
496 LimitExceeded,
497 /// A loaded font has no glyph for a character code the page draws, so
498 /// the code advanced the text position without painting. One value per
499 /// distinct `(font, code)` pair, so the report counts occurrences
500 /// instead of listing them.
501 NoGlyph {
502 /// The character code exactly as the show operator carried it.
503 code: u32,
504 /// The font's `/BaseFont` name, or its `Tf` resource name when the
505 /// dictionary has none.
506 font: String,
507 },
508}
509
510impl std::fmt::Display for SkipReason {
511 /// The reason as the clause after the colon of a warning line, e.g.
512 /// `unsupported filter /NotAFilterDecode`.
513 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
514 match self {
515 SkipReason::UnsupportedFilter(name) => write!(f, "unsupported filter /{name}"),
516 SkipReason::DecodeFailed(msg) => f.write_str(msg),
517 SkipReason::Undecodable => f.write_str("the data could not be interpreted"),
518 SkipReason::Truncated => f.write_str("sample data ended early; the rest painted blank"),
519 SkipReason::Missing => f.write_str("the resource is missing"),
520 SkipReason::Unsupported => f.write_str("not supported yet"),
521 SkipReason::LimitExceeded => f.write_str("a nesting limit stopped the render here"),
522 SkipReason::NoGlyph { code, font } => {
523 write!(f, "no glyph for code {code} in /{font}")
524 }
525 }
526 }
527}
528
529/// One kind of content dropped for one reason, with how often it happened.
530#[derive(Clone, Debug, PartialEq, Eq)]
531#[non_exhaustive]
532pub struct SkippedContent {
533 /// What was dropped.
534 pub kind: SkippedKind,
535 /// Why it was dropped.
536 pub reason: SkipReason,
537 /// How many times this exact kind/reason pair came up in the render.
538 pub count: u64,
539}
540
541/// What a page render could not reproduce faithfully: content dropped
542/// outright (an undecodable image, an unreadable form) and content painted
543/// as an approximation (a pattern fill as flat gray). Empty means every
544/// construct the render encountered was painted as the page describes it.
545///
546/// Two things are deliberately *not* reported, because they are configured
547/// behavior rather than a failure: text left unpainted by the requested
548/// [`GlyphPainting`] tier — its font loads metrics only, so the text still
549/// advances but draws nothing — and content clipped or transformed off the
550/// page. A code a *painting* font has no glyph for is a real loss and IS
551/// reported, as [`SkippedKind::Glyph`].
552#[derive(Clone, Debug, Default, PartialEq, Eq)]
553#[non_exhaustive]
554pub struct RenderReport {
555 /// Distinct drops in the order first encountered, at most 64 entries
556 /// (see `count` for repeats and [`RenderReport::unlisted`] for the
557 /// overflow).
558 pub skipped: Vec<SkippedContent>,
559 /// Drops that arrived after `skipped` reached its 64-entry cap and so
560 /// are counted but not described.
561 pub unlisted: u64,
562 /// Content the document's optional-content configuration turns off
563 /// (ISO 32000-1 §8.11): one count per `BDC /OC` span whose own
564 /// membership evaluated hidden, per XObject with a hidden `/OC` entry,
565 /// and per annotation with a hidden `/OC` entry. Configured behavior,
566 /// not a loss, so it plays no part in [`RenderReport::is_empty`],
567 /// [`RenderReport::summary`], or [`RenderReport::warnings`].
568 pub hidden: u64,
569}
570
571impl RenderReport {
572 /// Whether the page rasterized with nothing dropped or approximated.
573 pub fn is_empty(&self) -> bool {
574 self.skipped.is_empty() && self.unlisted == 0
575 }
576
577 /// A one-line human summary counting drops per kind, or `None` when
578 /// nothing was dropped: `"2 images, 1 shading skipped"`.
579 pub fn summary(&self) -> Option<String> {
580 if self.is_empty() {
581 return None;
582 }
583 let mut totals: Vec<(SkippedKind, u64)> = Vec::new();
584 for item in &self.skipped {
585 match totals.iter_mut().find(|(kind, _)| *kind == item.kind) {
586 Some((_, n)) => *n = n.saturating_add(item.count),
587 None => totals.push((item.kind, item.count)),
588 }
589 }
590 let mut parts: Vec<String> = totals
591 .iter()
592 .map(|(kind, n)| format!("{n} {}", kind.noun(*n)))
593 .collect();
594 if self.unlisted > 0 {
595 parts.push(format!("{} more", self.unlisted));
596 }
597 Some(format!("{} skipped", parts.join(", ")))
598 }
599
600 /// One human-readable line per distinct drop, for callers that warn
601 /// about them: `"1 image skipped: unsupported filter /NotAFilterDecode"`.
602 pub fn warnings(&self) -> Vec<String> {
603 let mut out: Vec<String> = self
604 .skipped
605 .iter()
606 .map(|item| {
607 format!(
608 "{} {} skipped: {}",
609 item.count,
610 item.kind.noun(item.count),
611 item.reason
612 )
613 })
614 .collect();
615 if self.unlisted > 0 {
616 out.push(format!(
617 "{} further drops not described (report limit reached)",
618 self.unlisted
619 ));
620 }
621 out
622 }
623
624 /// Records one drop, merging it into an existing entry when the same
625 /// kind and reason already happened. Beyond [`MAX_SKIPPED`] distinct
626 /// entries the drop is only counted, so a page drawing endlessly varied
627 /// broken content cannot grow this report without bound.
628 pub(crate) fn record(&mut self, kind: SkippedKind, reason: SkipReason) {
629 if let Some(item) = self
630 .skipped
631 .iter_mut()
632 .find(|item| item.kind == kind && item.reason == reason)
633 {
634 item.count = item.count.saturating_add(1);
635 return;
636 }
637 if self.skipped.len() >= MAX_SKIPPED {
638 self.unlisted = self.unlisted.saturating_add(1);
639 return;
640 }
641 self.skipped.push(SkippedContent {
642 kind,
643 reason,
644 count: 1,
645 });
646 }
647}
648
649#[cfg(test)]
650mod tests {
651 use super::*;
652
653 #[test]
654 fn new_pixmap_is_transparent() {
655 let pix = Pixmap::new(3, 2);
656 assert_eq!(pix.width, 3);
657 assert_eq!(pix.height, 2);
658 assert_eq!(pix.data.len(), 24);
659 assert!(pix.data.iter().all(|&b| b == 0));
660 }
661
662 #[test]
663 fn fill_sets_every_pixel() {
664 let mut pix = Pixmap::new(2, 2);
665 pix.fill([1, 2, 3, 4]);
666 assert_eq!(pix.data, [1, 2, 3, 4].repeat(4));
667 }
668
669 #[test]
670 fn compression_levels_map_to_their_encoder_settings() {
671 // png::Compression derives no PartialEq, hence matches!.
672 assert!(matches!(
673 PngCompression::None.to_encoding(),
674 png::Compression::NoCompression
675 ));
676 assert!(matches!(
677 PngCompression::Fast.to_encoding(),
678 png::Compression::Fast
679 ));
680 assert!(matches!(
681 PngCompression::Balanced.to_encoding(),
682 png::Compression::Balanced
683 ));
684 assert!(matches!(
685 PngCompression::Best.to_encoding(),
686 png::Compression::High
687 ));
688 }
689
690 #[test]
691 fn balanced_is_the_default_compression() {
692 assert_eq!(PngCompression::default(), PngCompression::Balanced);
693 }
694
695 #[test]
696 fn png_round_trip_preserves_pixels() {
697 let mut pix = Pixmap::new(3, 2);
698 for (i, b) in pix.data.iter_mut().enumerate() {
699 *b = (i * 11 % 256) as u8;
700 }
701 let bytes = pix.encode_png().expect("encode");
702 assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
703
704 let decoder = png::Decoder::new(std::io::Cursor::new(&bytes));
705 let mut reader = decoder.read_info().expect("read_info");
706 let mut buf = vec![0u8; reader.output_buffer_size().expect("size")];
707 let info = reader.next_frame(&mut buf).expect("frame");
708 assert_eq!(info.width, 3);
709 assert_eq!(info.height, 2);
710 assert_eq!(info.color_type, png::ColorType::Rgba);
711 assert_eq!(info.bit_depth, png::BitDepth::Eight);
712 assert_eq!(&buf[..info.buffer_size()], &pix.data[..]);
713 }
714
715 #[test]
716 fn report_merges_repeats_and_counts_per_kind() {
717 let mut report = RenderReport::default();
718 assert!(report.is_empty());
719 report.record(SkippedKind::Image, SkipReason::Undecodable);
720 report.record(SkippedKind::Image, SkipReason::Undecodable);
721 report.record(
722 SkippedKind::Image,
723 SkipReason::UnsupportedFilter("NotAFilterDecode".to_string()),
724 );
725 report.record(SkippedKind::Shading, SkipReason::Unsupported);
726
727 assert!(!report.is_empty());
728 assert_eq!(report.skipped.len(), 3, "same kind and reason merge");
729 assert_eq!(report.skipped[0].count, 2);
730 // The summary counts per kind, so the two image reasons add up.
731 assert_eq!(
732 report.summary().as_deref(),
733 Some("3 images, 1 shading skipped"),
734 );
735 assert_eq!(
736 report.warnings(),
737 vec![
738 "2 images skipped: the data could not be interpreted".to_string(),
739 "1 image skipped: unsupported filter /NotAFilterDecode".to_string(),
740 "1 shading skipped: not supported yet".to_string(),
741 ],
742 );
743 }
744
745 #[test]
746 fn report_stops_listing_at_the_cap_but_keeps_counting() {
747 let mut report = RenderReport::default();
748 for i in 0..MAX_SKIPPED + 5 {
749 report.record(SkippedKind::Image, SkipReason::DecodeFailed(i.to_string()));
750 }
751 assert_eq!(report.skipped.len(), MAX_SKIPPED);
752 assert_eq!(report.unlisted, 5);
753 assert_eq!(
754 report.summary().as_deref(),
755 Some("64 images, 5 more skipped"),
756 );
757 }
758
759 #[test]
760 fn save_png_writes_decodable_file() {
761 let mut pix = Pixmap::new(4, 4);
762 pix.fill([10, 20, 30, 255]);
763 let dir = std::env::temp_dir().join("pdfboss-render-test");
764 std::fs::create_dir_all(&dir).unwrap();
765 let path = dir.join("pix.png");
766 pix.save_png(&path).expect("save");
767 let bytes = std::fs::read(&path).unwrap();
768 assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
769 std::fs::remove_file(&path).ok();
770 }
771}