use crate::filters::decode_stream_data;
use crate::{Dictionary, Error, Object, ObjectRef, Pdf, Result, Stream};
use std::collections::BTreeSet;
use std::io::{Read, Seek};
pub const DEFAULT_MAX_PAGE_TREE_DEPTH: usize = 100;
pub fn page_refs<R: Read + Seek>(pdf: &mut Pdf<R>) -> Result<Vec<ObjectRef>> {
page_refs_with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
pub fn page_refs_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
max_depth: usize,
) -> Result<Vec<ObjectRef>> {
PageWalk::with_max_depth(pdf, max_depth)?.collect()
}
pub fn page_content_bytes<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
) -> Result<Vec<u8>> {
let page_obj = pdf.resolve_borrowed(page_ref)?;
let Some(page_dict) = page_obj.as_dict() else {
return Err(Error::Unsupported(format!(
"object {page_ref} is not a dictionary, cannot extract /Contents"
)));
};
match page_dict.get("Type") {
Some(Object::Name(name)) if name.as_slice() == b"Page" => {}
Some(Object::Name(name)) => {
return Err(Error::Unsupported(format!(
"object {page_ref} has /Type /{}, expected /Page",
String::from_utf8_lossy(name)
)));
}
Some(_) => {
return Err(Error::Unsupported(format!(
"object {page_ref} has a non-name /Type entry"
)));
}
None => {
return Err(Error::Unsupported(format!(
"object {page_ref} has no /Type entry"
)));
}
}
let contents = match page_dict.get("Contents").cloned() {
None => return Ok(Vec::new()),
Some(c) => c,
};
let streams: Vec<Stream> = collect_content_streams(pdf, &contents, page_ref)?;
if streams.is_empty() {
return Ok(Vec::new());
}
let mut result: Vec<u8> = Vec::new();
for (i, stream) in streams.into_iter().enumerate() {
let decoded = decode_stream_data(&stream.dict, &stream.data)?;
if i > 0 {
result.push(b' ');
}
result.extend_from_slice(&decoded);
}
Ok(result)
}
fn collect_content_streams<R: Read + Seek>(
pdf: &mut Pdf<R>,
contents: &Object,
page_ref: ObjectRef,
) -> Result<Vec<Stream>> {
match contents {
Object::Stream(s) => Ok(vec![s.clone()]),
Object::Reference(r) => {
let resolved = pdf.resolve_borrowed(*r)?;
match resolved {
Object::Stream(s) => Ok(vec![s.clone()]),
_ => Err(Error::Unsupported(format!(
"/Contents reference {r} on page {page_ref} does not resolve to a stream"
))),
}
}
Object::Array(elems) => {
let mut streams = Vec::with_capacity(elems.len());
for elem in elems {
match elem {
Object::Reference(r) => {
let resolved = pdf.resolve_borrowed(*r)?;
match resolved {
Object::Stream(s) => streams.push(s.clone()),
_ => {
return Err(Error::Unsupported(format!(
"/Contents array element {r} on page {page_ref} does not resolve to a stream"
)));
}
}
}
Object::Stream(s) => streams.push(s.clone()),
other => {
let type_name = object_type_name(other);
return Err(Error::Unsupported(format!(
"/Contents array element of type {type_name} on page {page_ref} is not a stream or reference"
)));
}
}
}
Ok(streams)
}
other => Err(Error::Unsupported(format!(
"/Contents entry on page {page_ref} has unexpected type {}",
object_type_name(other)
))),
}
}
pub fn coalesce_page_contents<R: Read + Seek>(pdf: &mut Pdf<R>, page_ref: ObjectRef) -> Result<()> {
let page_obj = pdf.resolve_borrowed(page_ref)?;
let Some(page_dict) = page_obj.as_dict() else {
return Err(Error::Unsupported(format!(
"object {page_ref} is not a dictionary, cannot coalesce /Contents"
)));
};
match page_dict.get("Type") {
Some(Object::Name(name)) if name.as_slice() == b"Page" => {}
Some(Object::Name(name)) => {
return Err(Error::Unsupported(format!(
"object {page_ref} has /Type /{}, expected /Page",
String::from_utf8_lossy(name)
)));
}
Some(_) => {
return Err(Error::Unsupported(format!(
"object {page_ref} has a non-name /Type entry"
)));
}
None => {
return Err(Error::Unsupported(format!(
"object {page_ref} has no /Type entry"
)));
}
}
let contents = match page_dict.get("Contents").cloned() {
None => return Ok(()), Some(c) => c,
};
let refs: Vec<Object> = match &contents {
Object::Array(elems) if elems.len() >= 2 => elems.clone(),
_ => return Ok(()),
};
let mut coalesced: Vec<u8> = Vec::new();
let mut new_dict: Option<Dictionary> = None;
for (i, elem) in refs.iter().enumerate() {
let stream: Stream = match elem {
Object::Reference(r) => {
let resolved = pdf.resolve_borrowed(*r)?;
match resolved {
Object::Stream(s) => s.clone(),
_ => {
return Err(Error::Unsupported(format!(
"/Contents array element {r} on page {page_ref} does not resolve to a stream"
)));
}
}
}
Object::Stream(s) => s.clone(),
other => {
let type_name = object_type_name(other);
return Err(Error::Unsupported(format!(
"/Contents array element of type {type_name} on page {page_ref} is not a stream or reference"
)));
}
};
if i == 0 {
let mut d = stream.dict.clone();
for key in [
"Filter",
"DecodeParms",
"DP",
"Length",
"DL",
"F",
"FFilter",
"FDecodeParms",
] {
d.remove(key);
}
new_dict = Some(d);
}
let decoded = decode_stream_data(&stream.dict, &stream.data)?;
if i > 0 {
coalesced.push(b'\n');
}
coalesced.extend_from_slice(&decoded);
}
let new_num: u32 = pdf
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0)
.checked_add(1)
.ok_or_else(|| {
Error::Unsupported(
"coalesce_page_contents: object number overflow allocating new stream".to_string(),
)
})?;
let new_stream_ref = ObjectRef::new(new_num, 0);
let new_stream = Stream::new(new_dict.unwrap_or_default(), coalesced);
pdf.set_object(new_stream_ref, Object::Stream(new_stream));
let page_obj2 = pdf.resolve_borrowed(page_ref)?;
let Some(mut new_page_dict) = page_obj2.as_dict().cloned() else {
return Err(Error::Unsupported(format!(
"object {page_ref} unexpectedly not a dictionary after coalesce"
)));
};
new_page_dict.insert("Contents", Object::Reference(new_stream_ref));
pdf.set_object(page_ref, Object::Dictionary(new_page_dict));
Ok(())
}
fn object_type_name(obj: &Object) -> &'static str {
match obj {
Object::Null => "null",
Object::Boolean(_) => "boolean",
Object::Integer(_) => "integer",
Object::Real(_) => "real",
Object::Name(_) => "name",
Object::String(_) => "string",
Object::Array(_) => "array",
Object::Dictionary(_) => "dictionary",
Object::Stream(_) => "stream",
Object::Reference(_) => "reference",
}
}
pub fn resolve_inherited_resources<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
) -> Result<Option<Dictionary>> {
resolve_inherited_resources_with_max_depth(pdf, page_ref, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
pub fn resolve_inherited_resources_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
max_depth: usize,
) -> Result<Option<Dictionary>> {
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 node_obj = pdf.resolve_borrowed(current)?;
let Some(dict) = node_obj.as_dict() else {
return Ok(None);
};
let resources_val = dict.get("Resources").cloned();
let parent_val = dict.get("Parent").cloned();
if let Some(resources_val) = resources_val {
match resources_val {
Object::Null => {}
Object::Dictionary(d) => return Ok(Some(d)),
Object::Reference(r) => {
let resolved = pdf.resolve_borrowed(r)?;
match resolved {
Object::Null => {}
Object::Dictionary(d) => return Ok(Some(d.clone())),
_ => {
return Err(Error::Unsupported(format!(
"/Resources reference {r} on node {current} does not resolve to a dictionary"
)));
}
}
}
_ => {
return Err(Error::Unsupported(format!(
"/Resources entry on node {current} has unexpected type"
)));
}
}
}
let parent_val = match parent_val {
Some(Object::Null) | None => return Ok(None),
Some(v) => v,
};
match parent_val {
Object::Reference(r) => {
current = r;
depth += 1;
}
_ => return Ok(None),
}
}
}
pub struct PageWalk<'a, R: Read + Seek> {
pdf: &'a mut Pdf<R>,
stack: Vec<(ObjectRef, usize)>,
seen: BTreeSet<ObjectRef>,
max_depth: usize,
done: bool,
}
impl<'a, R: Read + Seek> PageWalk<'a, R> {
pub fn new(pdf: &'a mut Pdf<R>) -> Result<Self> {
Self::with_max_depth(pdf, DEFAULT_MAX_PAGE_TREE_DEPTH)
}
pub fn with_max_depth(pdf: &'a mut Pdf<R>, max_depth: usize) -> Result<Self> {
let catalog_ref = pdf.root_ref().ok_or(Error::Missing("/Root"))?;
let catalog = pdf.resolve_borrowed(catalog_ref)?;
let Some(catalog) = catalog.as_dict() else {
return Err(Error::Unsupported(format!(
"document catalog {catalog_ref} is not a dictionary"
)));
};
let pages_ref = catalog.get_ref("Pages").ok_or(Error::Missing("/Pages"))?;
Ok(PageWalk {
pdf,
stack: vec![(pages_ref, 0)],
seen: BTreeSet::new(),
max_depth,
done: false,
})
}
}
impl<'a, R: Read + Seek> Iterator for PageWalk<'a, R> {
type Item = Result<ObjectRef>;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
loop {
let (node, depth) = self.stack.pop()?;
if depth >= self.max_depth {
self.done = true;
return Some(Err(Error::Unsupported(format!(
"page tree depth exceeds maximum of {} at {}",
self.max_depth, node
))));
}
if !self.seen.insert(node) {
continue; }
let node_obj = match self.pdf.resolve_borrowed(node) {
Ok(o) => o,
Err(e) => {
self.done = true;
return Some(Err(e));
}
};
let Some(dict) = node_obj.as_dict() else {
continue; };
let node_type = dict
.get("Type")
.and_then(|value| match value {
Object::Name(value) => Some(value.as_slice()),
_ => None,
})
.unwrap_or(&[]);
if node_type == b"Pages" {
if let Some(kids) = dict.get("Kids").and_then(Object::as_array) {
for kid in kids.iter().rev() {
if let Object::Reference(r) = kid {
self.stack.push((*r, depth + 1));
}
}
}
continue;
}
if node_type == b"Page" {
return Some(Ok(node));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::filters::encode_stream_data;
use crate::Dictionary;
use std::io::Cursor;
fn build_pdf_with_contents(contents_entry: &str, extra_objects: &[(u32, &str)]) -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len() as u64;
let page_obj = if contents_entry.is_empty() {
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
} else {
format!(
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {contents_entry} >>\nendobj\n"
)
};
pdf.extend_from_slice(page_obj.as_bytes());
let mut extra_offsets: Vec<(u32, u64)> = Vec::new();
for (num, body) in extra_objects.iter() {
let off = pdf.len() as u64;
extra_offsets.push((*num, off));
pdf.extend_from_slice(body.as_bytes());
}
let xref_start = pdf.len() as u64;
let max_num = extra_offsets.iter().map(|(n, _)| *n).max().unwrap_or(3);
let total = max_num as usize + 1; let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
xref.push_str(&format!("{:010} 00000 n \n", off1));
xref.push_str(&format!("{:010} 00000 n \n", off2));
xref.push_str(&format!("{:010} 00000 n \n", off3));
for i in 4..=max_num {
if let Some((_, off)) = extra_offsets.iter().find(|(n, _)| *n == i) {
xref.push_str(&format!("{:010} 00000 n \n", off));
} else {
xref.push_str("0000000000 65535 f \n");
}
}
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn build_pdf_with_pages_node_as_obj3() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
let off3 = pdf.len() as u64;
pdf.extend_from_slice(b"3 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn stream_object_bytes(num: u32, body: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(
format!("{num} 0 obj\n<< /Length {} >>\nstream\n", body.len()).as_bytes(),
);
out.extend_from_slice(body);
out.extend_from_slice(b"\nendstream\nendobj\n");
out
}
fn chained_filter_stream_object_bytes(num: u32, body: &[u8]) -> Vec<u8> {
let mut a85_dict = Dictionary::new();
a85_dict.insert("Filter", Object::Name(b"ASCII85Decode".to_vec()));
let after_a85 = encode_stream_data(&a85_dict, body).unwrap();
let mut flate_dict = Dictionary::new();
flate_dict.insert("Filter", Object::Name(b"FlateDecode".to_vec()));
let encoded = encode_stream_data(&flate_dict, &after_a85).unwrap();
let mut out = Vec::new();
out.extend_from_slice(
format!(
"{num} 0 obj\n<< /Filter [ /FlateDecode /ASCII85Decode ] /Length {} >>\nstream\n",
encoded.len()
)
.as_bytes(),
);
out.extend_from_slice(&encoded);
out.extend_from_slice(b"\nendstream\nendobj\n");
out
}
fn build_pdf_with_binary_extras(
contents_entry: &str,
extra_objects: &[(u32, Vec<u8>)],
) -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len() as u64;
let page_obj = if contents_entry.is_empty() {
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
} else {
format!(
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents {contents_entry} >>\nendobj\n"
)
};
pdf.extend_from_slice(page_obj.as_bytes());
let mut extra_offsets: Vec<(u32, u64)> = Vec::new();
for (num, body) in extra_objects.iter() {
let off = pdf.len() as u64;
extra_offsets.push((*num, off));
pdf.extend_from_slice(body);
}
let xref_start = pdf.len() as u64;
let max_num = extra_offsets.iter().map(|(n, _)| *n).max().unwrap_or(3);
let total = max_num as usize + 1;
let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
xref.push_str(&format!("{:010} 00000 n \n", off1));
xref.push_str(&format!("{:010} 00000 n \n", off2));
xref.push_str(&format!("{:010} 00000 n \n", off3));
for i in 4..=max_num {
if let Some((_, off)) = extra_offsets.iter().find(|(n, _)| *n == i) {
xref.push_str(&format!("{:010} 00000 n \n", off));
} else {
xref.push_str("0000000000 65535 f \n");
}
}
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
#[test]
fn page_content_bytes_returns_empty_for_page_without_contents() {
let bytes = build_pdf_with_contents("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
assert!(
content.is_empty(),
"expected empty Vec for page without /Contents"
);
}
#[test]
fn page_content_bytes_resolves_single_stream_reference() {
let body = b"BT /F1 12 Tf (Hello) Tj ET";
let stream_bytes = stream_object_bytes(4, body);
let bytes = build_pdf_with_binary_extras("4 0 R", &[(4, stream_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
assert_eq!(content, body);
}
#[test]
fn page_content_bytes_concatenates_array_of_refs_with_space_separator() {
let body1 = b"q 1 0 0 1 0 0 cm";
let body2 = b"BT /F1 12 Tf (World) Tj ET";
let stream_bytes1 = stream_object_bytes(4, body1);
let stream_bytes2 = stream_object_bytes(5, body2);
let bytes = build_pdf_with_binary_extras(
"[4 0 R 5 0 R]",
&[(4, stream_bytes1), (5, stream_bytes2)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let mut expected = body1.to_vec();
expected.push(b' ');
expected.extend_from_slice(body2);
assert_eq!(content, expected);
}
#[test]
fn page_content_bytes_applies_chained_filters() {
let body = b"q 0.5 g 100 100 300 300 re f Q";
let stream_bytes = chained_filter_stream_object_bytes(4, body);
let bytes = build_pdf_with_binary_extras("4 0 R", &[(4, stream_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
assert_eq!(content, body);
}
#[test]
fn page_content_bytes_rejects_non_page_ref() {
let bytes = build_pdf_with_pages_node_as_obj3();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let result = page_content_bytes(&mut pdf, ObjectRef::new(3, 0));
assert!(result.is_err(), "expected error for non-Page ref, got Ok");
match result.unwrap_err() {
Error::Unsupported(_) => {}
err => panic!("expected Error::Unsupported, got {err:?}"),
}
}
#[test]
fn page_content_bytes_handles_direct_stream_in_contents() {
let base_bytes = build_pdf_with_contents("", &[]);
let mut pdf = Pdf::open(Cursor::new(base_bytes)).expect("PDF should parse");
let content_body = b"BT /F1 12 Tf (Direct) Tj ET";
let stream = Stream::new(Dictionary::new(), content_body.to_vec());
let mut page_dict = Dictionary::new();
page_dict.insert("Type", Object::Name(b"Page".to_vec()));
page_dict.insert("Contents", Object::Stream(stream));
pdf.set_object(ObjectRef::new(3, 0), Object::Dictionary(page_dict));
let content = page_content_bytes(&mut pdf, ObjectRef::new(3, 0)).unwrap();
assert_eq!(content, content_body);
}
fn build_pdf_page_has_direct_resources() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len() as u64;
pdf.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << >> >> >>\nendobj\n",
);
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn build_pdf_resources_inherited_via_indirect_ref() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 /Resources 4 0 R >>\nendobj\n",
);
let off3 = pdf.len() as u64;
pdf.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
);
let off4 = pdf.len() as u64;
pdf.extend_from_slice(b"4 0 obj\n<< /Font << /F1 << /Type /Font >> >> >>\nendobj\n");
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 5\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3, off4,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn build_pdf_no_resources() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len() as u64;
pdf.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
);
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
#[test]
fn resolve_inherited_resources_page_has_direct_dict() {
let bytes = build_pdf_page_has_direct_resources();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let result = resolve_inherited_resources(&mut pdf, page_ref).expect("should succeed");
let dict = result.expect("should find /Resources");
assert!(
dict.get("Font").is_some(),
"expected /Font key in resolved Resources dict"
);
}
#[test]
fn resolve_inherited_resources_from_parent_via_indirect_ref() {
let bytes = build_pdf_resources_inherited_via_indirect_ref();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let result = resolve_inherited_resources(&mut pdf, page_ref).expect("should succeed");
let dict = result.expect("should find inherited /Resources via indirect ref");
assert!(
dict.get("Font").is_some(),
"expected /Font key in inherited Resources dict"
);
}
#[test]
fn resolve_inherited_resources_none_when_absent() {
let bytes = build_pdf_no_resources();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let page_ref = ObjectRef::new(3, 0);
let result =
resolve_inherited_resources(&mut pdf, page_ref).expect("should succeed with Ok(None)");
assert!(
result.is_none(),
"expected Ok(None) when no /Resources anywhere in the parent chain"
);
}
#[test]
fn resolve_inherited_resources_cycle_does_not_crash() {
let bytes = build_pdf_no_resources();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let mut pages_dict = Dictionary::new();
pages_dict.insert("Type", Object::Name(b"Pages".to_vec()));
pages_dict.insert(
"Kids",
Object::Array(vec![Object::Reference(ObjectRef::new(3, 0))]),
);
pages_dict.insert("Count", Object::Integer(1));
pages_dict.insert("Parent", Object::Reference(ObjectRef::new(3, 0))); pdf.set_object(ObjectRef::new(2, 0), Object::Dictionary(pages_dict));
let page_ref = ObjectRef::new(3, 0);
let result = resolve_inherited_resources(&mut pdf, page_ref);
match result {
Ok(None) => {} Ok(Some(_)) => panic!("should not find resources in a cycle-only graph"),
Err(Error::Unsupported(_)) => {} Err(e) => panic!("unexpected error variant: {e:?}"),
}
}
#[test]
fn resolve_inherited_resources_null_falls_through_to_parent() {
let bytes = build_pdf_resources_inherited_via_indirect_ref();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let mut page_dict = Dictionary::new();
page_dict.insert("Type", Object::Name(b"Page".to_vec()));
page_dict.insert("Parent", Object::Reference(ObjectRef::new(2, 0)));
page_dict.insert(
"MediaBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(612),
Object::Integer(792),
]),
);
page_dict.insert("Resources", Object::Null);
pdf.set_object(ObjectRef::new(3, 0), Object::Dictionary(page_dict));
let page_ref = ObjectRef::new(3, 0);
let result =
resolve_inherited_resources(&mut pdf, page_ref).expect("null should be like absent");
let dict = result.expect("should inherit /Resources from parent despite null on page");
assert!(
dict.get("Font").is_some(),
"expected inherited /Font key when page's /Resources is null"
);
}
#[test]
fn resolve_inherited_resources_null_parent_terminates_chain() {
let bytes = build_pdf_no_resources();
let mut pdf = Pdf::open(Cursor::new(bytes)).expect("PDF should parse");
let mut page_dict = Dictionary::new();
page_dict.insert("Type", Object::Name(b"Page".to_vec()));
page_dict.insert("Parent", Object::Null);
page_dict.insert(
"MediaBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(612),
Object::Integer(792),
]),
);
pdf.set_object(ObjectRef::new(3, 0), Object::Dictionary(page_dict));
let page_ref = ObjectRef::new(3, 0);
let result = resolve_inherited_resources(&mut pdf, page_ref)
.expect("null /Parent should be like absent");
assert!(
result.is_none(),
"expected Ok(None) when /Parent is null and no /Resources"
);
}
fn pdf_from_objects(catalog_ref: u32, objects: &[(u32, &str)]) -> Vec<u8> {
let mut data: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offsets: Vec<(u32, u64)> = Vec::new();
for (num, body) in objects {
let off = data.len() as u64;
offsets.push((*num, off));
data.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_start = data.len() as u64;
let max_num = offsets.iter().map(|(n, _)| *n).max().unwrap_or(0);
let total = max_num as usize + 1;
let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
for i in 1..=max_num {
if let Some((_, off)) = offsets.iter().find(|(n, _)| *n == i) {
xref.push_str(&format!("{off:010} 00000 n \n"));
} else {
xref.push_str("0000000000 65535 f \n");
}
}
data.extend_from_slice(xref.as_bytes());
let trailer = format!(
"trailer\n<< /Size {total} /Root {catalog_ref} 0 R >>\nstartxref\n{xref_start}\n%%EOF\n"
);
data.extend_from_slice(trailer.as_bytes());
data
}
#[test]
fn page_walk_single_page_yields_one_ref() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert_eq!(refs, vec![ObjectRef::new(3, 0)]);
}
#[test]
fn page_walk_sibling_order_is_document_order() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
(4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert_eq!(
refs,
vec![ObjectRef::new(3, 0), ObjectRef::new(4, 0)],
"pages must be yielded in document order (3 before 4)"
);
}
#[test]
fn page_walk_nested_tree_document_order() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 >>"),
(
3,
"<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 >>",
),
(4, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
(5, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
(6, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert_eq!(
refs,
vec![
ObjectRef::new(4, 0),
ObjectRef::new(5, 0),
ObjectRef::new(6, 0),
],
"pages must be yielded in document order across nested Pages nodes"
);
}
#[test]
fn page_walk_cycle_does_not_crash() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 0 >>"),
(3, "<< /Type /Pages /Kids [2 0 R] /Count 0 >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let result: Result<Vec<ObjectRef>> = PageWalk::new(&mut pdf).unwrap().collect();
assert_eq!(result.unwrap(), vec![]);
}
#[test]
fn page_walk_depth_limit_returns_err() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let result: Result<Vec<ObjectRef>> =
PageWalk::with_max_depth(&mut pdf, 1).unwrap().collect();
match result {
Err(Error::Unsupported(_)) => {}
other => panic!("expected Err(Unsupported) for depth limit, got {other:?}"),
}
}
#[test]
fn page_walk_fused_after_depth_err() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let mut walk = PageWalk::with_max_depth(&mut pdf, 1).unwrap();
let first = walk.next();
assert!(
matches!(first, Some(Err(Error::Unsupported(_)))),
"first item should be Err(Unsupported)"
);
assert!(walk.next().is_none(), "iterator must be fused after Err");
}
#[test]
fn page_walk_pages_node_without_kids_is_skipped() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Count 0 >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert!(refs.is_empty());
}
#[test]
fn page_walk_non_ref_kid_is_ignored() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let mut pages_dict = Dictionary::new();
pages_dict.insert("Type", Object::Name(b"Pages".to_vec()));
pages_dict.insert(
"Kids",
Object::Array(vec![
Object::Integer(999), Object::Reference(ObjectRef::new(3, 0)),
]),
);
pages_dict.insert("Count", Object::Integer(1));
pdf.set_object(ObjectRef::new(2, 0), Object::Dictionary(pages_dict));
let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert_eq!(refs, vec![ObjectRef::new(3, 0)]);
}
#[test]
fn page_walk_unknown_type_node_is_skipped() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 1 >>"),
(3, "<< /Type /Widget /Parent 2 0 R >>"),
(4, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let refs: Vec<ObjectRef> = PageWalk::new(&mut pdf)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert_eq!(
refs,
vec![ObjectRef::new(4, 0)],
"Widget node must be skipped"
);
}
#[test]
fn page_walk_matches_page_refs() {
let bytes = pdf_from_objects(
1,
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 >>"),
(
3,
"<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 >>",
),
(4, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
(5, "<< /Type /Page /Parent 3 0 R /MediaBox [0 0 612 792] >>"),
(6, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
);
let bytes2 = bytes.clone();
let mut pdf1 = Pdf::open(Cursor::new(bytes)).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(bytes2)).unwrap();
let from_page_refs = page_refs(&mut pdf1).unwrap();
let from_walk: Vec<ObjectRef> = PageWalk::new(&mut pdf2)
.unwrap()
.collect::<Result<_>>()
.unwrap();
assert_eq!(from_page_refs, from_walk);
}
}