Write native PDF catalogs and open actions

This commit is contained in:
gloamxun committed 2026-11-19 08:54:04 +08:00
1 parent a53d9c9bf9
commit f4b003bd27
20 files changed
+811 -40

No files matched your search

+170 -3
View File
@@ -13,6 +13,10 @@ use flate2::write::ZlibEncoder;
use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::pdf_device::{
catalog::{CatalogAction, CatalogTarget},
links::DestinationId,
};
use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font;
#[path = "pdf_text.rs"]
@@ -1459,6 +1463,137 @@ fn write_native_font(
id
}
fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
out.extend_from_slice(b"/F ");
if file.starts_with(b"(") && file.ends_with(b")") {
out.extend_from_slice(file);
} else {
out.push(b'(');
for &byte in file {
if matches!(byte, b'(' | b')' | b'\\') {
out.push(b'\\');
}
out.push(byte);
}
out.push(b')');
}
out.push(b' ');
}
fn write_catalog_action(
action: &CatalogAction,
page_ids: &[usize],
destinations: &mut BTreeMap<String, String>,
numbers: &BTreeMap<i32, usize>,
objects: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
) -> (usize, Option<usize>) {
let mut output = b"<< ".to_vec();
let mut threads = None;
match action {
CatalogAction::User(object) => output.clone_from(object),
CatalogAction::GoTo {
target,
file,
window,
structure,
} => {
if let Some(file) = file {
pdf_file_specification(&mut output, file);
if let Some(window) = window {
write!(&mut output, "/NewWindow {window} ").unwrap();
}
output.extend_from_slice(b"/S /GoToR /D ");
} else {
output.extend_from_slice(b"/S /GoTo /D ");
}
match target {
CatalogTarget::Destination(DestinationId::Name(name)) => {
if file.is_none() && !destinations.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]));
}
output.extend_from_slice(pdf_text(name).as_bytes());
}
CatalogTarget::Destination(DestinationId::Number(number)) => {
let id = numbers.get(number).copied().unwrap_or_else(|| {
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.len()
});
write!(&mut output, "{id} 0 R").unwrap();
}
CatalogTarget::Page { number, view } => {
let index = (*number - 1) as usize;
if file.is_some() {
write!(&mut output, "[{index} ").unwrap();
} else {
let page = page_ids.get(index).copied().unwrap_or_else(|| {
diagnostics.push(format!(
"page {number} has been referenced but does not exist"
));
objects.push(Vec::new());
objects.len()
});
write!(&mut output, "[{page} 0 R ").unwrap();
}
output.extend_from_slice(view);
output.push(b']');
}
}
if let Some(structure) = structure {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(structure);
}
output.extend_from_slice(b"\n>>");
}
CatalogAction::Thread { destination, file } => {
let mut local_id = None;
if let Some(file) = file {
pdf_file_specification(&mut output, file);
} else {
let (title, identifier) = match destination {
DestinationId::Name(name) => (name.clone(), format!("name{{{name}}}")),
DestinationId::Number(number) => (number.to_string(), format!("num{number}")),
};
diagnostics.push(format!(
"thread destination {identifier} has been referenced but does not exist, replaced by a fixed one"
));
// There are no thread definitions yet. As pdfTeX does for an
// undefined thread, link its single empty bead to the first page.
let thread = objects.len() + 1;
let bead = thread + 1;
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]
).into_bytes());
objects.push(format!("[{thread} 0 R]").into_bytes());
local_id = Some(thread);
threads = Some(objects.len());
}
output.extend_from_slice(b"/S /Thread /D ");
match destination {
DestinationId::Name(name) => output.extend_from_slice(pdf_text(name).as_bytes()),
DestinationId::Number(number) => {
if let Some(id) = local_id {
write!(&mut output, "{id} 0 R").unwrap();
} else {
write!(&mut output, "{number}").unwrap();
}
}
}
output.extend_from_slice(b" >>");
}
}
objects.push(output);
(objects.len(), threads)
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
@@ -1718,6 +1853,7 @@ 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 form_ids = BTreeMap::new();
for list in pages {
for item in &list.items {
@@ -1935,7 +2071,18 @@ fn write_pdf(
DestinationView::FitBH => format!("/FitBH {y}"),
DestinationView::FitBV => format!("/FitBV {x}"),
};
destinations.entry(destination.name.clone()).or_insert_with(|| format!("[{page_id} 0 R {view}]"));
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
destinations.entry(name.clone()).or_insert_with(object);
}
DestinationId::Number(number) => {
numbers.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
}
}
}
}
objects[1] = format!(
@@ -2025,6 +2172,15 @@ fn write_pdf(
.into_bytes();
catalog.push_str(&format!(" /Outlines {root_id} 0 R"));
}
let extra = unicode.and_then(|options| options.catalog);
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(|action| {
write_catalog_action(
action, &page_ids, &mut destinations, &numbers, &mut objects, diagnostics,
)
});
if let Some((_, Some(threads))) = action {
catalog.push_str(&format!(" /Threads {threads} 0 R"));
}
if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);
@@ -2037,8 +2193,19 @@ fn write_pdf(
entries.join(" ")).into_bytes());
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
}
catalog.push_str(" >>");
objects[0] = catalog.into_bytes();
let mut catalog = catalog.into_bytes();
if let Some(extra) = extra {
if !extra.entries.is_empty() {
catalog.push(b'\n');
catalog.extend_from_slice(&extra.entries);
catalog.push(b'\n');
}
if let Some((id, _)) = action {
write!(&mut catalog, " /OpenAction {id} 0 R").unwrap();
}
}
catalog.extend_from_slice(b" >>");
objects[0] = catalog;
let info_ref = match metadata_object(metadata) {
Some(object) => {