Skip to main content

laminapdf_render/
export.rs

1//! [`export_pages`]: pages drawn through a [`RenderDocument`] and encoded as PNG, JPEG or TIFF
2//! (the editor plan's operations H.06 and H.11). Feature `export`.
3
4use laminapdf_syntax::CancelToken;
5
6use crate::backend::RenderDocument;
7use crate::error::RenderError;
8use crate::request::{RenderFlags, RenderRequest, Rgba8};
9use crate::tiff_writer::TiffWriter;
10
11/// The file format pages are exported to.
12///
13/// Added in 0.2.0.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[non_exhaustive]
16pub enum ExportFormat {
17    /// PNG, RGBA (the `png` crate), with the resolution in `pHYs`.
18    Png,
19    /// JPEG at `quality` 1–100 (`jpeg-encoder`), RGB on the export's background, with the
20    /// resolution in the JFIF header.
21    Jpeg {
22        /// 1 (smallest) to 100 (best); clamped to that range.
23        quality: u8,
24    },
25    /// TIFF, RGBA, Deflate-compressed (the `tiff` crate), with the resolution in
26    /// `XResolution` and `YResolution`. With `multi_page`, [`export_pages`] writes every page
27    /// into one file.
28    Tiff {
29        /// One file holding every page, instead of one file per page.
30        multi_page: bool,
31    },
32}
33
34/// What [`export_pages`] writes.
35///
36/// ```
37/// use laminapdf_render::{ExportFormat, ExportOptions};
38///
39/// let options = ExportOptions::new(ExportFormat::Png).with_dpi(150.0);
40/// assert_eq!(options.dpi(), 150.0);
41/// ```
42///
43/// Added in 0.2.0.
44#[derive(Debug, Clone, Copy, PartialEq)]
45pub struct ExportOptions {
46    format: ExportFormat,
47    dpi: f64,
48    background: Option<Rgba8>,
49    flags: RenderFlags,
50}
51
52impl ExportOptions {
53    /// `format` at 150 dpi, on white, with the default [`RenderFlags`].
54    ///
55    /// Added in 0.2.0.
56    #[must_use]
57    pub fn new(format: ExportFormat) -> Self {
58        Self {
59            format,
60            dpi: 150.0,
61            background: Some(Rgba8::WHITE),
62            flags: RenderFlags::default(),
63        }
64    }
65
66    /// The resolution, in pixels per inch (72 is one pixel per point).
67    ///
68    /// Added in 0.2.0.
69    #[must_use]
70    pub const fn with_dpi(mut self, dpi: f64) -> Self {
71        self.dpi = dpi;
72        self
73    }
74
75    /// The colour under the page; `None` keeps PNG and TIFF transparent where nothing is drawn.
76    /// JPEG has no transparency, so it always goes on an opaque colour: this one, or white.
77    ///
78    /// Added in 0.2.0.
79    #[must_use]
80    pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
81        self.background = background;
82        self
83    }
84
85    /// What is drawn besides the page content (annotations, form widgets, print intent).
86    ///
87    /// Added in 0.2.0.
88    #[must_use]
89    pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
90        self.flags = flags;
91        self
92    }
93
94    /// The format.
95    ///
96    /// Added in 0.2.0.
97    #[must_use]
98    pub const fn format(&self) -> ExportFormat {
99        self.format
100    }
101
102    /// The resolution, in pixels per inch.
103    ///
104    /// Added in 0.2.0.
105    #[must_use]
106    pub const fn dpi(&self) -> f64 {
107        self.dpi
108    }
109
110    fn request(&self, page: u32) -> RenderRequest {
111        let background = match self.format {
112            ExportFormat::Jpeg { .. } => Some(self.background.filter(|c| c.a == 255).unwrap_or(Rgba8::WHITE)),
113            _ => self.background,
114        };
115        RenderRequest {
116            flags: self.flags,
117            background,
118            ..RenderRequest::page(page, scale(self.dpi))
119        }
120    }
121}
122
123/// Pixels per point for `dpi`, never below the exact ratio. A render's size is the page's
124/// size times the scale, rounded down, so an `f32` that lands a hair under `dpi / 72` would cost
125/// a page that is a whole number of pixels its last column (Letter at 150 dpi: 1,274, not 1,275).
126fn scale(dpi: f64) -> f32 {
127    let exact = dpi / 72.0;
128    #[expect(clippy::cast_possible_truncation, reason = "the nearest f32, nudged up below")]
129    let scale = exact as f32;
130    if f64::from(scale) < exact {
131        scale.next_up()
132    } else {
133        scale
134    }
135}
136
137/// Draws `pages` (0-based) of `doc` one at a time and encodes each as [`ExportOptions`] says:
138/// one file per page, in order, except a multi-page TIFF, which is one file. Only one page's
139/// pixels are held at a time.
140///
141/// ```
142/// # #[cfg(feature = "hayro")] {
143/// use std::sync::Arc;
144/// use laminapdf_render::{
145///     ByteSource, CancelToken, ExportFormat, ExportOptions, HayroBackend, RenderBackend, RenderOpenOptions,
146///     export_pages,
147/// };
148/// # let pdf = laminapdf_test_fixtures::fixture("corpus/hello.pdf");
149/// let doc = HayroBackend::new().open(Arc::new(pdf) as Arc<dyn ByteSource>, &RenderOpenOptions::new())?;
150/// let files = export_pages(doc.as_ref(), &[0], &ExportOptions::new(ExportFormat::Png), &CancelToken::new())?;
151/// assert!(files[0].starts_with(b"\x89PNG"));
152/// # }
153/// # Ok::<(), laminapdf_render::RenderError>(())
154/// ```
155///
156/// # Errors
157/// [`RenderError::InvalidRequest`] for a resolution that isn't a positive finite number; what
158/// [`RenderDocument::render`] returns for a page (an index out of range, a page past
159/// [`RenderLimits`](crate::RenderLimits), [`RenderError::Cancelled`]);
160/// [`RenderError::TooLarge`] for a page wider or taller than JPEG's 65,535 pixels;
161/// [`RenderError::InvalidRequest`] for no pages; [`RenderError::ExportFailed`] if an encoder
162/// fails.
163///
164/// Added in 0.2.0.
165pub fn export_pages(
166    doc: &dyn RenderDocument,
167    pages: &[u32],
168    options: &ExportOptions,
169    cancel: &CancelToken,
170) -> Result<Vec<Vec<u8>>, RenderError> {
171    if pages.is_empty() {
172        return Err(RenderError::InvalidRequest {
173            what: "an export needs at least one page",
174        });
175    }
176    if !options.dpi.is_finite() || options.dpi <= 0.0 {
177        return Err(RenderError::InvalidRequest {
178            what: "the export resolution must be a positive number of pixels per inch",
179        });
180    }
181    if let ExportFormat::Tiff { multi_page: true } = options.format {
182        let mut tiff = TiffWriter::new()?;
183        for &page in pages {
184            let (width, height, rgba) = draw(doc, page, options, cancel)?;
185            tiff.add_page(width, height, &rgba, options.dpi)?;
186        }
187        return Ok(vec![tiff.finish()]);
188    }
189    pages
190        .iter()
191        .map(|&page| {
192            let (width, height, rgba) = draw(doc, page, options, cancel)?;
193            encode(width, height, &rgba, options)
194        })
195        .collect()
196}
197
198/// One page's pixels: width, height and straight RGBA.
199fn draw(
200    doc: &dyn RenderDocument,
201    page: u32,
202    options: &ExportOptions,
203    cancel: &CancelToken,
204) -> Result<(u32, u32, Vec<u8>), RenderError> {
205    let request = options.request(page);
206    let plan = doc.plan(&request)?;
207    let mut rgba = vec![0; plan.byte_len()];
208    doc.render(&request, &mut rgba, cancel)?;
209    Ok((plan.tile.width, plan.tile.height, rgba))
210}
211
212fn encode(width: u32, height: u32, rgba: &[u8], options: &ExportOptions) -> Result<Vec<u8>, RenderError> {
213    let dpi = options.dpi;
214    match options.format {
215        ExportFormat::Png => encode_png(width, height, rgba, dpi),
216        ExportFormat::Jpeg { quality } => encode_jpeg(width, height, rgba, dpi, quality),
217        ExportFormat::Tiff { .. } => {
218            let mut tiff = TiffWriter::new()?;
219            tiff.add_page(width, height, rgba, dpi)?;
220            Ok(tiff.finish())
221        }
222    }
223}
224
225fn encode_failed(format: &'static str) -> RenderError {
226    RenderError::ExportFailed { format }
227}
228
229/// The metres in an inch.
230const METRES_PER_INCH: f64 = 0.0254;
231
232/// `dpi` as a whole number of dots per metre (PNG's unit).
233fn dots_per_metre(dpi: f64) -> u32 {
234    let dpm = (dpi / METRES_PER_INCH).round();
235    #[expect(
236        clippy::cast_possible_truncation,
237        clippy::cast_sign_loss,
238        reason = "clamped to u32's range first"
239    )]
240    let dpm = dpm.clamp(1.0, f64::from(u32::MAX)) as u32;
241    dpm
242}
243
244fn encode_png(width: u32, height: u32, rgba: &[u8], dpi: f64) -> Result<Vec<u8>, RenderError> {
245    let mut out = Vec::new();
246    let mut encoder = png::Encoder::new(&mut out, width, height);
247    encoder.set_color(png::ColorType::Rgba);
248    encoder.set_depth(png::BitDepth::Eight);
249    let dpm = dots_per_metre(dpi);
250    encoder.set_pixel_dims(Some(png::PixelDimensions {
251        xppu: dpm,
252        yppu: dpm,
253        unit: png::Unit::Meter,
254    }));
255    let mut writer = encoder.write_header().map_err(|_| encode_failed("png"))?;
256    writer.write_image_data(rgba).map_err(|_| encode_failed("png"))?;
257    writer.finish().map_err(|_| encode_failed("png"))?;
258    Ok(out)
259}
260
261fn encode_jpeg(width: u32, height: u32, rgba: &[u8], dpi: f64, quality: u8) -> Result<Vec<u8>, RenderError> {
262    const MAX_SIDE: u32 = 65_535;
263    let (Ok(w), Ok(h)) = (u16::try_from(width), u16::try_from(height)) else {
264        return Err(RenderError::TooLarge {
265            width: u64::from(width),
266            height: u64::from(height),
267            limit: u64::from(MAX_SIDE),
268            unit: "pixels per side",
269        });
270    };
271    let mut out = Vec::new();
272    let mut encoder = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
273    #[expect(
274        clippy::cast_possible_truncation,
275        clippy::cast_sign_loss,
276        reason = "clamped to u16's range first"
277    )]
278    let density = dpi.round().clamp(1.0, f64::from(u16::MAX)) as u16;
279    encoder.set_density(jpeg_encoder::PixelDensity {
280        density: (density, density),
281        unit: jpeg_encoder::PixelDensityUnit::Inches,
282    });
283    // The page was drawn on an opaque background, so alpha is 255 everywhere and is dropped.
284    encoder
285        .encode(rgba, w, h, jpeg_encoder::ColorType::Rgba)
286        .map_err(|_| encode_failed("jpeg"))?;
287    Ok(out)
288}