laminapdf_render/
tiff_writer.rs1use std::cell::RefCell;
6use std::io::{self, Cursor, Seek, SeekFrom, Write};
7use std::rc::Rc;
8
9use tiff::encoder::{Compression, DeflateLevel, Rational, TiffEncoder, colortype::RGBA8};
10use tiff::tags::ResolutionUnit;
11
12use crate::RenderError;
13
14#[derive(Clone, Default)]
17struct Shared(Rc<RefCell<Cursor<Vec<u8>>>>);
18
19impl Write for Shared {
20 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
21 self.0.borrow_mut().write(buf)
22 }
23
24 fn flush(&mut self) -> io::Result<()> {
25 Ok(())
26 }
27}
28
29impl Seek for Shared {
30 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
31 self.0.borrow_mut().seek(pos)
32 }
33}
34
35pub struct TiffWriter {
52 encoder: TiffEncoder<Shared>,
53 file: Shared,
54}
55
56impl std::fmt::Debug for TiffWriter {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 f.debug_struct("TiffWriter")
59 .field("bytes", &self.file.0.borrow().get_ref().len())
60 .finish_non_exhaustive()
61 }
62}
63
64impl TiffWriter {
65 pub fn new() -> Result<Self, RenderError> {
72 let file = Shared::default();
73 let encoder = TiffEncoder::new(file.clone())
74 .map_err(|_| failed())?
75 .with_compression(Compression::Deflate(DeflateLevel::Balanced));
76 Ok(Self { encoder, file })
77 }
78
79 pub fn add_page(&mut self, width: u32, height: u32, rgba: &[u8], dpi: f64) -> Result<(), RenderError> {
87 let expected = u64::from(width) * u64::from(height) * 4;
88 if width == 0 || height == 0 || rgba.len() as u64 != expected {
89 return Err(RenderError::InvalidRequest {
90 what: "a TIFF page's pixels must be width × height × 4 bytes of RGBA",
91 });
92 }
93 if !dpi.is_finite() || dpi <= 0.0 {
94 return Err(RenderError::InvalidRequest {
95 what: "a TIFF page's resolution must be a positive number of pixels per inch",
96 });
97 }
98 let mut image = self.encoder.new_image::<RGBA8>(width, height).map_err(|_| failed())?;
99 #[expect(
101 clippy::cast_possible_truncation,
102 clippy::cast_sign_loss,
103 reason = "clamped to u32's range first"
104 )]
105 let hundredths = (dpi * 100.0).round().clamp(1.0, f64::from(u32::MAX)) as u32;
106 image.resolution(ResolutionUnit::Inch, Rational { n: hundredths, d: 100 });
107 image.write_data(rgba).map_err(|_| failed())
108 }
109
110 #[must_use]
114 pub fn finish(self) -> Vec<u8> {
115 let Self { encoder, file } = self;
116 drop(encoder);
119 match Rc::try_unwrap(file.0) {
120 Ok(cell) => cell.into_inner().into_inner(),
121 Err(shared) => shared.borrow().get_ref().clone(),
122 }
123 }
124}
125
126fn failed() -> RenderError {
127 RenderError::ExportFailed { format: "tiff" }
128}