Skip to main content

rustium_pdf/
render.rs

1//! Rasterising a page to pixels.
2//!
3//! The page's primitives are replayed in the order the content stream drew them — glyphs, paths
4//! and images share one [`crate::page::Glyph::order`] sequence precisely so that this pass can
5//! interleave them correctly. Painting each type in its own batch would put every image on top
6//! of every rule, which is wrong for any page with a shaded table cell or a figure background.
7
8use tiny_skia::{
9    FillRule, Paint, PathBuilder, Pixmap, PixmapPaint, Shader, Stroke, Transform as SkTransform,
10};
11
12use crate::document::Document;
13use crate::error::{Error, Result};
14use crate::font::glyph::PathCmd;
15use crate::geom::{Matrix, Rect};
16use crate::page::{ImageData, ImageItem, Page};
17
18/// Anything larger than this in either dimension is refused rather than attempted: a page whose
19/// media box or requested scale is absurd would otherwise ask for a multi-gigabyte allocation.
20const MAX_DIMENSION: u32 = 20_000;
21
22/// Options for a render.
23#[derive(Debug, Clone, Copy)]
24pub struct RenderOptions {
25    /// Output resolution. 72 dpi renders one pixel per point.
26    pub dpi: f32,
27    /// Paint an opaque white background first. A PDF page is defined as white paper; leaving it
28    /// transparent makes text unreadable in any viewer that composites onto dark.
29    pub background: bool,
30    /// Draw text. Turning it off is how a caller gets a figure's artwork without its labels.
31    pub draw_text: bool,
32    pub draw_paths: bool,
33    pub draw_images: bool,
34}
35
36impl Default for RenderOptions {
37    fn default() -> Self {
38        RenderOptions {
39            dpi: 72.0,
40            background: true,
41            draw_text: true,
42            draw_paths: true,
43            draw_images: true,
44        }
45    }
46}
47
48impl RenderOptions {
49    pub fn at_dpi(dpi: f32) -> Self {
50        RenderOptions {
51            dpi,
52            ..Default::default()
53        }
54    }
55}
56
57/// A rendered page: 8-bit RGBA, row-major, premultiplied by tiny-skia's convention undone.
58pub struct Rendered {
59    pub width: u32,
60    pub height: u32,
61    /// Straight (non-premultiplied) RGBA, four bytes per pixel.
62    pub rgba: Vec<u8>,
63}
64
65impl Rendered {
66    /// Encodes to PNG.
67    pub fn to_png(&self) -> Result<Vec<u8>> {
68        use image::ImageEncoder;
69        let mut out = Vec::new();
70        image::codecs::png::PngEncoder::new(&mut out)
71            .write_image(
72                &self.rgba,
73                self.width,
74                self.height,
75                image::ExtendedColorType::Rgba8,
76            )
77            .map_err(|e| Error::Render(format!("png encode: {e}")))?;
78        Ok(out)
79    }
80}
81
82impl Page {
83    /// Renders the whole page.
84    pub fn render(&self, doc: &Document, options: RenderOptions) -> Result<Rendered> {
85        self.render_region(doc, None, options)
86    }
87
88    /// Renders a region of the page, or all of it when `region` is `None`.
89    ///
90    /// `region` is in **y-down page space** — the same space [`Page::page_matrix`] produces and
91    /// that a layout consumer works in — with the origin at the top-left of the displayed page.
92    pub fn render_region(
93        &self,
94        doc: &Document,
95        region: Option<Rect>,
96        options: RenderOptions,
97    ) -> Result<Rendered> {
98        let scale = (options.dpi / 72.0).max(0.0);
99        if !scale.is_finite() || scale <= 0.0 {
100            return Err(Error::Render(format!("bad dpi {}", options.dpi)));
101        }
102
103        // Clamp the region to the page so a slightly oversized caller bbox cannot ask for
104        // pixels that do not exist.
105        let page_rect = Rect::from_corners(0.0, 0.0, self.width(), self.height());
106        let region = match region {
107            Some(r) => {
108                let clipped = r.intersect(&page_rect);
109                if clipped.is_empty() {
110                    return Err(Error::Render("region does not overlap the page".into()));
111                }
112                clipped
113            }
114            None => page_rect,
115        };
116
117        let width = ((region.width() * scale).ceil() as u32).clamp(1, MAX_DIMENSION);
118        let height = ((region.height() * scale).ceil() as u32).clamp(1, MAX_DIMENSION);
119        let mut pixmap = Pixmap::new(width, height)
120            .ok_or_else(|| Error::Render(format!("cannot allocate {width}x{height} pixmap")))?;
121        if options.background {
122            pixmap.fill(tiny_skia::Color::WHITE);
123        }
124
125        // User space to the cropped, scaled output: the page transform, then the region offset.
126        let base = self
127            .page_matrix(scale)
128            .concat(&Matrix::translate(-region.x0 * scale, -region.y0 * scale));
129
130        // One merged pass in paint order. Each primitive is cheap to classify and the counts
131        // are page-sized, so the sort costs nothing next to the rasterisation.
132        let mut order: Vec<Item> = Vec::new();
133        if options.draw_paths {
134            order.extend(self.paths.iter().map(|p| Item::Path(p.order, p)));
135        }
136        if options.draw_text {
137            order.extend(
138                self.glyphs
139                    .iter()
140                    .filter(|g| g.is_visible())
141                    .map(|g| Item::Glyph(g.order, g)),
142            );
143        }
144        if options.draw_images {
145            order.extend(self.images.iter().map(|i| Item::Image(i.order, i)));
146        }
147        order.sort_by_key(Item::order);
148
149        for item in order {
150            match item {
151                Item::Path(_, p) => draw_path(&mut pixmap, p, &base),
152                Item::Glyph(_, g) => draw_glyph(&mut pixmap, g, &base),
153                Item::Image(_, i) => draw_image(doc, &mut pixmap, i, &base),
154            }
155        }
156
157        // tiny-skia stores premultiplied alpha; callers expect straight RGBA.
158        let rgba = pixmap
159            .pixels()
160            .iter()
161            .flat_map(|p| {
162                let c = p.demultiply();
163                [c.red(), c.green(), c.blue(), c.alpha()]
164            })
165            .collect();
166
167        Ok(Rendered {
168            width,
169            height,
170            rgba,
171        })
172    }
173}
174
175/// A primitive tagged with its paint order, so the three vectors can be merged.
176enum Item<'a> {
177    Path(u32, &'a crate::page::PathItem),
178    Glyph(u32, &'a crate::page::Glyph),
179    Image(u32, &'a ImageItem),
180}
181
182impl Item<'_> {
183    fn order(&self) -> u32 {
184        match self {
185            Item::Path(o, _) | Item::Glyph(o, _) | Item::Image(o, _) => *o,
186        }
187    }
188}
189
190fn paint_for(color: [f32; 3], alpha: f32) -> Paint<'static> {
191    let mut paint = Paint {
192        anti_alias: true,
193        ..Default::default()
194    };
195    paint.shader = Shader::SolidColor(
196        tiny_skia::Color::from_rgba(
197            color[0].clamp(0.0, 1.0),
198            color[1].clamp(0.0, 1.0),
199            color[2].clamp(0.0, 1.0),
200            alpha.clamp(0.0, 1.0),
201        )
202        .unwrap_or(tiny_skia::Color::BLACK),
203    );
204    paint
205}
206
207/// Builds a tiny-skia path from our commands, transformed by `m`.
208fn build_path(cmds: &[PathCmd], m: &Matrix) -> Option<tiny_skia::Path> {
209    let mut b = PathBuilder::new();
210    let mut open = false;
211    for cmd in cmds {
212        match *cmd {
213            PathCmd::MoveTo(p) => {
214                let p = m.apply(p);
215                b.move_to(p.x, p.y);
216                open = true;
217            }
218            PathCmd::LineTo(p) => {
219                if !open {
220                    continue;
221                }
222                let p = m.apply(p);
223                b.line_to(p.x, p.y);
224            }
225            PathCmd::CurveTo(c1, c2, p) => {
226                if !open {
227                    continue;
228                }
229                let (c1, c2, p) = (m.apply(c1), m.apply(c2), m.apply(p));
230                b.cubic_to(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
231            }
232            PathCmd::Close => {
233                if open {
234                    b.close();
235                }
236            }
237        }
238    }
239    b.finish()
240}
241
242fn draw_path(pixmap: &mut Pixmap, item: &crate::page::PathItem, base: &Matrix) {
243    let Some(path) = build_path(&item.cmds, base) else {
244        return;
245    };
246    if let Some(color) = item.fill {
247        let rule = if item.even_odd {
248            FillRule::EvenOdd
249        } else {
250            FillRule::Winding
251        };
252        pixmap.fill_path(
253            &path,
254            &paint_for(color, item.fill_alpha),
255            rule,
256            SkTransform::identity(),
257            None,
258        );
259    }
260    if let Some(color) = item.stroke {
261        // The recorded width is already in user space; the base transform scales it to device.
262        let width = (item.line_width * base.x_scale()).max(0.1);
263        pixmap.stroke_path(
264            &path,
265            &paint_for(color, item.stroke_alpha),
266            &Stroke {
267                width,
268                ..Default::default()
269            },
270            SkTransform::identity(),
271            None,
272        );
273    }
274}
275
276/// Draws one glyph. The document is not needed: the glyph carries its own font, and outlines
277/// resolve through that font's cache.
278fn draw_glyph(pixmap: &mut Pixmap, glyph: &crate::page::Glyph, base: &Matrix) {
279    // Generated spaces have no outline by construction, and a Type3 glyph's marks were already
280    // emitted as ordinary paths by the interpreter.
281    let Some(outline) = glyph.outline() else {
282        return;
283    };
284    let m = glyph.outline_matrix().concat(base);
285    let Some(path) = build_path(&outline.cmds, &m) else {
286        return;
287    };
288    // Modes 1 and 5 stroke; everything else that paints, fills. Stroked text is rare enough
289    // that filling it too is closer than leaving it blank.
290    pixmap.fill_path(
291        &path,
292        &paint_for(glyph.color, glyph.alpha),
293        FillRule::Winding,
294        SkTransform::identity(),
295        None,
296    );
297}
298
299fn draw_image(doc: &Document, pixmap: &mut Pixmap, item: &ImageItem, base: &Matrix) {
300    let Some(src) = decode_to_rgba(doc, item) else {
301        return;
302    };
303    // `item.ctm` maps the unit square onto the page with the row flip already folded in, so the
304    // image's own pixel grid only needs scaling down to that square.
305    let to_unit = Matrix::scale(1.0 / item.width as f32, 1.0 / item.height as f32);
306    let m = to_unit.concat(&item.ctm).concat(base);
307    let ts = SkTransform::from_row(m.a, m.b, m.c, m.d, m.e, m.f);
308
309    pixmap.draw_pixmap(
310        0,
311        0,
312        src.as_ref(),
313        &PixmapPaint {
314            opacity: item.alpha.clamp(0.0, 1.0),
315            quality: tiny_skia::FilterQuality::Bilinear,
316            ..Default::default()
317        },
318        ts,
319        None,
320    );
321}
322
323/// Expands an image's samples to an RGBA pixmap.
324fn decode_to_rgba(doc: &Document, item: &ImageItem) -> Option<Pixmap> {
325    let data = item.decode(doc).ok()?;
326    let mut pixmap = Pixmap::new(item.width, item.height)?;
327    let px = pixmap.pixels_mut();
328    let (w, h) = (item.width as usize, item.height as usize);
329
330    match data {
331        // JPEG is the only image codec worth carrying a decoder for: it is what scanned pages
332        // and photographs use. JPEG 2000, CCITT and JBIG2 are left to the caller.
333        ImageData::Encoded { filter, data } if filter == "DCTDecode" || filter == "DCT" => {
334            let img = image::load_from_memory_with_format(&data, image::ImageFormat::Jpeg)
335                .ok()?
336                .to_rgba8();
337            for (i, slot) in px.iter_mut().enumerate() {
338                let (x, y) = ((i % w) as u32, (i / w) as u32);
339                if x >= img.width() || y >= img.height() {
340                    continue;
341                }
342                let p = img.get_pixel(x, y).0;
343                *slot = tiny_skia::PremultipliedColorU8::from_rgba(p[0], p[1], p[2], 255)
344                    .unwrap_or(tiny_skia::PremultipliedColorU8::TRANSPARENT);
345            }
346            Some(pixmap)
347        }
348        ImageData::Encoded { .. } => None,
349        ImageData::Raw {
350            bits_per_component,
351            components,
352            data,
353        } => {
354            let bpc = bits_per_component.max(1) as usize;
355            let comps = components.max(1) as usize;
356            // Rows are padded to a byte boundary.
357            let row_bits = w * comps * bpc;
358            let row_bytes = row_bits.div_ceil(8);
359
360            for y in 0..h {
361                for x in 0..w {
362                    let mut vals = [0u8; 4];
363                    for (c, slot) in vals.iter_mut().enumerate().take(comps.min(4)) {
364                        let bit = (x * comps + c) * bpc;
365                        *slot = sample(&data, y * row_bytes, bit, bpc);
366                    }
367                    let (r, g, b, a) = if item.is_mask {
368                        // A stencil mask paints the fill colour where the sample is 0.
369                        let on = vals[0] == 0;
370                        let c = item.fill;
371                        (
372                            (c[0] * 255.0) as u8,
373                            (c[1] * 255.0) as u8,
374                            (c[2] * 255.0) as u8,
375                            if on { 255 } else { 0 },
376                        )
377                    } else {
378                        match comps {
379                            1 => (vals[0], vals[0], vals[0], 255),
380                            3 => (vals[0], vals[1], vals[2], 255),
381                            4 => {
382                                // Naive CMYK, matching the interpreter's colour conversion:
383                                // `(1 - c) * (1 - k)` per channel.
384                                let k = vals[3] as f32 / 255.0;
385                                let f = |v: u8| (((255 - v) as f32) * (1.0 - k)) as u8;
386                                (f(vals[0]), f(vals[1]), f(vals[2]), 255)
387                            }
388                            _ => (vals[0], vals[0], vals[0], 255),
389                        }
390                    };
391                    let idx = y * w + x;
392                    if let Some(slot) = px.get_mut(idx) {
393                        // tiny-skia stores premultiplied; alpha here is 0 or 255 so the
394                        // multiply is exact.
395                        let (r, g, b) = if a == 0 { (0, 0, 0) } else { (r, g, b) };
396                        *slot = tiny_skia::PremultipliedColorU8::from_rgba(r, g, b, a)
397                            .unwrap_or(tiny_skia::PremultipliedColorU8::TRANSPARENT);
398                    }
399                }
400            }
401            Some(pixmap)
402        }
403    }
404}
405
406/// Reads one sample of `bits` width starting `bit_offset` bits into the row at `row_start`,
407/// scaled up to a full byte.
408fn sample(data: &[u8], row_start: usize, bit_offset: usize, bits: usize) -> u8 {
409    match bits {
410        8 => data.get(row_start + bit_offset / 8).copied().unwrap_or(0),
411        16 => data.get(row_start + bit_offset / 8).copied().unwrap_or(0),
412        1 | 2 | 4 => {
413            let byte = data.get(row_start + bit_offset / 8).copied().unwrap_or(0);
414            let shift = 8 - bits - (bit_offset % 8);
415            let mask = (1u16 << bits) - 1;
416            let v = (byte >> shift) as u16 & mask;
417            // Scale the small range up so 1-bit 1 becomes 255, not 1.
418            ((v * 255) / mask) as u8
419        }
420        _ => 0,
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use crate::page::tests::doc_with;
428
429    /// Reads a pixel as `(r, g, b, a)`.
430    fn px(img: &Rendered, x: u32, y: u32) -> (u8, u8, u8, u8) {
431        let i = ((y * img.width + x) * 4) as usize;
432        (
433            img.rgba[i],
434            img.rgba[i + 1],
435            img.rgba[i + 2],
436            img.rgba[i + 3],
437        )
438    }
439
440    #[test]
441    fn fills_land_in_y_down_device_space() {
442        // A 100x100 blue box at the user-space origin is at the *bottom* left of the page.
443        let doc = doc_with("0 0 1 rg 0 0 100 100 re f");
444        let page = doc.page(0).unwrap();
445        let img = page.render(&doc, RenderOptions::at_dpi(72.0)).unwrap();
446        assert_eq!((img.width, img.height), (612, 792));
447        assert_eq!(
448            px(&img, 50, 742),
449            (0, 0, 255, 255),
450            "box should be bottom-left"
451        );
452        assert_eq!(
453            px(&img, 50, 50),
454            (255, 255, 255, 255),
455            "top-left is background"
456        );
457    }
458
459    #[test]
460    fn cmyk_image_samples_are_not_inverted() {
461        // One DeviceCMYK pixel stretched over the page: C=0x60 M=0x20 Y=0x10 K=0x40, which is a
462        // pale cyan. The samples used to be inverted twice, turning it into a dark red.
463        let doc = doc_with(
464            "q 612 0 0 792 0 0 cm BI /W 1 /H 1 /BPC 8 /CS /CMYK ID \u{60}\u{20}\u{10}\u{40} EI Q",
465        );
466        let page = doc.page(0).unwrap();
467        let img = page.render(&doc, RenderOptions::at_dpi(72.0)).unwrap();
468        let (r, g, b, a) = px(&img, 306, 396);
469        assert_eq!(a, 255);
470        // (255 - component) * (1 - k), so cyan leaves the red channel darkest.
471        let want = |c: u8| ((255 - c) as f32 * (1.0 - 0x40 as f32 / 255.0)) as u8;
472        for (got, expect) in [(r, want(0x60)), (g, want(0x20)), (b, want(0x10))] {
473            assert!(
474                got.abs_diff(expect) <= 1,
475                "channel {got} should be about {expect}"
476            );
477        }
478        assert!(r < g && g < b, "cyan-dominant, not the inverted red");
479    }
480
481    #[test]
482    fn dpi_scales_the_output() {
483        let doc = doc_with("0 0 1 rg 0 0 100 100 re f");
484        let page = doc.page(0).unwrap();
485        let img = page.render(&doc, RenderOptions::at_dpi(144.0)).unwrap();
486        assert_eq!((img.width, img.height), (1224, 1584));
487    }
488
489    #[test]
490    fn region_crops_and_is_clamped_to_the_page() {
491        let doc = doc_with("0 0 1 rg 0 0 100 100 re f");
492        let page = doc.page(0).unwrap();
493        // Bottom-left corner in y-down space, deliberately overhanging the page edge.
494        let region = Rect::from_corners(0.0, 692.0, 200.0, 900.0);
495        let img = page
496            .render_region(&doc, Some(region), RenderOptions::at_dpi(72.0))
497            .unwrap();
498        assert_eq!((img.width, img.height), (200, 100));
499        assert_eq!(px(&img, 50, 50), (0, 0, 255, 255));
500        // Right of the 100pt box is background.
501        assert_eq!(px(&img, 150, 50), (255, 255, 255, 255));
502    }
503
504    #[test]
505    fn a_region_off_the_page_is_an_error() {
506        let doc = doc_with("0 0 1 rg 0 0 10 10 re f");
507        let page = doc.page(0).unwrap();
508        let region = Rect::from_corners(2000.0, 2000.0, 2100.0, 2100.0);
509        assert!(page
510            .render_region(&doc, Some(region), RenderOptions::default())
511            .is_err());
512    }
513
514    #[test]
515    fn paint_order_is_preserved_across_primitive_types() {
516        // Red box, then a blue box on top of it. The later one must win.
517        let doc = doc_with("1 0 0 rg 0 0 100 100 re f 0 0 1 rg 0 0 100 100 re f");
518        let page = doc.page(0).unwrap();
519        let img = page.render(&doc, RenderOptions::at_dpi(72.0)).unwrap();
520        assert_eq!(px(&img, 50, 742), (0, 0, 255, 255));
521    }
522
523    #[test]
524    fn non_embedded_base14_text_draws_via_substitution() {
525        // Helvetica with no embedded program: without a substitute face this page would render
526        // blank, which is the failure this whole path exists to prevent.
527        let doc = doc_with("BT /F1 48 Tf 0 0 0 rg 40 400 Td (HHHHHH) Tj ET");
528        let page = doc.page(0).unwrap();
529        assert!(!page.glyphs.is_empty());
530        if page.glyphs[0].outline().is_none() {
531            eprintln!("no substitute font installed; skipping ink check");
532            return;
533        }
534        let img = page.render(&doc, RenderOptions::at_dpi(72.0)).unwrap();
535        let inked = img.rgba.chunks(4).filter(|p| p[0] < 128).count();
536        assert!(inked > 200, "expected glyph ink, got {inked} dark pixels");
537    }
538
539    #[test]
540    fn draw_text_false_suppresses_glyphs_only() {
541        let doc = doc_with("0 0 1 rg 0 0 100 100 re f BT /F1 48 Tf 40 400 Td (HHHH) Tj ET");
542        let page = doc.page(0).unwrap();
543        let img = page
544            .render(
545                &doc,
546                RenderOptions {
547                    draw_text: false,
548                    ..RenderOptions::at_dpi(72.0)
549                },
550            )
551            .unwrap();
552        // The box still paints; nothing dark remains where the text was.
553        assert_eq!(px(&img, 50, 742), (0, 0, 255, 255));
554        let dark = img
555            .rgba
556            .chunks(4)
557            .filter(|p| p[0] < 128 && p[2] < 128)
558            .count();
559        assert_eq!(dark, 0, "text should be suppressed");
560    }
561
562    #[test]
563    fn transparent_background_is_available() {
564        let doc = doc_with("0 0 1 rg 0 0 100 100 re f");
565        let page = doc.page(0).unwrap();
566        let img = page
567            .render(
568                &doc,
569                RenderOptions {
570                    background: false,
571                    ..RenderOptions::at_dpi(72.0)
572                },
573            )
574            .unwrap();
575        assert_eq!(
576            px(&img, 50, 50).3,
577            0,
578            "unpainted area should be transparent"
579        );
580        assert_eq!(px(&img, 50, 742), (0, 0, 255, 255));
581    }
582
583    #[test]
584    fn png_encodes() {
585        let doc = doc_with("0 0 1 rg 0 0 100 100 re f");
586        let png = doc
587            .page(0)
588            .unwrap()
589            .render(&doc, RenderOptions::at_dpi(36.0))
590            .unwrap()
591            .to_png()
592            .unwrap();
593        assert!(png.starts_with(&[0x89, b'P', b'N', b'G']));
594    }
595}