Resolve native PDF structure destinations and local actions

This commit is contained in:
gloamxun committed 2026-11-21 05:04:54 +08:00
1 parent 58bcfca7b7
commit 22154b53a6
11 files changed
+284 -78

No files matched your search

+115 -61
View File
@@ -14,7 +14,7 @@ use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::pdf_device::{
catalog::{CatalogAction, CatalogTarget, PdfOutline},
catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget},
links::DestinationId,
};
use crate::render::{DisplayItem, DisplayList, FontFace};
@@ -1393,7 +1393,8 @@ fn native_pdf(
|| !font_attributes.is_empty()
|| !page_tree.is_empty()
|| pages.iter().any(|page| !page.pdf_resources.entries.is_empty()
|| !page.pdf_resources.attributes.is_empty())
|| !page.pdf_resources.attributes.is_empty()
|| page.pdf_links.destinations.iter().any(|destination| destination.structure.is_some()))
{
let (catalog, info) = if raw_objects.is_some() {
(
@@ -1694,15 +1695,29 @@ fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
out.push(b' ');
}
fn write_catalog_action(
#[derive(Default)]
struct PdfNavigation {
pages: Vec<usize>,
named: BTreeMap<String, String>,
numbered: BTreeMap<i32, usize>,
structures: BTreeMap<DestinationId<String>, usize>,
threads: BTreeMap<DestinationId<String>, usize>,
}
fn destination_identifier(id: &DestinationId<String>) -> String {
match id {
DestinationId::Name(name) => format!("name{{{name}}}"),
DestinationId::Number(number) => format!("num{number}"),
}
}
fn catalog_action_bytes(
action: &CatalogAction,
page_ids: &[usize],
destinations: &mut BTreeMap<String, String>,
numbers: &mut BTreeMap<i32, usize>,
threads: &mut BTreeMap<DestinationId<String>, usize>,
destinations: &mut PdfNavigation,
objects: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
) -> usize {
) -> Vec<u8> {
let PdfNavigation { pages, named, numbered, structures, threads } = destinations;
let mut output = b"<< ".to_vec();
match action {
CatalogAction::User(object) => output.clone_from(object),
@@ -1723,20 +1738,20 @@ fn write_catalog_action(
}
match target {
CatalogTarget::Destination(DestinationId::Name(name)) => {
if file.is_none() && !destinations.contains_key(name) {
if file.is_none() && !named.contains_key(name) {
diagnostics.push(format!(
"destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one"
));
destinations.insert(name.clone(), format!("[{} 0 R /Fit]", page_ids[0]));
named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0]));
}
output.extend_from_slice(pdf_text(name).as_bytes());
}
CatalogTarget::Destination(DestinationId::Number(number)) => {
let id = numbers.entry(*number).or_insert_with(|| {
let id = numbered.entry(*number).or_insert_with(|| {
diagnostics.push(format!(
"destination num{number} has been referenced but does not exist, replaced by a fixed one"
));
objects.push(format!("[{} 0 R /Fit]", page_ids[0]).into_bytes());
objects.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes());
objects.len()
});
write!(&mut output, "{id} 0 R").unwrap();
@@ -1746,7 +1761,7 @@ fn write_catalog_action(
if file.is_some() {
write!(&mut output, "[{index} ").unwrap();
} else {
let page = page_ids.get(index).copied().unwrap_or_else(|| {
let page = pages.get(index).copied().unwrap_or_else(|| {
diagnostics.push(format!(
"page {number} has been referenced but does not exist"
));
@@ -1759,9 +1774,24 @@ fn write_catalog_action(
output.push(b']');
}
}
if let Some(structure) = structure {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(structure);
match structure {
Some(StructureTarget::Local(destination)) => {
let id = structures.entry(destination.clone()).or_insert_with(|| {
diagnostics.push(format!(
"structure destination {} has been referenced but does not exist",
destination_identifier(destination)
));
// pdfTeX leaves the missing destination in the free list.
objects.push(Vec::new());
objects.len()
});
write!(&mut output, " /SD {id} 0 R").unwrap();
}
Some(StructureTarget::Remote(bytes)) => {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(bytes);
}
None => {}
}
output.extend_from_slice(b"\n>>");
}
@@ -1784,7 +1814,7 @@ fn write_catalog_action(
objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes());
objects.push(format!(
"<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>",
page_ids[0]
pages[0]
).into_bytes());
thread
}));
@@ -1803,8 +1833,7 @@ fn write_catalog_action(
output.extend_from_slice(b" >>");
}
}
objects.push(output);
objects.len()
output
}
#[derive(Clone, Default)]
@@ -2180,9 +2209,8 @@ fn write_pdf(
}
}
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
let mut numbers = BTreeMap::new();
let mut navigation = PdfNavigation::default();
let mut annotation_actions = Vec::new();
let pdf_version = pages
.first()
.and_then(|page| page.pdf.as_ref())
@@ -2342,7 +2370,7 @@ fn write_pdf(
} else {
format!(" /Annots [{annotation_refs}]")
};
page_ids.push(page_id);
navigation.pages.push(page_id);
kids.push(format!("{page_id} 0 R"));
let decorated = !list.pdf_resources.attributes.is_empty();
let mut page = b"<< /Type /Page".to_vec();
@@ -2435,25 +2463,33 @@ fn write_pdf(
use crate::pdf_device::links::AnnotationAction;
let [left, top, right, bottom] = annotation.rect;
let coordinates = [left, height - bottom, right, height - top].map(physical);
let action = match &annotation.action {
AnnotationAction::User(raw) => raw.clone(),
AnnotationAction::GotoName(name) =>
format!("/Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)),
};
let entries = remapped.as_ref().and_then(|resources|
resources.annotations[page_index][index].as_deref());
let body = if let Some(entries) = entries {
let mut body = if let Some(entries) = entries {
let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes();
body.extend_from_slice(entries);
if matches!(annotation.action, AnnotationAction::GotoName(_)) {
body.extend_from_slice(action.as_bytes());
}
body.extend_from_slice(b" >>");
body
} else {
format!("<< /Type /Annot {} /Rect [{}] {} >>",
annotation.attributes, coordinates.join(" "), action).into_bytes()
format!("<< /Type /Annot {} /Rect [{}] ",
annotation.attributes, coordinates.join(" ")).into_bytes()
};
match &annotation.action {
AnnotationAction::User(raw) if entries.is_none() => body.extend_from_slice(raw.as_bytes()),
AnnotationAction::User(_) => {}
AnnotationAction::GotoName(name) => {
write!(&mut body, " /Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)).unwrap();
}
AnnotationAction::Catalog(action) => {
// A local action may use a structure or page in a later shipout.
body.extend_from_slice(b" /Subtype /Link /A ");
annotation_actions.push((id, body, action));
if id == objects.len() + 1 {
objects.push(Vec::new());
}
continue;
}
}
body.extend_from_slice(b" >>");
if id == objects.len() + 1 {
objects.push(body);
} else {
@@ -2477,16 +2513,32 @@ fn write_pdf(
DestinationView::FitBH => format!("/FitBH {y}"),
DestinationView::FitBV => format!("/FitBV {x}"),
};
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
destinations.entry(name.clone()).or_insert_with(object);
if let Some(number) = destination.structure {
use std::collections::btree_map::Entry;
match navigation.structures.entry(destination.destination.clone()) {
Entry::Vacant(entry) => {
let structure = remapped.as_ref().expect("structure objects were remapped")
.structure_objects[&number];
objects.push(format!("[{structure} 0 R {view}]").into_bytes());
entry.insert(objects.len());
}
Entry::Occupied(entry) => diagnostics.push(format!(
"structure destination with the same identifier ({}) has been already used, duplicate ignored",
destination_identifier(entry.key())
)),
}
DestinationId::Number(number) => {
numbers.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
} else {
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
navigation.named.entry(name.clone()).or_insert_with(object);
}
DestinationId::Number(number) => {
navigation.numbered.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
}
}
}
}
@@ -2503,6 +2555,11 @@ fn write_pdf(
}
objects[1].extend_from_slice(b" >>");
for (id, mut body, action) in annotation_actions {
body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics));
body.extend_from_slice(b" >>");
objects[id - 1] = body;
}
let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned();
if !metadata.outline.is_empty() {
let root_id = objects.len() + 1;
@@ -2538,9 +2595,9 @@ fn write_pdf(
}
for (index, entry) in metadata.outline.iter().enumerate() {
let page_id = page_ids
let page_id = navigation.pages
.get(entry.page)
.or_else(|| page_ids.last())
.or_else(|| navigation.pages.last())
.copied()
.unwrap_or(0);
let parent_id = parents[index].map_or(root_id, |parent| item_ids[parent]);
@@ -2584,30 +2641,27 @@ fn write_pdf(
catalog.push_str(&format!(" /Outlines {root_id} 0 R"));
}
let extra = unicode.and_then(|options| options.catalog);
let mut threads = BTreeMap::new();
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(|action| {
write_catalog_action(
action, &page_ids, &mut destinations, &mut numbers, &mut threads, &mut objects,
diagnostics,
)
});
let mut action_object = |action| {
let body = catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics);
objects.push(body);
objects.len()
};
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(&mut action_object);
if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) {
let action_ids: Vec<_> = extra.outlines.iter().map(|outline| {
write_catalog_action(
&outline.action, &page_ids, &mut destinations, &mut numbers, &mut threads,
&mut objects, diagnostics,
)
}).collect();
let action_ids: Vec<_> = extra.outlines.iter()
.map(|outline| action_object(&outline.action))
.collect();
let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects);
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
}
if !threads.is_empty() {
let mut ids: Vec<_> = threads.into_values().collect();
if !navigation.threads.is_empty() {
let mut ids: Vec<_> = navigation.threads.into_values().collect();
ids.sort_unstable_by(|left, right| right.cmp(left));
let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect();
objects.push(format!("[{}]", references.join(" ")).into_bytes());
catalog.push_str(&format!(" /Threads {} 0 R", objects.len()));
}
let destinations = navigation.named;
if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);