rusty_pdf_core 0.2.1

Pure-Rust PDF reader core: objects, classic and stream cross-reference tables, object streams, incremental updates, broken-xref repair, RC4 and AES-128/256 decryption, stream filters, page tree, content streams, editing and save. Hostile input errors or stays bounded. No C, no unsafe.
Documentation
//! The page tree and pages.

use crate::content::{Content, Operation};
use crate::document::Document;
use crate::error::{Error, Result};
use crate::object::{Dictionary, Object, ObjectId};
use std::collections::BTreeSet;

/// A rectangle in default user space, normalised so that `x0 <= x1` and
/// `y0 <= y1`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
    /// Left edge.
    pub x0: f64,
    /// Bottom edge.
    pub y0: f64,
    /// Right edge.
    pub x1: f64,
    /// Top edge.
    pub y1: f64,
}

impl Rect {
    /// US Letter, what readers assume when a page has no usable `/MediaBox`.
    pub const LETTER: Self = Self { x0: 0.0, y0: 0.0, x1: 612.0, y1: 792.0 };

    /// From two opposite corners, in any order.
    #[must_use]
    pub fn new(xa: f64, ya: f64, xb: f64, yb: f64) -> Self {
        Self { x0: xa.min(xb), y0: ya.min(yb), x1: xa.max(xb), y1: ya.max(yb) }
    }

    /// Width.
    #[must_use]
    pub fn width(&self) -> f64 {
        self.x1 - self.x0
    }

    /// Height.
    #[must_use]
    pub fn height(&self) -> f64 {
        self.y1 - self.y0
    }

    /// The part of `self` inside `other`, if any.
    #[must_use]
    pub fn intersect(&self, other: &Self) -> Option<Self> {
        let r = Self {
            x0: self.x0.max(other.x0),
            y0: self.y0.max(other.y0),
            x1: self.x1.min(other.x1),
            y1: self.y1.min(other.y1),
        };
        (r.x0 < r.x1 && r.y0 < r.y1).then_some(r)
    }
}

/// Walk the page tree from the catalog, left to right.
pub(crate) fn collect_pages(doc: &Document) -> Result<Vec<ObjectId>> {
    let limit = doc.limits.max_pages;
    let mut pages = Vec::new();
    let mut visited = BTreeSet::new();
    let mut stack: Vec<ObjectId> = Vec::new();
    if let Some(Object::Reference(root)) = doc.catalog()?.get(b"Pages") {
        stack.push(*root);
    }
    // Depth-first with an explicit stack: page trees in the wild include
    // degenerate ones thousands of levels deep, and hostile ones that loop.
    while let Some(id) = stack.pop() {
        if !visited.insert(id.0) {
            continue;
        }
        let Ok(dict) = doc.get_dictionary(id) else { continue };
        let kids = doc.lookup(dict, b"Kids")?;
        match kids {
            Object::Array(kids) if !dict.is_type(b"Page") => {
                stack.extend(kids.iter().rev().filter_map(|k| k.as_reference().ok()));
            }
            _ => {
                if pages.len() >= limit {
                    return Err(Error::Limit { what: "page count", limit: limit as u64 });
                }
                pages.push(id);
            }
        }
    }
    if pages.is_empty() {
        // No usable tree. Any object that says it is a page is one, in
        // object order: what other readers recover in this state.
        for id in doc.object_ids() {
            if doc.get_object(id).is_ok_and(|o| o.as_dict().is_ok_and(|d| d.is_type(b"Page"))) {
                if pages.len() >= limit {
                    return Err(Error::Limit { what: "page count", limit: limit as u64 });
                }
                pages.push(id);
            }
        }
    }
    Ok(pages)
}

/// One page of a [`Document`].
#[derive(Debug, Clone, Copy)]
pub struct Page<'a> {
    doc: &'a Document,
    id: ObjectId,
    dict: &'a Dictionary,
}

impl<'a> Page<'a> {
    pub(crate) fn new(doc: &'a Document, id: ObjectId) -> Result<Self> {
        Ok(Self { doc, id, dict: doc.get_dictionary(id)? })
    }

    /// The page object's id.
    #[must_use]
    pub const fn id(&self) -> ObjectId {
        self.id
    }

    /// The page dictionary.
    #[must_use]
    pub const fn dict(&self) -> &'a Dictionary {
        self.dict
    }

    /// The document this page belongs to.
    #[must_use]
    pub const fn document(&self) -> &'a Document {
        self.doc
    }

    /// An attribute of the page, resolved, looked up through `/Parent` when
    /// the page itself lacks it (`/Resources`, `/MediaBox`, `/CropBox` and
    /// `/Rotate` are inheritable).
    #[must_use]
    pub fn attribute(&self, key: &[u8]) -> Option<&'a Object> {
        let mut dict = self.dict;
        for _ in 0..=self.doc.limits.max_page_tree_depth {
            match self.doc.lookup(dict, key) {
                Ok(Object::Null) | Err(_) => {}
                Ok(o) => return Some(o),
            }
            dict = self.doc.lookup_dict(dict, b"Parent")?;
        }
        None
    }

    fn rect(&self, key: &[u8]) -> Option<Rect> {
        let a = self.attribute(key)?.as_array().ok()?;
        let mut v = [0.0f64; 4];
        for (slot, o) in v.iter_mut().zip(a) {
            *slot = self.doc.resolve(o).ok()?.as_f64().ok()?;
        }
        (a.len() >= 4 && v.iter().all(|x| x.is_finite())).then(|| Rect::new(v[0], v[1], v[2], v[3]))
    }

    /// The media box. A page with none, or an empty or unreadable one, gets
    /// US Letter, as in other readers.
    #[must_use]
    pub fn media_box(&self) -> Rect {
        self.rect(b"MediaBox")
            .filter(|r| r.width() > 0.0 && r.height() > 0.0)
            .unwrap_or(Rect::LETTER)
    }

    /// The crop box: the visible region, clipped to the media box. Defaults
    /// to the media box.
    #[must_use]
    pub fn crop_box(&self) -> Rect {
        let media = self.media_box();
        self.rect(b"CropBox").and_then(|c| c.intersect(&media)).unwrap_or(media)
    }

    /// Clockwise rotation for display: 0, 90, 180 or 270.
    #[must_use]
    pub fn rotate(&self) -> u16 {
        let r = self.attribute(b"Rotate").and_then(|o| o.as_i64().ok()).unwrap_or(0);
        // rem_euclid(360) is 0..=359; a value that is not a multiple of 90
        // rounds down.
        u16::try_from(r.rem_euclid(360) / 90 * 90).unwrap_or(0)
    }

    /// Size of a user-space unit in 1/72 inch. Default 1.
    #[must_use]
    pub fn user_unit(&self) -> f64 {
        self.dict
            .get(b"UserUnit")
            .and_then(|o| self.doc.resolve(o).ok())
            .and_then(|o| o.as_f64().ok())
            .filter(|u| u.is_finite() && *u > 0.0)
            .unwrap_or(1.0)
    }

    /// The page's resource dictionary (inherited if need be).
    #[must_use]
    pub fn resources(&self) -> Option<&'a Dictionary> {
        self.attribute(b"Resources").and_then(|o| o.as_dict().ok())
    }

    /// The page's content streams, decoded and joined, at most `max` bytes.
    /// A page with no `/Contents` has empty content.
    ///
    /// Damaged stream data is an error here. A caller that would rather draw
    /// part of a page than none uses
    /// [`content_lenient`](Self::content_lenient).
    pub fn content(&self, max: usize) -> Result<Vec<u8>> {
        let (data, complete) = self.content_lenient(max)?;
        if complete {
            Ok(data)
        } else {
            Err(Error::Filter {
                filter: "page content".into(),
                message: "encoded data is damaged or ends early".into(),
            })
        }
    }

    /// Like [`content`](Self::content), but damaged stream data yields what
    /// could be decoded, with `false` for "not complete".
    pub fn content_lenient(&self, max: usize) -> Result<(Vec<u8>, bool)> {
        let contents = self.doc.lookup(self.dict, b"Contents")?;
        // One stream (the common case): its decoded buffer is the content,
        // with the separator appended, and nothing is copied into a join.
        let single = match contents {
            Object::Array(parts) if parts.len() == 1 => Some(&parts[0]),
            Object::Array(_) => None,
            other => Some(other),
        };
        if let Some(part) = single {
            return match self.doc.resolve(part)? {
                Object::Stream(s) => {
                    let (mut data, complete) = self.doc.decode_stream_lenient(s, max)?;
                    if data.len() < max {
                        data.push(b'\n');
                    }
                    Ok((data, complete))
                }
                _ => Ok((Vec::new(), true)),
            };
        }
        let mut out = Vec::new();
        let mut complete = true;
        let mut append = |o: &Object| -> Result<()> {
            let Object::Stream(s) = self.doc.resolve(o)? else {
                return Ok(());
            };
            let (data, whole) = self.doc.decode_stream_lenient(s, max - out.len())?;
            complete &= whole;
            out.extend_from_slice(&data);
            // The streams of a page are one stream split at token
            // boundaries; a separator keeps the last token of one from
            // fusing with the first of the next.
            if out.len() < max {
                out.push(b'\n');
            }
            Ok(())
        };
        match contents {
            Object::Array(parts) => {
                for part in parts {
                    append(part)?;
                }
            }
            other => append(other)?,
        }
        Ok((out, complete))
    }

    /// The page's content as operations. The content is bounded by
    /// [`Limits::max_stream_bytes`](crate::Limits::max_stream_bytes).
    pub fn operations(&self) -> Result<Vec<Operation>> {
        let data = self.content(self.doc.limits.max_stream_bytes)?;
        Ok(Content::parse_with(&data, &self.doc.limits)?.operations)
    }

    /// The page's annotation dictionaries, whether `/Annots` lists them by
    /// reference or holds them inline. An entry that is not a dictionary is
    /// an error: skipping an annotation that cannot be read would be
    /// skipping, for instance, a redaction.
    pub fn annotations(&self) -> Result<Vec<&'a Dictionary>> {
        match self.doc.lookup(self.dict, b"Annots")? {
            Object::Null => Ok(Vec::new()),
            Object::Array(items) => items
                .iter()
                .map(|item| {
                    self.doc
                        .resolve(item)?
                        .as_dict()
                        .map_err(|_| Error::Page("an annotation is not a dictionary".into()))
                })
                .collect(),
            _ => Err(Error::Page("/Annots is not an array".into())),
        }
    }
}