Skip to main content

cellix_doc/
pdf.rs

1//! A PDF's pages as pixels, from pure Rust, so a paper shows beside its source on any host.
2
3use std::sync::Arc;
4
5use hayro::hayro_interpret::InterpreterSettings;
6use hayro::hayro_syntax::Pdf;
7use hayro::vello_cpu::color::palette::css::WHITE;
8use hayro::{PixmapSettings, RenderCache, RenderSettings, render};
9
10/// One page, as straight RGBA.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Page {
13    pub width: u32,
14    pub height: u32,
15    pub rgba: Arc<Vec<u8>>,
16}
17
18/// An open PDF. Its pages render on demand.
19pub struct Document {
20    pdf: Pdf,
21}
22
23impl Document {
24    pub fn open(bytes: Vec<u8>) -> Result<Self, String> {
25        let pdf = Pdf::new(bytes).map_err(|e| format!("{e:?}"))?;
26        Ok(Self { pdf })
27    }
28
29    pub fn pages(&self) -> usize {
30        self.pdf.pages().len()
31    }
32
33    /// A page as (width, height) in points.
34    pub fn size(&self, page: usize) -> Option<(f32, f32)> {
35        let (width, height) = self.pdf.pages().get(page)?.render_dimensions();
36        Some((width, height))
37    }
38
39    /// Draws a page at `scale` pixels to the point, or smaller if that would pass `max_width`.
40    pub fn render_at(&self, page: usize, scale: f32, max_width: u32) -> Option<Page> {
41        let (width, _) = self.size(page)?;
42        self.render(page, ((width * scale) as u32).clamp(1, max_width.max(1)))
43    }
44
45    /// Draws a page `width` pixels wide.
46    pub fn render(&self, page: usize, width: u32) -> Option<Page> {
47        let pages = self.pdf.pages();
48        let page = pages.get(page)?;
49        let (natural, _) = page.render_dimensions();
50        let scale = width as f32 / natural.max(1.0);
51        let pixmap = render(
52            page,
53            &RenderCache::new(),
54            &InterpreterSettings::default(),
55            &RenderSettings::default(),
56            &PixmapSettings {
57                x_scale: scale,
58                y_scale: scale,
59                bg_color: WHITE,
60            },
61        );
62        let (width, height) = (pixmap.width() as u32, pixmap.height() as u32);
63        // A white background leaves nothing see-through, so premultiplying changed nothing.
64        let rgba = pixmap.data_as_u8_slice().to_vec();
65        Some(Page {
66            width,
67            height,
68            rgba: Arc::new(rgba),
69        })
70    }
71}
72
73/// The smallest PDF that shows something, for tests.
74#[cfg(any(test, feature = "fixtures"))]
75pub fn sample() -> Vec<u8> {
76    let objects = [
77        "<< /Type /Catalog /Pages 2 0 R >>",
78        "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
79        "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Contents 4 0 R >>",
80    ];
81    let stream = "0 0 1 rg 20 20 100 100 re f";
82    let mut pdf = String::from("%PDF-1.4\n");
83    let mut offsets = Vec::new();
84    for (index, object) in objects.iter().enumerate() {
85        offsets.push(pdf.len());
86        pdf.push_str(&format!("{} 0 obj\n{object}\nendobj\n", index + 1));
87    }
88    offsets.push(pdf.len());
89    pdf.push_str(&format!(
90        "4 0 obj\n<< /Length {} >>\nstream\n{stream}\nendstream\nendobj\n",
91        stream.len()
92    ));
93    let table = pdf.len();
94    pdf.push_str("xref\n0 5\n0000000000 65535 f \n");
95    for offset in &offsets {
96        pdf.push_str(&format!("{offset:010} 00000 n \n"));
97    }
98    pdf.push_str(&format!(
99        "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{table}\n%%EOF\n"
100    ));
101    pdf.into_bytes()
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn a_page_comes_out_as_pixels() {
110        let document = Document::open(sample()).unwrap();
111        assert_eq!(document.pages(), 1);
112        assert_eq!(document.size(0), Some((200.0, 300.0)));
113        let page = document.render(0, 400).unwrap();
114        assert_eq!((page.width, page.height), (400, 600));
115        assert_eq!(page.rgba.len(), 400 * 600 * 4);
116        let at = |x: usize, y: usize| {
117            let i = (y * 400 + x) * 4;
118            (page.rgba[i], page.rgba[i + 1], page.rgba[i + 2])
119        };
120        assert_eq!(at(10, 10), (255, 255, 255), "paper");
121        assert_eq!(
122            at(100, 500),
123            (0, 0, 255),
124            "and the square on it, at the bottom"
125        );
126    }
127
128    #[test]
129    fn nonsense_is_an_error() {
130        assert!(Document::open(b"not a pdf".to_vec()).is_err());
131    }
132}