Skip to main content

pdf2/
page.rs

1//! The document model: the page tree (§7.7.3) and XMP metadata (§14.3.2).
2//!
3//! The page tree is walked from the catalog's `/Pages` node. Attributes that
4//! the standard marks as inheritable — `/MediaBox`, `/CropBox`, `/Rotate` and
5//! `/Resources` — are carried down the walk and overridden where a node or page
6//! states its own value, which is what makes "per-page boxes" correct for files
7//! that state them once at the root.
8//!
9//! `/Count` is deliberately not trusted: it is a hint, and a wrong hint would
10//! silently hide pages. Pages are counted by walking the tree (§7.7.3.2 says a
11//! conforming reader shall not rely on `/Count`).
12
13use alloc::vec;
14use alloc::vec::Vec;
15
16use alloc::collections::BTreeSet;
17
18use crate::document::Document;
19use crate::error::{Error, Result};
20use crate::object::{Dictionary, Object, ObjectId};
21
22/// Deepest page tree accepted. Big documents nest a handful of levels; a
23/// hostile file must produce an error rather than a stack overflow.
24pub const MAX_PAGE_TREE_DEPTH: usize = 64;
25
26/// A rectangle in PDF user space: `[x0 y0 x1 y1]`.
27///
28/// Coordinates are normalised so that `x0 <= x1` and `y0 <= y1`, because
29/// writers disagree about the order of the corners.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct Rect {
32    /// Left edge.
33    pub x0: f64,
34    /// Bottom edge.
35    pub y0: f64,
36    /// Right edge.
37    pub x1: f64,
38    /// Top edge.
39    pub y1: f64,
40}
41
42impl Rect {
43    /// A rectangle from its four coordinates.
44    pub fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Self {
45        Self {
46            x0: if x0 <= x1 { x0 } else { x1 },
47            y0: if y0 <= y1 { y0 } else { y1 },
48            x1: if x1 >= x0 { x1 } else { x0 },
49            y1: if y1 >= y0 { y1 } else { y0 },
50        }
51    }
52
53    /// Width in user-space units.
54    pub fn width(&self) -> f64 {
55        self.x1 - self.x0
56    }
57
58    /// Height in user-space units.
59    pub fn height(&self) -> f64 {
60        self.y1 - self.y0
61    }
62
63    /// Read a box from a four-element array of numbers.
64    pub fn from_array(items: &[Object]) -> Result<Self> {
65        if items.len() != 4 {
66            return Err(Error::Malformed {
67                what: "a page box must be an array of four numbers",
68                offset: None,
69            });
70        }
71        let mut values = [0.0_f64; 4];
72        for (slot, item) in values.iter_mut().zip(items) {
73            *slot = match item {
74                Object::Integer(value) => *value as f64,
75                Object::Real(value) => *value,
76                _ => {
77                    return Err(Error::Malformed {
78                        what: "a page box must be an array of four numbers",
79                        offset: None,
80                    })
81                }
82            };
83        }
84        Ok(Self::new(values[0], values[1], values[2], values[3]))
85    }
86}
87
88/// One page, with every inheritable attribute already resolved.
89#[derive(Debug, Clone, PartialEq)]
90pub struct Page {
91    /// The page object's id, absent when the page dictionary sits directly in
92    /// its parent's `/Kids` array.
93    pub id: Option<ObjectId>,
94    /// Effective `/MediaBox`, required by the standard for every page.
95    pub media_box: Option<Rect>,
96    /// Effective `/CropBox`, which defaults to the media box.
97    pub crop_box: Option<Rect>,
98    /// Effective `/Rotate`, normalised to 0, 90, 180 or 270.
99    pub rotate: i64,
100    /// Effective `/Resources`.
101    pub resources: Option<Dictionary>,
102    /// Content stream ids, in the order they are painted.
103    pub contents: Vec<ObjectId>,
104}
105
106impl Page {
107    /// Whether this page's media box contains the point `(x, y)`.
108    pub fn contains(&self, x: f64, y: f64) -> bool {
109        match self.media_box {
110            Some(rect) => x >= rect.x0 && x <= rect.x1 && y >= rect.y0 && y <= rect.y1,
111            None => false,
112        }
113    }
114}
115
116/// Inheritable attributes carried down the page tree.
117#[derive(Debug, Clone, Default)]
118struct Inherited {
119    media_box: Option<Rect>,
120    crop_box: Option<Rect>,
121    rotate: i64,
122    resources: Option<Dictionary>,
123}
124
125impl Document {
126    /// The catalog dictionary.
127    pub fn catalog_dict(&self) -> Result<Dictionary> {
128        match self.catalog()? {
129            Object::Dictionary(dict) => Ok(dict),
130            _ => Err(Error::Malformed {
131                what: "catalog /Root is not a dictionary",
132                offset: None,
133            }),
134        }
135    }
136
137    /// Walk the page tree and return every page in document order.
138    pub fn pages(&self) -> Result<Vec<Page>> {
139        let catalog = self.catalog_dict()?;
140        let root = catalog.get(b"Pages").ok_or(Error::Malformed {
141            what: "catalog without /Pages",
142            offset: None,
143        })?;
144        let mut pages = Vec::new();
145        let mut visited = BTreeSet::new();
146        self.collect_pages(root, &Inherited::default(), 0, &mut visited, &mut pages)?;
147        Ok(pages)
148    }
149
150    /// Number of pages, counted by walking the tree rather than trusting
151    /// `/Count`.
152    pub fn page_count(&self) -> Result<usize> {
153        Ok(self.pages()?.len())
154    }
155
156    /// The page at `index`, counting from zero.
157    pub fn page(&self, index: usize) -> Result<Page> {
158        self.pages()?
159            .into_iter()
160            .nth(index)
161            .ok_or(Error::Malformed {
162                what: "page index is past the last page",
163                offset: None,
164            })
165    }
166
167    /// The decoded content of a page, with its streams joined by a newline.
168    ///
169    /// This is the input the content-stream interpreter takes.
170    pub fn page_content(&self, page: &Page) -> Result<Vec<u8>> {
171        let mut out = Vec::new();
172        for id in &page.contents {
173            let stream = self.stream_data(*id)?;
174            if !out.is_empty() {
175                out.push(b'\n');
176            }
177            out.extend_from_slice(&stream);
178        }
179        Ok(out)
180    }
181
182    /// Whether the catalog carries an XMP `/Metadata` stream.
183    pub fn has_metadata(&self) -> Result<bool> {
184        Ok(self.catalog_dict()?.contains_key(b"Metadata"))
185    }
186
187    /// The decoded XMP metadata packet, if the document has one.
188    pub fn metadata(&self) -> Result<Option<Vec<u8>>> {
189        let catalog = self.catalog_dict()?;
190        let Some(metadata) = catalog.get(b"Metadata") else {
191            return Ok(None);
192        };
193        match self.resolve(Some(metadata))? {
194            Some(Object::Stream(stream)) => Ok(Some(self.decode_stream(&stream)?)),
195            _ => Err(Error::Malformed {
196                what: "/Metadata must be a stream",
197                offset: None,
198            }),
199        }
200    }
201
202    fn collect_pages(
203        &self,
204        node: &Object,
205        inherited: &Inherited,
206        depth: usize,
207        visited: &mut BTreeSet<ObjectId>,
208        pages: &mut Vec<Page>,
209    ) -> Result<()> {
210        if depth > MAX_PAGE_TREE_DEPTH {
211            return Err(Error::Malformed {
212                what: "page tree is nested too deeply",
213                offset: None,
214            });
215        }
216        let (dict, id) = match node {
217            Object::Reference(id) => {
218                if !visited.insert(*id) {
219                    return Err(Error::Malformed {
220                        what: "page tree contains a cycle",
221                        offset: None,
222                    });
223                }
224                match self.get_object(*id)? {
225                    Object::Dictionary(dict) => (dict, Some(*id)),
226                    _ => {
227                        return Err(Error::Malformed {
228                            what: "page tree node is not a dictionary",
229                            offset: None,
230                        })
231                    }
232                }
233            }
234            Object::Dictionary(dict) => (dict.clone(), None),
235            _ => {
236                return Err(Error::Malformed {
237                    what: "page tree node is not a dictionary or reference",
238                    offset: None,
239                })
240            }
241        };
242
243        let inherited = Inherited {
244            media_box: self.box_of(&dict, b"MediaBox")?.or(inherited.media_box),
245            crop_box: self.box_of(&dict, b"CropBox")?.or(inherited.crop_box),
246            rotate: match dict.get(b"Rotate") {
247                Some(rotate) => normalise_rotate(rotate)?,
248                None => inherited.rotate,
249            },
250            resources: match dict.get(b"Resources") {
251                Some(resources) => Some(self.resources_of(resources)?),
252                None => inherited.resources.clone(),
253            },
254        };
255
256        if let Some(kids) = dict.get(b"Kids") {
257            // Only the array itself may be indirect: the entries stay
258            // references so that each page keeps its object id.
259            let kids = match kids {
260                Object::Array(items) => items.clone(),
261                Object::Reference(id) => match self.get_object(*id)? {
262                    Object::Array(items) => items,
263                    _ => {
264                        return Err(Error::Malformed {
265                            what: "/Kids must be an array",
266                            offset: None,
267                        })
268                    }
269                },
270                _ => {
271                    return Err(Error::Malformed {
272                        what: "/Kids must be an array",
273                        offset: None,
274                    })
275                }
276            };
277            for kid in &kids {
278                self.collect_pages(kid, &inherited, depth + 1, visited, pages)?;
279            }
280            return Ok(());
281        }
282
283        let is_page = matches!(
284            dict.get(b"Type").and_then(Object::as_name),
285            Some(name) if name == b"Page"
286        ) || dict.contains_key(b"MediaBox")
287            || inherited.media_box.is_some();
288        if !is_page {
289            return Err(Error::Malformed {
290                what: "page tree node has neither /Kids nor /Type /Page",
291                offset: None,
292            });
293        }
294        let crop_box = inherited.crop_box.or(inherited.media_box);
295        pages.push(Page {
296            id,
297            media_box: inherited.media_box,
298            crop_box,
299            rotate: inherited.rotate,
300            resources: inherited.resources,
301            contents: page_contents(&dict)?,
302        });
303        Ok(())
304    }
305
306    fn box_of(&self, dict: &Dictionary, key: &[u8]) -> Result<Option<Rect>> {
307        let Some(value) = dict.get(key) else {
308            return Ok(None);
309        };
310        let value = self.resolve(Some(value))?.unwrap_or(Object::Null);
311        match value {
312            Object::Array(items) => Rect::from_array(&items).map(Some),
313            _ => Err(Error::Malformed {
314                what: "a page box must be an array of four numbers",
315                offset: None,
316            }),
317        }
318    }
319
320    fn resources_of(&self, resources: &Object) -> Result<Dictionary> {
321        match self.resolve(Some(resources))?.unwrap_or(Object::Null) {
322            Object::Dictionary(dict) => Ok(dict),
323            _ => Err(Error::Malformed {
324                what: "/Resources must be a dictionary",
325                offset: None,
326            }),
327        }
328    }
329}
330
331/// `/Rotate` is a multiple of 90; normalise it into 0, 90, 180 or 270.
332fn normalise_rotate(value: &Object) -> Result<i64> {
333    let value = match value {
334        Object::Integer(value) => *value,
335        _ => {
336            return Err(Error::Malformed {
337                what: "/Rotate must be an integer",
338                offset: None,
339            })
340        }
341    };
342    if value % 90 != 0 {
343        return Err(Error::Malformed {
344            what: "/Rotate must be a multiple of 90",
345            offset: None,
346        });
347    }
348    Ok(((value % 360) + 360) % 360)
349}
350
351/// Content stream ids of a page: one reference or an array of references.
352fn page_contents(dict: &Dictionary) -> Result<Vec<ObjectId>> {
353    match dict.get(b"Contents") {
354        None | Some(Object::Null) => Ok(Vec::new()),
355        Some(Object::Reference(id)) => Ok(vec![*id]),
356        Some(Object::Array(items)) => {
357            let mut contents = Vec::with_capacity(items.len());
358            for item in items {
359                match item {
360                    Object::Reference(id) => contents.push(*id),
361                    _ => {
362                        return Err(Error::Malformed {
363                            what: "/Contents array entries must be stream references",
364                            offset: None,
365                        })
366                    }
367                }
368            }
369            Ok(contents)
370        }
371        Some(_) => Err(Error::Malformed {
372            what: "/Contents must be a stream reference or an array",
373            offset: None,
374        }),
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::{normalise_rotate, page_contents, Rect};
381    use crate::object::{Dictionary, Object, ObjectId};
382
383    #[test]
384    fn rectangles_normalise_their_corners() {
385        let rect = Rect::new(10.0, 20.0, 0.0, 0.0);
386        assert_eq!(
387            rect,
388            Rect {
389                x0: 0.0,
390                y0: 0.0,
391                x1: 10.0,
392                y1: 20.0
393            }
394        );
395        assert_eq!(rect.width(), 10.0);
396        assert_eq!(rect.height(), 20.0);
397    }
398
399    #[test]
400    fn rectangles_read_integer_and_real_arrays() {
401        let rect = Rect::from_array(&[
402            Object::Integer(0),
403            Object::Integer(0),
404            Object::Real(612.5),
405            Object::Integer(792),
406        ])
407        .expect("rectangle");
408        assert_eq!(rect.x1, 612.5);
409        assert_eq!(rect.y1, 792.0);
410    }
411
412    #[test]
413    fn malformed_rectangles_are_errors() {
414        assert!(Rect::from_array(&[Object::Integer(0), Object::Integer(0)]).is_err());
415        assert!(Rect::from_array(&[
416            Object::Integer(0),
417            Object::Integer(0),
418            Object::Integer(1),
419            Object::name("top"),
420        ])
421        .is_err());
422    }
423
424    #[test]
425    fn rotations_are_normalised() {
426        assert_eq!(normalise_rotate(&Object::Integer(0)).expect("0"), 0);
427        assert_eq!(normalise_rotate(&Object::Integer(90)).expect("90"), 90);
428        assert_eq!(normalise_rotate(&Object::Integer(450)).expect("450"), 90);
429        assert_eq!(normalise_rotate(&Object::Integer(-90)).expect("-90"), 270);
430        assert_eq!(normalise_rotate(&Object::Integer(360)).expect("360"), 0);
431        assert!(normalise_rotate(&Object::Integer(45)).is_err());
432        assert!(normalise_rotate(&Object::Real(90.0)).is_err());
433    }
434
435    #[test]
436    fn contents_accept_one_reference_or_an_array() {
437        let mut dict = Dictionary::new();
438        assert!(page_contents(&dict).expect("absent").is_empty());
439
440        dict.insert("Contents", Object::reference(ObjectId::new(4, 0)));
441        assert_eq!(
442            page_contents(&dict).expect("single"),
443            vec![ObjectId::new(4, 0)]
444        );
445
446        dict.insert(
447            "Contents",
448            Object::array([
449                Object::reference(ObjectId::new(4, 0)),
450                Object::reference(ObjectId::new(5, 0)),
451            ]),
452        );
453        assert_eq!(
454            page_contents(&dict).expect("array"),
455            vec![ObjectId::new(4, 0), ObjectId::new(5, 0)]
456        );
457
458        dict.insert("Contents", Object::Integer(1));
459        assert!(page_contents(&dict).is_err());
460    }
461}