use crate::page_rotate::resolve_inherited_rotate_with_max_depth;
use crate::pages::{resolve_inherited_resources_with_max_depth, DEFAULT_MAX_PAGE_TREE_DEPTH};
use crate::{Error, Object, ObjectRef, Pdf, Result};
use std::collections::BTreeMap;
use std::io::{Read, Seek};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RebuildResult {
pub new_kids: Vec<ObjectRef>,
pub ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>>,
}
fn resolve_inherited_raw<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
key: &str,
max_depth: usize,
) -> Result<Option<Object>> {
use std::collections::BTreeSet;
let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
let mut current = page_ref;
let mut depth: usize = 0;
loop {
if depth >= max_depth {
return Err(Error::Unsupported(format!(
"page tree depth exceeds maximum of {max_depth} at {current}"
)));
}
if !seen.insert(current) {
return Ok(None);
}
let Object::Dictionary(dict) = pdf.resolve_borrowed(current)? else {
return Ok(None);
};
if let Some(val) = dict.get(key).cloned() {
match val {
Object::Null => {}
other => return Ok(Some(other)),
}
}
let parent_val = match dict.get("Parent").cloned() {
Some(Object::Null) | None => return Ok(None),
Some(v) => v,
};
match parent_val {
Object::Reference(r) => {
current = r;
depth += 1;
}
_ => return Ok(None),
}
}
}
fn leaf_has_own(dict: &crate::Dictionary, key: &str) -> bool {
!matches!(dict.get(key), None | Some(Object::Null))
}
pub fn rebuild_page_tree<R: Read + Seek>(
pdf: &mut Pdf<R>,
selected: &[ObjectRef],
) -> Result<RebuildResult> {
rebuild_page_tree_with_max_depth(pdf, selected, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
pub fn rebuild_page_tree_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
selected: &[ObjectRef],
max_depth: usize,
) -> Result<RebuildResult> {
if selected.is_empty() {
return Err(Error::Missing("page-tree rebuild: empty selection"));
}
let catalog_ref = pdf.root_ref().ok_or(Error::Missing("/Root"))?;
let Object::Dictionary(catalog) = pdf.resolve_borrowed(catalog_ref)? else {
return Err(Error::Unsupported(format!(
"document catalog {catalog_ref} is not a dictionary"
)));
};
let pages_root_ref = catalog.get_ref("Pages").ok_or(Error::Missing("/Pages"))?;
let mut next_num: u32 = pdf
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0);
let mut new_kids: Vec<ObjectRef> = Vec::with_capacity(selected.len());
let mut ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>> = BTreeMap::new();
let mut materialized: BTreeMap<ObjectRef, ()> = BTreeMap::new();
for &src in selected {
let inherited_resources = resolve_inherited_resources_with_max_depth(pdf, src, max_depth)?;
let inherited_rotate = resolve_inherited_rotate_with_max_depth(pdf, src, max_depth)?;
let inherited_mediabox = resolve_inherited_raw(pdf, src, "MediaBox", max_depth)?;
let inherited_cropbox = resolve_inherited_raw(pdf, src, "CropBox", max_depth)?;
let Object::Dictionary(mut leaf) = pdf.resolve(src)? else {
return Err(Error::Unsupported(format!(
"selected object {src} is not a dictionary (expected /Page)"
)));
};
if !matches!(leaf.get("Type"), Some(Object::Name(name)) if name == b"Page") {
return Err(Error::Unsupported(format!(
"selected object {src} is not a /Page dictionary"
)));
}
if !leaf_has_own(&leaf, "Resources") {
if let Some(res) = &inherited_resources {
leaf.insert("Resources", Object::Dictionary(res.clone()));
}
}
if !leaf_has_own(&leaf, "MediaBox") {
if let Some(mb) = &inherited_mediabox {
leaf.insert("MediaBox", mb.clone());
}
}
if !leaf_has_own(&leaf, "CropBox") {
if let Some(cb) = &inherited_cropbox {
leaf.insert("CropBox", cb.clone());
}
}
if !leaf_has_own(&leaf, "Rotate") {
leaf.insert("Rotate", Object::Integer(inherited_rotate as i64));
}
leaf.insert("Parent", Object::Reference(pages_root_ref));
let target_ref = if materialized.insert(src, ()).is_none() {
pdf.set_object(src, Object::Dictionary(leaf));
src
} else {
next_num = next_num.checked_add(1).ok_or_else(|| {
Error::Unsupported(
"page-tree rebuild: object-number overflow allocating duplicate page"
.to_string(),
)
})?;
let clone_ref = ObjectRef::new(next_num, 0);
pdf.set_object(clone_ref, Object::Dictionary(leaf));
clone_ref
};
new_kids.push(target_ref);
ref_map.entry(src).or_default().push(target_ref);
}
let Object::Dictionary(mut root_dict) = pdf.resolve_borrowed(pages_root_ref)?.clone() else {
return Err(Error::Unsupported(format!(
"document /Pages root {pages_root_ref} is not a dictionary"
)));
};
root_dict.insert("Type", Object::Name(b"Pages".to_vec()));
root_dict.insert(
"Kids",
Object::Array(new_kids.iter().map(|&r| Object::Reference(r)).collect()),
);
root_dict.insert("Count", Object::Integer(new_kids.len() as i64));
root_dict.remove("Parent");
pdf.set_object(pages_root_ref, Object::Dictionary(root_dict));
Ok(RebuildResult { new_kids, ref_map })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::check::check_reader;
use crate::pages::page_refs;
use crate::writer::write_pdf;
use crate::Pdf;
use std::io::Cursor;
fn build_nested_pdf() -> Vec<u8> {
let parts: Vec<(u32, String)> = vec![
(1, "<< /Type /Catalog /Pages 2 0 R >>".into()),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 3 >>".into()),
(
3,
"<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R 6 0 R] /Count 3 \
/Rotate 90 /MediaBox [0 0 200 300] /Resources 9 0 R >>"
.into(),
),
(4, "<< /Type /Page /Parent 3 0 R /Contents 7 0 R >>".into()),
(
5,
"<< /Type /Page /Parent 3 0 R /Contents 8 0 R /MediaBox [0 0 400 500] >>".into(),
),
(6, "<< /Type /Page /Parent 3 0 R >>".into()),
];
let c1 = b"BT /F1 12 Tf 10 10 Td (Page1) Tj ET";
let c2 = b"BT /F1 12 Tf 10 10 Td (Page2) Tj ET";
let mut out: Vec<u8> = b"%PDF-1.5\n".to_vec();
let mut offs: BTreeMap<u32, u64> = BTreeMap::new();
for (n, s) in &parts {
offs.insert(*n, out.len() as u64);
out.extend_from_slice(format!("{n} 0 obj\n{s}\nendobj\n").as_bytes());
}
offs.insert(7, out.len() as u64);
out.extend_from_slice(format!("7 0 obj\n<< /Length {} >>\nstream\n", c1.len()).as_bytes());
out.extend_from_slice(c1);
out.extend_from_slice(b"\nendstream\nendobj\n");
offs.insert(8, out.len() as u64);
out.extend_from_slice(format!("8 0 obj\n<< /Length {} >>\nstream\n", c2.len()).as_bytes());
out.extend_from_slice(c2);
out.extend_from_slice(b"\nendstream\nendobj\n");
offs.insert(9, out.len() as u64);
out.extend_from_slice(
b"9 0 obj\n<< /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >>\nendobj\n",
);
let xref_start = out.len() as u64;
let total = 10u32;
out.extend_from_slice(format!("xref\n0 {total}\n0000000000 65535 f \n").as_bytes());
for i in 1..total {
out.extend_from_slice(format!("{:010} 00000 n \n", offs[&i]).as_bytes());
}
out.extend_from_slice(
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
.as_bytes(),
);
out
}
fn open(bytes: Vec<u8>) -> Pdf<Cursor<Vec<u8>>> {
Pdf::open(Cursor::new(bytes)).expect("PDF should parse")
}
fn dict_of(pdf: &mut Pdf<Cursor<Vec<u8>>>, r: ObjectRef) -> crate::Dictionary {
match pdf.resolve_borrowed(r).unwrap() {
Object::Dictionary(d) => d.clone(),
other => panic!("{r} is not a dictionary: {other:?}"),
}
}
#[test]
fn empty_selection_is_error() {
let mut pdf = open(build_nested_pdf());
let err = rebuild_page_tree(&mut pdf, &[]).unwrap_err();
assert!(matches!(err, Error::Missing(_)), "got {err:?}");
}
#[test]
fn selecting_a_pages_node_is_rejected() {
let mut pdf = open(build_nested_pdf());
let err = rebuild_page_tree(&mut pdf, &[ObjectRef::new(2, 0)]).unwrap_err();
assert!(
matches!(err, Error::Unsupported(_)),
"expected Unsupported for /Pages node, got {err:?}"
);
}
#[test]
fn count_and_kids_match_selection_order() {
let mut pdf = open(build_nested_pdf());
let sel = [ObjectRef::new(6, 0), ObjectRef::new(4, 0)];
let res = rebuild_page_tree(&mut pdf, &sel).unwrap();
assert_eq!(
res.new_kids,
vec![ObjectRef::new(6, 0), ObjectRef::new(4, 0)]
);
let root = dict_of(&mut pdf, ObjectRef::new(2, 0));
assert_eq!(root.get("Count"), Some(&Object::Integer(2)));
let Some(Object::Array(kids)) = root.get("Kids") else {
panic!("root /Kids missing or wrong type");
};
assert_eq!(
kids,
&vec![
Object::Reference(ObjectRef::new(6, 0)),
Object::Reference(ObjectRef::new(4, 0)),
]
);
}
#[test]
fn inherited_attrs_materialized_on_leaf() {
let mut pdf = open(build_nested_pdf());
rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0)]).unwrap();
let leaf = dict_of(&mut pdf, ObjectRef::new(4, 0));
assert_eq!(leaf.get("Rotate"), Some(&Object::Integer(90)));
assert_eq!(
leaf.get("MediaBox"),
Some(&Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(200),
Object::Integer(300),
]))
);
match leaf.get("Resources") {
Some(Object::Dictionary(d)) => assert!(d.get("Font").is_some()),
other => panic!("expected materialized /Resources dict, got {other:?}"),
}
assert_eq!(
leaf.get("Parent"),
Some(&Object::Reference(ObjectRef::new(2, 0)))
);
}
#[test]
fn own_attribute_wins_over_inherited() {
let mut pdf = open(build_nested_pdf());
rebuild_page_tree(&mut pdf, &[ObjectRef::new(5, 0)]).unwrap();
let leaf = dict_of(&mut pdf, ObjectRef::new(5, 0));
assert_eq!(
leaf.get("MediaBox"),
Some(&Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(400),
Object::Integer(500),
])),
"own /MediaBox must win over inherited [0 0 200 300]"
);
assert_eq!(leaf.get("Rotate"), Some(&Object::Integer(90)));
}
#[test]
fn duplicate_selection_yields_distinct_page_dicts_sharing_contents() {
let mut pdf = open(build_nested_pdf());
let res =
rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0), ObjectRef::new(4, 0)]).unwrap();
assert_eq!(res.new_kids.len(), 2);
assert_eq!(res.new_kids[0], ObjectRef::new(4, 0)); let clone_ref = res.new_kids[1];
assert_ne!(clone_ref, ObjectRef::new(4, 0), "second slot is a clone");
assert_eq!(
res.ref_map.get(&ObjectRef::new(4, 0)),
Some(&vec![ObjectRef::new(4, 0), clone_ref])
);
let original = dict_of(&mut pdf, ObjectRef::new(4, 0));
let clone = dict_of(&mut pdf, clone_ref);
assert_eq!(original.get("Contents"), clone.get("Contents"));
assert_eq!(
original.get("Contents"),
Some(&Object::Reference(ObjectRef::new(7, 0)))
);
assert_eq!(clone.get("Rotate"), Some(&Object::Integer(90)));
let root = dict_of(&mut pdf, ObjectRef::new(2, 0));
assert_eq!(root.get("Count"), Some(&Object::Integer(2)));
}
#[test]
fn subset_round_trips_to_valid_pdf() {
let mut pdf = open(build_nested_pdf());
rebuild_page_tree(&mut pdf, &[ObjectRef::new(4, 0), ObjectRef::new(6, 0)]).unwrap();
let mut out: Vec<u8> = Vec::new();
write_pdf(&mut pdf, &mut out).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(out.clone())).expect("rebuilt PDF should parse");
let refs = page_refs(&mut pdf2).expect("page tree should walk");
assert_eq!(refs.len(), 2, "/Pages should enumerate exactly 2 leaves");
assert_eq!(refs, vec![ObjectRef::new(4, 0), ObjectRef::new(6, 0)]);
let leaf = dict_of(&mut pdf2, ObjectRef::new(6, 0));
assert_eq!(leaf.get("Rotate"), Some(&Object::Integer(90)));
assert!(leaf.get("MediaBox").is_some());
let report = check_reader(Cursor::new(out)).expect("check should run");
assert!(
report.valid,
"rebuilt subset PDF should pass check_reader: {:?}",
report.diagnostics
);
}
#[test]
fn duplicate_round_trips_with_correct_page_count() {
let mut pdf = open(build_nested_pdf());
rebuild_page_tree(
&mut pdf,
&[
ObjectRef::new(4, 0),
ObjectRef::new(4, 0),
ObjectRef::new(5, 0),
],
)
.unwrap();
let mut out: Vec<u8> = Vec::new();
write_pdf(&mut pdf, &mut out).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(out)).expect("should parse");
let refs = page_refs(&mut pdf2).expect("walk");
assert_eq!(refs.len(), 3, "duplicate selection → 3 enumerated pages");
}
}