Skip to main content

rustium_pdf/
document.rs

1//! The document: catalog, page tree, and per-page access.
2
3use std::collections::HashSet;
4use std::path::Path;
5
6use crate::error::{Error, Result};
7use crate::geom::Rect;
8use crate::object::{Dict, Object};
9use crate::page::Page;
10use crate::parser::PdfFile;
11
12/// Attributes a page inherits from its ancestors when it lacks its own.
13#[derive(Clone, Default)]
14struct Inherited {
15    resources: Option<Object>,
16    media_box: Option<Rect>,
17    crop_box: Option<Rect>,
18    rotate: Option<i64>,
19}
20
21/// One leaf of the page tree, fully resolved.
22pub(crate) struct PageNode {
23    pub dict: Dict,
24    pub resources: Dict,
25    pub media_box: Rect,
26    pub crop_box: Rect,
27    /// Clockwise display rotation in degrees: 0, 90, 180 or 270.
28    pub rotation: i32,
29}
30
31/// An open PDF document.
32///
33/// `Document` is `Send + Sync`: internal caches are lock-guarded and there is no global state,
34/// so separate documents can be processed on separate threads freely — and a single document
35/// can be shared across threads too.
36pub struct Document {
37    pub(crate) file: PdfFile,
38    pages: Vec<PageNode>,
39}
40
41impl Document {
42    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
43        Self::open_with_password(path, None)
44    }
45
46    pub fn open_with_password(path: impl AsRef<Path>, password: Option<&str>) -> Result<Self> {
47        let data = std::fs::read(path)?;
48        Self::from_bytes(data, password)
49    }
50
51    pub fn from_bytes(data: Vec<u8>, password: Option<&str>) -> Result<Self> {
52        let file = PdfFile::load(data, password)?;
53        let pages = collect_pages(&file)?;
54        Ok(Self { file, pages })
55    }
56
57    pub fn page_count(&self) -> usize {
58        self.pages.len()
59    }
60
61    /// Loads one page and interprets its content streams into primitives.
62    pub fn page(&self, index: usize) -> Result<Page> {
63        let node = self.pages.get(index).ok_or(Error::PageOutOfRange(index))?;
64        Page::build(self, node, index)
65    }
66
67    pub(crate) fn resolve(&self, obj: &Object) -> Object {
68        self.file.resolve(obj)
69    }
70
71    /// Resolved value of `key` in `dict`.
72    pub(crate) fn dict_get(&self, dict: &Dict, key: &str) -> Option<Object> {
73        dict.get(key)
74            .map(|o| self.resolve(o))
75            .filter(|o| !o.is_null())
76    }
77}
78
79fn rect_from(obj: &Object) -> Option<Rect> {
80    let a = obj.as_array()?;
81    let v: Vec<f32> = a.iter().filter_map(|o| o.as_f32()).collect();
82    if v.len() < 4 {
83        return None;
84    }
85    let r = Rect::from_corners(v[0], v[1], v[2], v[3]);
86    (!r.is_empty()).then_some(r)
87}
88
89fn collect_pages(file: &PdfFile) -> Result<Vec<PageNode>> {
90    const MAX_PAGES: usize = 100_000;
91    const MAX_DEPTH: usize = 64;
92
93    let root = file
94        .trailer
95        .get("Root")
96        .map(|o| file.resolve(o))
97        .and_then(|o| o.as_dict().cloned())
98        .ok_or_else(|| Error::Parse("catalog missing".into()))?;
99    let pages_obj = root
100        .get("Pages")
101        .map(|o| file.resolve(o))
102        .ok_or_else(|| Error::Parse("catalog has no /Pages".into()))?;
103
104    let mut out = Vec::new();
105    let mut visited: HashSet<usize> = HashSet::new();
106
107    // Stack of (node, inherited, depth). Kids are pushed in reverse so page order is preserved.
108    let mut stack: Vec<(Object, Inherited, usize)> = vec![(pages_obj, Inherited::default(), 0)];
109    while let Some((node_ref, inherited, depth)) = stack.pop() {
110        if out.len() >= MAX_PAGES || depth > MAX_DEPTH {
111            break;
112        }
113        // Cycle guard keyed on object identity where available.
114        if let Object::Ref(r) = &node_ref {
115            if !visited.insert(r.num as usize) {
116                continue;
117            }
118        }
119        let node = file.resolve(&node_ref);
120        let Some(dict) = node.as_dict() else { continue };
121
122        let mut inh = inherited.clone();
123        if let Some(r) = dict.get("Resources") {
124            inh.resources = Some(r.clone());
125        }
126        if let Some(r) = dict.get("MediaBox").map(|o| file.resolve(o)) {
127            if let Some(rect) = rect_from(&r) {
128                inh.media_box = Some(rect);
129            }
130        }
131        if let Some(r) = dict.get("CropBox").map(|o| file.resolve(o)) {
132            if let Some(rect) = rect_from(&r) {
133                inh.crop_box = Some(rect);
134            }
135        }
136        if let Some(r) = dict
137            .get("Rotate")
138            .map(|o| file.resolve(o))
139            .and_then(|o| o.as_int())
140        {
141            inh.rotate = Some(r);
142        }
143
144        let ty = dict.get("Type").and_then(|o| o.as_name());
145        let kids = dict.get("Kids").map(|o| file.resolve(o));
146        match (ty, &kids) {
147            // Treat anything with /Kids as an internal node; some producers mislabel /Type.
148            (Some("Pages"), _) | (_, Some(Object::Array(_))) => {
149                if let Some(Object::Array(kids)) = kids {
150                    for kid in kids.iter().rev() {
151                        stack.push((kid.clone(), inh.clone(), depth + 1));
152                    }
153                }
154            }
155            _ => {
156                // A leaf. US Letter is the fallback of last resort for a missing MediaBox.
157                let media_box = inh
158                    .media_box
159                    .unwrap_or(Rect::from_corners(0.0, 0.0, 612.0, 792.0));
160                let crop_box = inh
161                    .crop_box
162                    .map(|c| {
163                        let i = c.intersect(&media_box);
164                        if i.is_empty() {
165                            media_box
166                        } else {
167                            i
168                        }
169                    })
170                    .unwrap_or(media_box);
171                let resources = inh
172                    .resources
173                    .as_ref()
174                    .map(|o| file.resolve(o))
175                    .and_then(|o| o.as_dict().cloned())
176                    .unwrap_or_default();
177                let rotation = inh.rotate.unwrap_or(0).rem_euclid(360) as i32;
178                let rotation = (rotation / 90) * 90; // Anything non-multiple is treated as 0/90/180/270 floor.
179                out.push(PageNode {
180                    dict: dict.clone(),
181                    resources,
182                    media_box,
183                    crop_box,
184                    rotation,
185                });
186            }
187        }
188    }
189    Ok(out)
190}
191
192/// Concatenates a page's content streams, newline-separated, decoded.
193pub(crate) fn page_content(doc: &Document, page: &Dict) -> Vec<u8> {
194    let Some(contents) = doc.dict_get(page, "Contents") else {
195        return Vec::new();
196    };
197    let mut out = Vec::new();
198    let mut push_stream = |obj: &Object| {
199        if let Some(stream) = doc.resolve(obj).as_stream() {
200            if let Ok(decoded) = doc.file.decode_stream(stream) {
201                if !out.is_empty() {
202                    out.push(b'\n');
203                }
204                out.extend_from_slice(&decoded.data);
205            }
206        }
207    };
208    match &contents {
209        Object::Array(items) => {
210            for item in items {
211                push_stream(item);
212            }
213        }
214        other => push_stream(other),
215    }
216    out
217}