Resolve named PDF image destinations through the page tree

This commit is contained in:
gloamxun committed 2026-11-26 17:41:30 +08:00
1 parent 4c532f9396
commit 58012d9397
5 files changed
+196 -17

No files matched your search

@@ -0,0 +1,122 @@
//! Resolve local PDF destinations to pages in the document's actual page tree.
use super::resolved;
use lopdf::{Dictionary, Document, Object, ObjectId};
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
};
pub(super) fn page(
doc: &Document,
pages: &BTreeMap<u32, ObjectId>,
name: &[u8],
) -> Result<u32, String> {
// pdfTeX hands the expanded TeX bytes to the PDF reader as a C string.
let name = name.split(|&byte| byte == 0).next().unwrap_or_default();
let invalid = || {
format!(
"PDF inclusion: invalid destination <{}>",
String::from_utf8_lossy(name)
)
};
let value = destination(doc, name).ok_or_else(invalid)?;
let destination = match value {
Object::Dictionary(dict) => entry(doc, dict, b"D").ok_or_else(invalid)?,
value => value,
};
let [reference, view, positions @ ..] = destination
.as_array()
.ok()
.map(Vec::as_slice)
.ok_or_else(invalid)?
else {
return Err(invalid());
};
let view = resolved(doc, view)
.ok()
.and_then(|view| view.as_name().ok());
let valid = match view {
Some(b"XYZ") => positions.iter().take(3).all(|position| {
matches!(
resolved(doc, position),
Ok(Object::Null | Object::Integer(_) | Object::Real(_))
)
}),
Some(b"Fit" | b"FitB") => true,
Some(b"FitH" | b"FitV" | b"FitBH" | b"FitBV") => !positions.is_empty(),
Some(b"FitR") => positions.len() >= 4,
_ => false,
};
if !valid {
return Err(invalid());
}
let page = match reference {
Object::Reference(id) => pages
.iter()
.find_map(|(&number, page)| (page == id).then_some(number)),
// Integer destinations can address remote pages. A local inclusion
// needs an actual page reference in this document.
Object::Integer(_) => None,
_ => return Err(invalid()),
};
page.ok_or_else(|| "PDF inclusion: destination is not a page".into())
}
fn entry<'a>(doc: &'a Document, dict: &'a Dictionary, key: &[u8]) -> Option<&'a Object> {
resolved(doc, dict.get(key).ok()?).ok()
}
fn destination<'a>(doc: &'a Document, name: &[u8]) -> Option<&'a Object> {
let catalog = entry(doc, &doc.trailer, b"Root")?.as_dict().ok()?;
if let Some(value) = entry(doc, catalog, b"Dests")
.and_then(|dests| dests.as_dict().ok())
.and_then(|dests| entry(doc, dests, name))
.filter(|value| !matches!(value, Object::Null))
{
return Some(value);
}
let names = entry(doc, catalog, b"Names")?.as_dict().ok()?;
let mut node = names.get(b"Dests").ok()?;
let mut seen = BTreeSet::new();
// Follow only the matching Limits range. Track visited references so
// malformed cycles terminate without limiting a well-formed tree's depth.
loop {
if let Object::Reference(id) = node
&& !seen.insert(*id)
{
return None;
}
let dict = resolved(doc, node).ok()?.as_dict().ok()?;
if let Some(names) = entry(doc, dict, b"Names").and_then(|names| names.as_array().ok()) {
for pair in names.chunks_exact(2) {
let Some(key) = resolved(doc, &pair[0])
.ok()
.and_then(|key| key.as_str().ok())
else {
continue;
};
match name.cmp(key) {
Ordering::Equal => return resolved(doc, &pair[1]).ok(),
Ordering::Less => break,
Ordering::Greater => {}
}
}
return None;
}
let kids = entry(doc, dict, b"Kids")?.as_array().ok()?;
node = kids.iter().find(|kid| {
let bounds = || {
let child = resolved(doc, kid).ok()?.as_dict().ok()?;
let limits = entry(doc, child, b"Limits")?.as_array().ok()?;
let [low, high, ..] = limits.as_slice() else {
return None;
};
Some((
resolved(doc, low).ok()?.as_str().ok()?,
resolved(doc, high).ok()?.as_str().ok()?,
))
};
bounds().is_some_and(|(low, high)| low <= name && name <= high)
})?;
}
}