1use crate::PdfError;
2use crate::lopdf_document::Document;
3
4pub struct PdfDocument(pub(crate) Document);
8
9#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct PageSize {
13 pub width_pt: f32,
14 pub height_pt: f32,
15}
16
17#[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 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 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 pub fn page_count(&self) -> u32 {
46 self.0.get_pages().len() as u32
47 }
48
49 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 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 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}