use std::collections::HashSet;
use crate::document::Document;
use crate::graph::ObjectGraph;
use crate::object::{Dict, ObjId, Object};
use crate::view::DocumentView;
pub const MAX_TREE_DEPTH: usize = 64;
pub const MAX_PAGES: usize = 1_000_000;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
pub llx: f64,
pub lly: f64,
pub urx: f64,
pub ury: f64,
}
impl Rect {
#[must_use]
pub fn from_corners(x1: f64, y1: f64, x2: f64, y2: f64) -> Self {
Self {
llx: x1.min(x2),
lly: y1.min(y2),
urx: x1.max(x2),
ury: y1.max(y2),
}
}
#[must_use]
pub fn width(&self) -> f64 {
self.urx - self.llx
}
#[must_use]
pub fn height(&self) -> f64 {
self.ury - self.lly
}
#[must_use]
pub fn contains(&self, other: &Self) -> bool {
other.llx >= self.llx
&& other.lly >= self.lly
&& other.urx <= self.urx
&& other.ury <= self.ury
}
#[must_use]
pub fn intersection(&self, other: &Self) -> Option<Self> {
let r = Self {
llx: self.llx.max(other.llx),
lly: self.lly.max(other.lly),
urx: self.urx.min(other.urx),
ury: self.ury.min(other.ury),
};
(r.urx > r.llx && r.ury > r.lly).then_some(r)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum BoxResolution {
#[default]
Defaulted,
AsWritten,
Clipped,
Unusable,
}
#[derive(Debug, Clone)]
pub struct Page {
pub id: ObjId,
pub resources: Dict,
pub resources_defaulted: bool,
pub media_box: Rect,
pub crop_box: Rect,
pub crop_box_resolution: BoxResolution,
pub bleed_box: Rect,
pub bleed_box_resolution: BoxResolution,
pub trim_box: Rect,
pub trim_box_resolution: BoxResolution,
pub art_box: Rect,
pub art_box_resolution: BoxResolution,
pub rotate: u16,
pub contents: Vec<ObjId>,
pub contents_unresolved: usize,
pub contents_flattened: usize,
}
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PageTreeError {
#[error("catalog /Pages missing or not a dictionary")]
NoPageTreeRoot,
#[error("page tree kid is not a dictionary (object {0})")]
BadKid(ObjId),
#[error("page tree cycle at object {0}")]
Cycle(ObjId),
#[error("page tree exceeds MAX_TREE_DEPTH ({MAX_TREE_DEPTH})")]
TooDeep,
#[error("page tree exceeds MAX_PAGES ({MAX_PAGES})")]
TooManyPages,
#[error("required page attribute {0} missing on page and all ancestors")]
MissingRequired(&'static str),
#[error("page /Resources is not a dictionary")]
BadResources,
#[error("malformed rectangle in page attribute {0}")]
BadRectangle(&'static str),
#[error("page /Rotate value {0} is not a multiple of 90")]
BadRotate(i64),
#[error("page /Contents is neither a stream nor an array of streams")]
BadContents,
}
#[derive(Clone, Default)]
struct Inherited<'a> {
resources: Option<&'a Object>,
media_box: Option<&'a Object>,
crop_box: Option<&'a Object>,
rotate: Option<&'a Object>,
}
pub fn pages(doc: &Document) -> Result<Vec<Page>, PageTreeError> {
pages_in(doc)
}
pub fn pages_in<G: ObjectGraph + ?Sized>(graph: &G) -> Result<Vec<Page>, PageTreeError> {
let catalog = graph.catalog_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
let root_obj = catalog
.get(b"Pages")
.map(|o| graph.resolve(o))
.ok_or(PageTreeError::NoPageTreeRoot)?;
let root = root_obj.as_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
let root_id = catalog.get(b"Pages").and_then(Object::as_reference);
let mut out = Vec::new();
let mut visited: HashSet<ObjId> = root_id.into_iter().collect();
walk(graph, root, Inherited::default(), 0, &mut visited, &mut out)?;
Ok(out)
}
#[derive(Debug, Clone)]
pub struct PageSlot {
pub id: ObjId,
pub parent: Option<ObjId>,
pub index_in_parent: usize,
pub ancestors: Vec<ObjId>,
pub inherited: InheritedRaw,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InheritedRaw {
pub resources: Option<Object>,
pub media_box: Option<Object>,
pub crop_box: Option<Object>,
pub rotate: Option<Object>,
}
impl InheritedRaw {
#[must_use]
pub fn materialize_for(&self, page: &Dict) -> Vec<(&'static [u8], Object)> {
let mut out = Vec::new();
for (key, value) in [
(&b"Resources"[..], &self.resources),
(&b"MediaBox"[..], &self.media_box),
(&b"CropBox"[..], &self.crop_box),
(&b"Rotate"[..], &self.rotate),
] {
if let Some(v) = value
&& !page.contains_key(key)
{
out.push((key, v.clone()));
}
}
out
}
}
pub fn page_slots<G: ObjectGraph + ?Sized>(graph: &G) -> Result<Vec<PageSlot>, PageTreeError> {
let catalog = graph.catalog_dict().ok_or(PageTreeError::NoPageTreeRoot)?;
let root_id = catalog
.get(b"Pages")
.and_then(Object::as_reference)
.ok_or(PageTreeError::NoPageTreeRoot)?;
let root = graph
.resolved(root_id)
.as_dict()
.ok_or(PageTreeError::NoPageTreeRoot)?;
let mut out = Vec::new();
let mut visited: HashSet<ObjId> = [root_id].into_iter().collect();
walk_slots(
graph,
root_id,
root,
&InheritedRaw::default(),
&[],
0,
&mut visited,
&mut out,
)?;
Ok(out)
}
#[allow(clippy::too_many_arguments)] fn walk_slots<G: ObjectGraph + ?Sized>(
graph: &G,
node_id: ObjId,
node: &Dict,
inherited: &InheritedRaw,
ancestors: &[ObjId],
depth: usize,
visited: &mut HashSet<ObjId>,
out: &mut Vec<PageSlot>,
) -> Result<(), PageTreeError> {
if depth > MAX_TREE_DEPTH {
return Err(PageTreeError::TooDeep);
}
let here = InheritedRaw {
resources: node
.get(b"Resources")
.cloned()
.or_else(|| inherited.resources.clone()),
media_box: node
.get(b"MediaBox")
.cloned()
.or_else(|| inherited.media_box.clone()),
crop_box: node
.get(b"CropBox")
.cloned()
.or_else(|| inherited.crop_box.clone()),
rotate: node
.get(b"Rotate")
.cloned()
.or_else(|| inherited.rotate.clone()),
};
let mut chain = ancestors.to_vec();
chain.push(node_id);
let Some(kids) = node
.get(b"Kids")
.map(|o| graph.resolve(o))
.and_then(Object::as_array)
else {
return Err(PageTreeError::NoPageTreeRoot);
};
for (index, kid) in kids.iter().enumerate() {
let Some(kid_id) = kid.as_reference() else {
return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
};
if !visited.insert(kid_id) {
return Err(PageTreeError::Cycle(kid_id));
}
let Some(kid_dict) = graph.resolved(kid_id).as_dict() else {
return Err(PageTreeError::BadKid(kid_id));
};
if is_pages_node(graph, kid_dict) {
walk_slots(
graph,
kid_id,
kid_dict,
&here,
&chain,
depth + 1,
visited,
out,
)?;
} else {
if out.len() >= MAX_PAGES {
return Err(PageTreeError::TooManyPages);
}
out.push(PageSlot {
id: kid_id,
parent: Some(node_id),
index_in_parent: index,
ancestors: chain.clone(),
inherited: here.clone(),
});
}
}
Ok(())
}
fn is_pages_node<G: ObjectGraph + ?Sized>(graph: &G, node: &Dict) -> bool {
match node
.get(b"Type")
.map(|o| graph.resolve(o))
.and_then(Object::as_name)
.map(crate::object::Name::as_bytes)
{
Some(b"Pages") => true,
Some(b"Page") => false,
_ => node.contains_key(b"Kids"),
}
}
fn walk<'a, G: ObjectGraph + ?Sized>(
doc: &'a G,
node: &'a Dict,
inherited: Inherited<'a>,
depth: usize,
visited: &mut HashSet<ObjId>,
out: &mut Vec<Page>,
) -> Result<(), PageTreeError> {
if depth > MAX_TREE_DEPTH {
return Err(PageTreeError::TooDeep);
}
let inherited = Inherited {
resources: node.get(b"Resources").or(inherited.resources),
media_box: node.get(b"MediaBox").or(inherited.media_box),
crop_box: node.get(b"CropBox").or(inherited.crop_box),
rotate: node.get(b"Rotate").or(inherited.rotate),
};
let type_name = node
.get(b"Type")
.map(|o| doc.resolve(o))
.and_then(Object::as_name)
.map(crate::object::Name::as_bytes);
let is_pages_node = match type_name {
Some(b"Pages") => true,
Some(b"Page") => false,
_ => node.contains_key(b"Kids"),
};
if !is_pages_node {
return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
}
let kids = node
.get(b"Kids")
.map(|o| doc.resolve(o))
.and_then(Object::as_array)
.ok_or(PageTreeError::NoPageTreeRoot)?;
for kid in kids {
let Some(kid_id) = kid.as_reference() else {
return Err(PageTreeError::BadKid(ObjId::new(0, 0)));
};
if !visited.insert(kid_id) {
return Err(PageTreeError::Cycle(kid_id));
}
let Some(kid_dict) = doc.resolve(kid).as_dict() else {
return Err(PageTreeError::BadKid(kid_id));
};
let kid_type = kid_dict
.get(b"Type")
.map(|o| doc.resolve(o))
.and_then(Object::as_name)
.map(crate::object::Name::as_bytes);
let kid_is_pages = match kid_type {
Some(b"Pages") => true,
Some(b"Page") => false,
_ => kid_dict.contains_key(b"Kids"),
};
if kid_is_pages {
walk(doc, kid_dict, inherited.clone(), depth + 1, visited, out)?;
} else {
if out.len() >= MAX_PAGES {
return Err(PageTreeError::TooManyPages);
}
out.push(resolve_page(doc, kid_id, kid_dict, &inherited)?);
}
}
Ok(())
}
fn resolve_page<G: ObjectGraph + ?Sized>(
doc: &G,
id: ObjId,
page: &Dict,
inherited: &Inherited<'_>,
) -> Result<Page, PageTreeError> {
let (resources, resources_defaulted) = match page
.get(b"Resources")
.or(inherited.resources)
.map(|o| doc.resolve(o))
{
Some(Object::Dict(d)) => (d.clone(), false),
None | Some(Object::Null) => (Dict::new(), true),
Some(_) => return Err(PageTreeError::BadResources),
};
let media_box = page
.get(b"MediaBox")
.or(inherited.media_box)
.ok_or(PageTreeError::MissingRequired("MediaBox"))
.and_then(|o| parse_rect(doc, o, "MediaBox"))?;
let (crop_box, crop_box_resolution) = match page.get(b"CropBox").or(inherited.crop_box) {
Some(o) => clip_to_media(parse_rect(doc, o, "CropBox")?, media_box, media_box),
None => (media_box, BoxResolution::Defaulted),
};
let production_box = |key: &[u8]| match page.get(key) {
None => (crop_box, BoxResolution::Defaulted),
Some(o) => match parse_rect(doc, o, "BleedBox") {
Ok(r) => clip_to_media(r, media_box, crop_box),
Err(_) => (crop_box, BoxResolution::Unusable),
},
};
let (bleed_box, bleed_box_resolution) = production_box(b"BleedBox");
let (trim_box, trim_box_resolution) = production_box(b"TrimBox");
let (art_box, art_box_resolution) = production_box(b"ArtBox");
let rotate = match page
.get(b"Rotate")
.or(inherited.rotate)
.map(|o| doc.resolve(o))
{
None => 0,
Some(Object::Integer(v)) if v % 90 == 0 => u16::try_from(v.rem_euclid(360)).unwrap_or(0),
Some(Object::Integer(v)) => return Err(PageTreeError::BadRotate(*v)),
Some(_) => return Err(PageTreeError::BadRotate(i64::MIN)),
};
let (contents, contents_unresolved, contents_flattened) = match page.get(b"Contents") {
None => (Vec::new(), 0, 0),
Some(Object::Null) => (Vec::new(), 0, 0),
Some(entry @ Object::Reference(r)) => match doc.resolve(entry) {
Object::Stream(_) => (vec![*r], 0, 0),
Object::Array(items) => contents_from_array(doc, items, 0)?,
Object::Null => (Vec::new(), 1, 0),
_ => return Err(PageTreeError::BadContents),
},
Some(Object::Array(items)) => contents_from_array(doc, items, 0)?,
Some(_) => return Err(PageTreeError::BadContents),
};
Ok(Page {
id,
resources,
resources_defaulted,
media_box,
crop_box,
crop_box_resolution,
bleed_box,
bleed_box_resolution,
trim_box,
trim_box_resolution,
art_box,
art_box_resolution,
rotate,
contents,
contents_unresolved,
contents_flattened,
})
}
impl Page {
#[must_use]
pub fn with_boxes(id: ObjId, media_box: Rect, crop_box: Rect, rotate: u16) -> Self {
let rotate = if rotate.is_multiple_of(90) {
rotate % 360
} else {
0
};
Self {
id,
resources: Dict::new(),
resources_defaulted: false,
media_box,
crop_box,
crop_box_resolution: BoxResolution::Defaulted,
bleed_box: crop_box,
bleed_box_resolution: BoxResolution::Defaulted,
trim_box: crop_box,
trim_box_resolution: BoxResolution::Defaulted,
art_box: crop_box,
art_box_resolution: BoxResolution::Defaulted,
rotate,
contents: Vec::new(),
contents_unresolved: 0,
contents_flattened: 0,
}
}
}
fn clip_to_media(written: Rect, media_box: Rect, default: Rect) -> (Rect, BoxResolution) {
match media_box.intersection(&written) {
Some(r) if r == written => (r, BoxResolution::AsWritten),
Some(r) => (r, BoxResolution::Clipped),
None => (default, BoxResolution::Unusable),
}
}
const MAX_CONTENTS_NESTING: usize = 8;
fn contents_from_array<G: ObjectGraph + ?Sized>(
doc: &G,
items: &[Object],
depth: usize,
) -> Result<(Vec<ObjId>, usize, usize), PageTreeError> {
if depth > MAX_CONTENTS_NESTING {
return Err(PageTreeError::BadContents);
}
let mut ids = Vec::with_capacity(items.len());
let mut unresolved = 0usize;
let mut flattened = 0usize;
for item in items {
match (item.as_reference(), doc.resolve(item)) {
(Some(id), Object::Stream(_)) => ids.push(id),
(Some(_), Object::Null) => unresolved += 1,
(None, Object::Null) => {}
(_, Object::Array(inner)) => {
let (mut nested, unres, flat) = contents_from_array(doc, inner, depth + 1)?;
ids.append(&mut nested);
unresolved += unres;
flattened += flat + 1;
}
_ => return Err(PageTreeError::BadContents),
}
}
Ok((ids, unresolved, flattened))
}
#[doc(hidden)] pub const WRAP_SAVE: &[u8] = b"%pdfcer overlay wrap: save\nq\n";
#[doc(hidden)] pub const WRAP_RESTORE: &[u8] = b"%pdfcer overlay wrap: restore\nQ\n";
const NEUTRAL_SCAN_LIMIT: usize = 64 * 1024;
const WRAPPER_RAW_LIMIT: usize = 256;
#[doc(hidden)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WrapStreams {
pub save: ObjId,
pub restore: ObjId,
}
#[doc(hidden)] #[derive(Debug, Clone, PartialEq)]
pub struct OverlayAppend {
items: Vec<Object>,
wrap: bool,
}
impl OverlayAppend {
#[must_use]
pub const fn needs_wrap(&self) -> bool {
self.wrap
}
#[must_use]
pub fn finish(&self, new_id: ObjId, wrap: Option<WrapStreams>) -> Option<Object> {
let mut out = Vec::with_capacity(self.items.len() + 3);
if self.wrap {
let pair = wrap?;
out.push(Object::Reference(pair.save));
out.extend(self.items.iter().cloned());
out.push(Object::Reference(pair.restore));
} else {
out.extend(self.items.iter().cloned());
}
out.push(Object::Reference(new_id));
Some(Object::Array(out))
}
}
#[doc(hidden)] #[must_use]
pub fn plan_overlay_append(view: &DocumentView<'_>, before: Option<&Object>) -> OverlayAppend {
let items = contents_items(view, before);
let wrap = !items.is_empty() && !leaves_no_state(view, &items);
OverlayAppend { items, wrap }
}
#[doc(hidden)] #[must_use]
pub fn remove_overlays(
view: &DocumentView<'_>,
before: Option<&Object>,
drop: impl Fn(&Object, &[u8]) -> bool,
) -> Option<Object> {
let before = before?;
let items = contents_items(view, Some(before));
let mut kept: Vec<Object> = items
.iter()
.filter(|item| !decoded_item(view, item).is_some_and(|b| drop(item, &b)))
.cloned()
.collect();
if kept.len() == items.len() {
return Some(before.clone());
}
while kept.len() >= 2
&& is_exactly(view, kept.first(), WRAP_SAVE)
&& is_exactly(view, kept.last(), WRAP_RESTORE)
{
kept.pop();
kept.remove(0);
}
(!kept.is_empty()).then_some(Object::Array(kept))
}
#[doc(hidden)] #[must_use]
pub fn is_state_neutral(content: &[u8]) -> bool {
let Ok(cs) = crate::content::ContentStream::parse(content.to_vec()) else {
return false;
};
let buf = cs.buf.as_slice();
let mut depth = 0_usize;
for op in cs.operations() {
match op.operator_name(buf) {
Some(b"q") => depth += 1,
Some(b"Q") => match depth.checked_sub(1) {
Some(d) => depth = d,
None => return false,
},
Some(b"BMC" | b"BDC" | b"EMC" | b"MP" | b"DP" | b"BX" | b"EX") => {}
_ if depth > 0 => {}
_ => return false,
}
}
depth == 0
}
fn contents_items(view: &DocumentView<'_>, before: Option<&Object>) -> Vec<Object> {
let Some(before) = before else {
return Vec::new();
};
match view.resolve(before) {
Object::Array(items) => items.clone(),
_ => vec![before.clone()],
}
}
fn decoded_item(view: &DocumentView<'_>, item: &Object) -> Option<Vec<u8>> {
let Object::Stream(stream) = view.resolve(item) else {
return None;
};
crate::filters::decode_stream(&stream.dict, view.slice(stream.data_span)?).ok()
}
fn is_exactly(view: &DocumentView<'_>, item: Option<&Object>, bytes: &[u8]) -> bool {
let Some(item) = item else {
return false;
};
let Object::Stream(stream) = view.resolve(item) else {
return false;
};
stream.data_span.len <= WRAPPER_RAW_LIMIT && decoded_item(view, item).as_deref() == Some(bytes)
}
fn leaves_no_state(view: &DocumentView<'_>, items: &[Object]) -> bool {
let neutral = |part: &[Object]| {
let mut all = Vec::new();
for item in part {
let Some(bytes) = decoded_item(view, item) else {
return false;
};
all.extend_from_slice(&bytes);
all.push(b'\n');
}
is_state_neutral(&all)
};
if is_exactly(view, items.first(), WRAP_SAVE)
&& let Some(r) = items
.iter()
.rposition(|item| is_exactly(view, Some(item), WRAP_RESTORE))
&& r > 0
{
return neutral(items.get(r + 1..).unwrap_or_default());
}
let raw: usize = items
.iter()
.map(|item| match view.resolve(item) {
Object::Stream(s) => s.data_span.len,
_ => usize::MAX,
})
.fold(0, usize::saturating_add);
raw <= NEUTRAL_SCAN_LIMIT && neutral(items)
}
#[doc(hidden)] pub fn parse_rect<G: ObjectGraph + ?Sized>(
doc: &G,
obj: &Object,
attr: &'static str,
) -> Result<Rect, PageTreeError> {
let arr = doc
.resolve(obj)
.as_array()
.ok_or(PageTreeError::BadRectangle(attr))?;
let nums: Vec<f64> = arr
.iter()
.filter_map(|o| doc.resolve(o).as_number())
.collect();
match nums.as_slice() {
&[x1, y1, x2, y2] => Ok(Rect::from_corners(x1, y1, x2, y2)),
_ => Err(PageTreeError::BadRectangle(attr)),
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
fn build_pdf(objects: &[(u32, &str)]) -> Document {
let mut buf = b"%PDF-1.4\n".to_vec();
let mut offsets: Vec<(u32, usize)> = Vec::new();
for (num, body) in objects {
offsets.push((*num, buf.len()));
buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_at = buf.len();
let max_num = objects.iter().map(|(n, _)| *n).max().unwrap_or(0);
buf.extend_from_slice(format!("xref\n0 {}\n", max_num + 1).as_bytes());
buf.extend_from_slice(b"0000000000 65535 f\r\n");
for num in 1..=max_num {
match offsets.iter().find(|(n, _)| *n == num) {
Some((_, off)) => {
buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
}
None => buf.extend_from_slice(b"0000000000 65535 f\r\n"),
}
}
buf.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n",
max_num + 1
)
.as_bytes(),
);
Document::from_bytes(buf).unwrap()
}
#[test]
fn inheritance_spec_figure_6_style() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
/MediaBox [0 0 612 792] /Rotate 90 /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R >>"),
(4, "<< /Type /Page /Parent 2 0 R /Rotate 270 >>"),
(5, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >>"),
]);
let pages = pages(&doc).unwrap();
assert_eq!(pages.len(), 3);
assert_eq!(pages[0].media_box.width(), 612.0);
assert_eq!(pages[0].rotate, 90);
assert_eq!(pages[0].crop_box, pages[0].media_box);
assert_eq!(pages[1].rotate, 270);
assert_eq!(pages[2].media_box.width(), 200.0);
assert_eq!(pages[2].rotate, 90);
}
fn one_page(extra: &str) -> Page {
let page = format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] {extra} >>");
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
),
(3, &page),
]);
pages(&doc).unwrap().remove(0)
}
#[test]
fn page_boxes_are_intersected_with_the_media_box() {
let r = Rect::from_corners;
let p = one_page("/CropBox [-50 20 300 80]");
assert_eq!(p.crop_box, r(0.0, 20.0, 100.0, 80.0));
assert_eq!(p.crop_box_resolution, BoxResolution::Clipped);
let p = one_page("/CropBox [10 10 90 90]");
assert_eq!(p.crop_box, r(10.0, 10.0, 90.0, 90.0));
assert_eq!(p.crop_box_resolution, BoxResolution::AsWritten);
let p = one_page("/CropBox [200 200 300 300]");
assert_eq!(p.crop_box, p.media_box);
assert_eq!(p.crop_box_resolution, BoxResolution::Unusable);
let p = one_page("/CropBox [100 0 200 100]");
assert_eq!(p.crop_box_resolution, BoxResolution::Unusable);
let p = one_page("");
assert_eq!(p.crop_box_resolution, BoxResolution::Defaulted);
}
#[test]
fn production_boxes_clip_to_the_media_box_and_default_to_the_crop_box() {
let r = Rect::from_corners;
let p = one_page(
"/CropBox [10 10 90 90] /TrimBox [-5 -5 50 50] \
/BleedBox [500 500 600 600] /ArtBox [1 2 3]",
);
assert_eq!(p.trim_box, r(0.0, 0.0, 50.0, 50.0));
assert_eq!(p.trim_box_resolution, BoxResolution::Clipped);
assert_eq!(p.bleed_box, p.crop_box);
assert_eq!(p.bleed_box_resolution, BoxResolution::Unusable);
assert_eq!(p.art_box, p.crop_box);
assert_eq!(p.art_box_resolution, BoxResolution::Unusable);
let p = one_page("/CropBox [50 50 500 500]");
assert_eq!(p.trim_box, r(50.0, 50.0, 100.0, 100.0));
assert_eq!(p.trim_box_resolution, BoxResolution::Defaulted);
}
#[test]
fn production_boxes_are_not_inherited() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> \
/MediaBox [0 0 100 100] /TrimBox [10 10 20 20] >>",
),
(3, "<< /Type /Page /Parent 2 0 R >>"),
]);
let p = pages(&doc).unwrap().remove(0);
assert_eq!(p.trim_box, p.media_box);
assert_eq!(p.trim_box_resolution, BoxResolution::Defaulted);
}
#[test]
fn deep_tree_and_intermediate_inheritance() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 100 100] /Resources << >> >>",
),
(
3,
"<< /Type /Pages /Parent 2 0 R /Kids [4 0 R] /Count 1 /Rotate 180 >>",
),
(4, "<< /Type /Page /Parent 3 0 R >>"),
]);
let pages = pages(&doc).unwrap();
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].rotate, 180);
assert_eq!(pages[0].media_box.width(), 100.0);
}
#[test]
fn empty_own_resources_beats_inherited() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << /Font << >> >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Resources << >> >>"),
]);
let pages = pages(&doc).unwrap();
assert!(pages[0].resources.is_empty());
assert!(!pages[0].resources_defaulted);
}
#[test]
fn a_resourceless_page_does_not_cost_its_siblings() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
/MediaBox [0 0 612 792] >>",
),
(3, "<< /Type /Page /Parent 2 0 R >>"),
(
4,
"<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 9 0 R >> >> >>",
),
(
5,
"<< /Type /Page /Parent 2 0 R /Resources << /XObject << /Im0 9 0 R >> >> >>",
),
]);
let pages = pages(&doc).unwrap();
assert_eq!(pages.len(), 3);
assert!(pages[0].resources_defaulted);
assert!(pages[0].resources.is_empty());
assert!(!pages[1].resources_defaulted);
assert!(pages[1].resources.contains_key(b"Font"));
assert!(!pages[2].resources_defaulted);
assert!(pages[2].resources.contains_key(b"XObject"));
}
#[test]
fn an_inherited_resource_dictionary_is_not_a_default() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] \
/Resources << /Font << /F1 9 0 R >> >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R >>"),
]);
let pages = pages(&doc).unwrap();
assert!(!pages[0].resources_defaulted);
assert!(pages[0].resources.contains_key(b"Font"));
}
#[test]
fn a_dangling_resources_reference_degrades_like_an_absent_one() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Resources 99 0 R >>"),
]);
let pages = pages(&doc).unwrap();
assert!(pages[0].resources_defaulted);
assert!(pages[0].resources.is_empty());
}
#[test]
fn a_resources_entry_of_the_wrong_type_still_fails_the_page() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Resources 42 >>"),
]);
assert_eq!(pages(&doc).unwrap_err(), PageTreeError::BadResources);
}
#[test]
fn a_missing_media_box_is_still_fatal_to_the_page() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R >>"),
]);
assert_eq!(
pages(&doc).unwrap_err(),
PageTreeError::MissingRequired("MediaBox")
);
}
#[test]
fn rectangle_corners_normalize_in_any_order() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [612 792 0 0] >>"),
]);
let pages = pages(&doc).unwrap();
assert_eq!(pages[0].media_box.llx, 0.0);
assert_eq!(pages[0].media_box.urx, 612.0);
assert_eq!(pages[0].media_box.height(), 792.0);
}
#[test]
fn negative_rotate_normalizes_positive() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Rotate -90 >>"),
]);
assert_eq!(pages(&doc).unwrap()[0].rotate, 270);
}
#[test]
fn non_multiple_of_90_rotate_is_error() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Rotate 45 >>"),
]);
assert_eq!(pages(&doc).unwrap_err(), PageTreeError::BadRotate(45));
}
#[test]
fn missing_mediabox_everywhere_is_error() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R >>"),
]);
assert_eq!(
pages(&doc).unwrap_err(),
PageTreeError::MissingRequired("MediaBox")
);
}
#[test]
fn kids_cycle_is_detected() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [2 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
]);
assert_eq!(
pages(&doc).unwrap_err(),
PageTreeError::Cycle(ObjId::new(2, 0))
);
}
#[test]
fn count_is_not_trusted() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 99 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R >>"),
]);
assert_eq!(pages(&doc).unwrap().len(), 1);
}
#[test]
fn contents_single_and_array_and_absent() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>"),
(4, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 7 0 R] >>"),
(5, "<< /Type /Page /Parent 2 0 R >>"),
(6, "<< /Length 2 >>\nstream\nq \nendstream"),
(7, "<< /Length 2 >>\nstream\nQ \nendstream"),
]);
let pages = pages(&doc).unwrap();
assert_eq!(pages[0].contents, vec![ObjId::new(6, 0)]);
assert_eq!(pages[1].contents, vec![ObjId::new(6, 0), ObjId::new(7, 0)]);
assert!(pages[2].contents.is_empty(), "absent Contents = empty page");
assert!(pages.iter().all(|p| p.contents_unresolved == 0));
}
#[test]
fn contents_array_with_dangling_element_degrades_and_is_disclosed() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(
3,
"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 7 0 R 8 0 R] >>",
),
(6, "<< /Length 2 >>\nstream\nq \nendstream"),
(8, "<< /Length 2 >>\nstream\nQ \nendstream"),
]);
let pages = pages(&doc).expect("a dangling element must not fail the document");
assert_eq!(pages.len(), 1);
assert_eq!(
pages[0].contents,
vec![ObjId::new(6, 0), ObjId::new(8, 0)],
"the streams that DO exist still load, in order"
);
assert_eq!(
pages[0].contents_unresolved, 1,
"the omission is counted, not swallowed"
);
}
#[test]
fn contents_entirely_unresolvable_is_an_empty_page_disclosed() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Contents 9 0 R >>"),
]);
let pages = pages(&doc).expect("an unresolvable /Contents must not fail the document");
assert_eq!(pages.len(), 1);
assert!(pages[0].contents.is_empty(), "empty page, per Table 30");
assert_eq!(
pages[0].contents_unresolved, 1,
"an empty page from a MISSING stream is disclosed, unlike a genuinely blank one"
);
}
#[test]
fn contents_of_the_wrong_type_is_still_an_error() {
let numeric = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Contents 42 >>"),
]);
assert_eq!(pages(&numeric).unwrap_err(), PageTreeError::BadContents);
let dict_target = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>"),
(6, "<< /NotAStream true >>"),
]);
assert_eq!(pages(&dict_target).unwrap_err(), PageTreeError::BadContents);
let bad_element = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R 42] >>"),
(6, "<< /Length 2 >>\nstream\nq \nendstream"),
]);
assert_eq!(pages(&bad_element).unwrap_err(), PageTreeError::BadContents);
}
#[test]
fn explicit_null_contents_is_absent_not_a_degradation() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 \
/MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Type /Page /Parent 2 0 R /Contents null >>"),
(4, "<< /Type /Page /Parent 2 0 R /Contents [6 0 R null] >>"),
(6, "<< /Length 2 >>\nstream\nq \nendstream"),
]);
let pages = pages(&doc).unwrap();
assert!(pages[0].contents.is_empty());
assert_eq!(
pages[0].contents_unresolved, 0,
"an explicit null is an omitted entry, not missing content"
);
assert_eq!(pages[1].contents, vec![ObjId::new(6, 0)]);
assert_eq!(pages[1].contents_unresolved, 0);
}
#[test]
fn missing_type_falls_back_to_structural_detection() {
let doc = build_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
"<< /Kids [3 0 R] /Count 1 /MediaBox [0 0 10 10] /Resources << >> >>",
),
(3, "<< /Parent 2 0 R >>"),
]);
assert_eq!(pages(&doc).unwrap().len(), 1);
}
}