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