Skip to main content

pdf_forms/
document.rs

1use crate::PdfError;
2use crate::lopdf_document::Document;
3
4/// A parsed PDF document. All pdf-forms operations work through this type.
5///
6/// lopdf's `Document` is never exposed in the public API.
7pub struct PdfDocument(pub(crate) Document);
8
9/// Page dimensions in PDF user units (points; 1pt = 1/72 inch).
10/// Origin is at the bottom-left of the page.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct PageSize {
13    pub width_pt: f32,
14    pub height_pt: f32,
15}
16
17/// An axis-aligned rectangle in PDF user units.
18/// Origin is at the bottom-left of the page.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct Rect {
21    pub x: f32,
22    pub y: f32,
23    pub width: f32,
24    pub height: f32,
25}
26
27impl PdfDocument {
28    /// Parse a PDF from raw bytes.
29    pub fn open(bytes: impl AsRef<[u8]>) -> Result<Self, PdfError> {
30        Document::load_mem(bytes.as_ref())
31            .map(PdfDocument)
32            .map_err(|e| PdfError::Parse(e.to_string()))
33    }
34
35    /// Serialize the document back to bytes.
36    pub fn to_bytes(&mut self) -> Result<Vec<u8>, PdfError> {
37        let mut out = Vec::new();
38        self.0
39            .save_to(&mut out)
40            .map_err(|e| PdfError::Serialize(e.to_string()))?;
41        Ok(out)
42    }
43
44    /// Number of pages in the document (1-based count).
45    pub fn page_count(&self) -> u32 {
46        self.0.get_pages().len() as u32
47    }
48
49    /// Dimensions of the given page (1-based page number).
50    ///
51    /// Resolves the MediaBox by walking the Parent chain (depth-capped at 32)
52    /// before falling back to an error. Correct for multi-page PDFs where the
53    /// MediaBox lives on the page tree root node.
54    pub fn page_size(&self, page: u32) -> Result<PageSize, PdfError> {
55        let pages = self.0.get_pages();
56        let page_id = pages
57            .get(&page)
58            .copied()
59            .ok_or(PdfError::PageNotFound(page))?;
60
61        // Walk up the page tree to find MediaBox (depth-capped at 32)
62        let mut current_id = page_id;
63        for _ in 0..32 {
64            let obj = self
65                .0
66                .get_object(current_id)
67                .map_err(|e| PdfError::Internal(e.to_string()))?;
68            let dict = obj
69                .as_dict()
70                .map_err(|e| PdfError::Internal(e.to_string()))?;
71
72            if let Ok(media_box) = dict.get(b"MediaBox") {
73                let arr = media_box
74                    .as_array()
75                    .map_err(|e| PdfError::Internal(e.to_string()))?;
76                if arr.len() == 4 {
77                    let w = arr[2].as_float().unwrap_or(0.0) - arr[0].as_float().unwrap_or(0.0);
78                    let h = arr[3].as_float().unwrap_or(0.0) - arr[1].as_float().unwrap_or(0.0);
79                    return Ok(PageSize {
80                        width_pt: w,
81                        height_pt: h,
82                    });
83                }
84            }
85
86            // Climb to parent
87            match dict.get(b"Parent").and_then(|o| o.as_reference()) {
88                Ok(parent_id) => current_id = parent_id,
89                Err(_) => break,
90            }
91        }
92
93        Err(PdfError::Internal(format!(
94            "page {page}: no MediaBox found in page tree"
95        )))
96    }
97}