Write native PDF catalogs and open actions
This commit is contained in:
1 parent
a53d9c9bf9
commit
f4b003bd27
20 files changed
+811
-40
No files matched your search
@@ -22,6 +22,7 @@ mod nesting;
|
||||
mod page;
|
||||
mod paragraphs;
|
||||
mod pdf_color;
|
||||
mod pdf_catalog;
|
||||
mod pdf_graphics;
|
||||
mod pdf_links;
|
||||
mod pdf_image;
|
||||
@@ -162,6 +163,7 @@ pub struct Executor {
|
||||
io: IoState,
|
||||
pdf_colors: crate::pdf_device::PdfColorStacks,
|
||||
pdf_link_stack: Vec<pdf_links::ActiveLink>,
|
||||
pdf_catalog_tokens: Vec<Token>,
|
||||
pdf_images: Vec<pdf_image::RegisteredImage>,
|
||||
input_position: Option<(usize, usize)>,
|
||||
paragraph: Option<super::paragraph::Builder>,
|
||||
@@ -230,6 +232,7 @@ impl Executor {
|
||||
io: IoState::default(),
|
||||
pdf_colors: Default::default(),
|
||||
pdf_link_stack: Vec::new(),
|
||||
pdf_catalog_tokens: Vec::new(),
|
||||
pdf_images: Vec::new(),
|
||||
input_position: None,
|
||||
paragraph: None,
|
||||
@@ -2936,7 +2939,10 @@ impl Executor {
|
||||
) -> Result<(), Error> {
|
||||
self.check_cancellation()?;
|
||||
self.change_interaction_mode(self.interaction_mode, files)?;
|
||||
if let Err(mut error) = self.run_input(file, files) {
|
||||
let result = self
|
||||
.run_input(file, files)
|
||||
.and_then(|()| self.finish_pdf_catalog());
|
||||
if let Err(mut error) = result {
|
||||
if let Err(sink) = files.observe_error(&error) {
|
||||
error
|
||||
.message
|
||||
@@ -3349,6 +3355,7 @@ impl Executor {
|
||||
Pdfstartlink | Pdfendlink | Pdfdest => {
|
||||
self.scan_pdf_link(primitive, token.span, files)?;
|
||||
}
|
||||
Pdfcatalog => self.scan_pdf_catalog(files)?,
|
||||
Pdfximage => self.scan_pdf_image(&token, false, files)?,
|
||||
Pdfrefximage => self.reference_pdf_image(&token, files)?,
|
||||
_ => {
|
||||
|
||||
@@ -550,7 +550,7 @@ impl Executor {
|
||||
Vcenter => self.box_command(*p, boxes::Destination::Append, token.span, files)?,
|
||||
Hbox | Vbox | Vtop | Box | Copy | Setbox | Wd | Ht | Dp | Lastbox | Raise
|
||||
| Lower | Vsplit | Mark | Marks | Vadjust | Insert | Shipout | Openout
|
||||
| Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore
|
||||
| Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfcatalog
|
||||
| Ignorespaces | Unskip | Unkern | Unpenalty => {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
use super::*;
|
||||
use crate::pdf_device::{
|
||||
catalog::{CatalogAction, CatalogTarget},
|
||||
links::DestinationId,
|
||||
};
|
||||
|
||||
impl Executor {
|
||||
pub(super) fn scan_pdf_tokens(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<Vec<Token>, Error> {
|
||||
self.with_scanner(ScannerStatus::Absorbing, |s| {
|
||||
s.scan_expanded_group_mode(files, false)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn positive_pdf_number(
|
||||
&mut self,
|
||||
description: &str,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<i32, Error> {
|
||||
let number = self.integer(files)?;
|
||||
if number <= 0 {
|
||||
return self.fail(format!("PDF {description} must be positive"));
|
||||
}
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
|
||||
let text = self.token_list_text(tokens);
|
||||
if text.len() > self.limits.tokens {
|
||||
return self.fail("native PDF token output limit exceeded");
|
||||
}
|
||||
if self.state.input_profile() == InputProfile::TeX8Bit {
|
||||
text.chars()
|
||||
.map(|character| {
|
||||
u8::try_from(u32::from(character)).map_err(|_| {
|
||||
self.error("PDF token is outside the 8-bit profile", self.current)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Ok(text.into_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
|
||||
let tokens = self.scan_pdf_tokens(files)?;
|
||||
self.pdf_token_bytes(&tokens)
|
||||
}
|
||||
|
||||
fn scan_catalog_target(
|
||||
&mut self,
|
||||
goto: bool,
|
||||
remote: bool,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<CatalogTarget, Error> {
|
||||
if self.keyword("page", files)? {
|
||||
if !goto {
|
||||
return self.fail("only PDF GoTo actions can target a page");
|
||||
}
|
||||
let number = self.positive_pdf_number("page number", files)?;
|
||||
let view = self.scan_pdf_bytes(files)?;
|
||||
Ok(CatalogTarget::Page { number, view })
|
||||
} else if self.keyword("name", files)? {
|
||||
let tokens = self.scan_pdf_tokens(files)?;
|
||||
Ok(CatalogTarget::Destination(DestinationId::Name(
|
||||
self.token_list_text(&tokens),
|
||||
)))
|
||||
} else if self.keyword("num", files)? {
|
||||
if goto && remote {
|
||||
return self.fail("PDF goto cannot use both file and num");
|
||||
}
|
||||
let number = self.positive_pdf_number("destination number", files)?;
|
||||
Ok(CatalogTarget::Destination(DestinationId::Number(number)))
|
||||
} else {
|
||||
self.fail("PDF action destination type missing")
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_catalog_action(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<CatalogAction, Error> {
|
||||
if self.keyword("user", files)? {
|
||||
return self.scan_pdf_bytes(files).map(CatalogAction::User);
|
||||
}
|
||||
let goto = self.keyword("goto", files)?;
|
||||
if !goto && !self.keyword("thread", files)? {
|
||||
return self.fail("PDF action type missing");
|
||||
}
|
||||
let file = if self.keyword("file", files)? {
|
||||
Some(self.scan_pdf_bytes(files)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let structure = if self.keyword("struct", files)? {
|
||||
if !goto || file.is_none() {
|
||||
return self.fail("current PDF structure actions require a remote GoTo");
|
||||
}
|
||||
Some(self.scan_pdf_bytes(files)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let target = self.scan_catalog_target(goto, file.is_some(), files)?;
|
||||
let window = if self.keyword("newwindow", files)? {
|
||||
Some(true)
|
||||
} else if self.keyword("nonewwindow", files)? {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if window.is_some() {
|
||||
if !goto || file.is_none() {
|
||||
return self.fail("PDF newwindow/nonewwindow requires goto with file");
|
||||
}
|
||||
if let Some(next) = self.expanded(files)? {
|
||||
if !self.is_spacer(&next.token) {
|
||||
self.unread(next)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if goto {
|
||||
Ok(CatalogAction::GoTo {
|
||||
target,
|
||||
file,
|
||||
window,
|
||||
structure,
|
||||
})
|
||||
} else {
|
||||
let CatalogTarget::Destination(destination) = target else {
|
||||
unreachable!("thread page targets were rejected while scanning")
|
||||
};
|
||||
Ok(CatalogAction::Thread { destination, file })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn scan_pdf_catalog(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
let enabled = self.read_parameter(Parameter::Pdfoutput).width() > 0;
|
||||
if !enabled {
|
||||
let text = "pdfTeX warning (\\pdfcatalog): not allowed in DVI mode (\\pdfoutput <= 0); ignoring it";
|
||||
files
|
||||
.observe_message(text)
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
self.events.push(Event::Message {
|
||||
text: text.into(),
|
||||
span: self.current,
|
||||
});
|
||||
}
|
||||
let tokens = self.scan_pdf_tokens(files)?;
|
||||
if enabled {
|
||||
if self.pdf_catalog_tokens.len().saturating_add(tokens.len()) > self.limits.tokens {
|
||||
return self.fail("native PDF catalog token limit exceeded");
|
||||
}
|
||||
self.pdf_catalog_tokens.extend(tokens);
|
||||
}
|
||||
if self.keyword("openaction", files)? {
|
||||
self.reads.insert(Dependency::PdfCatalogState);
|
||||
if enabled
|
||||
&& self
|
||||
.state
|
||||
.pdf_catalog
|
||||
.as_ref()
|
||||
.is_some_and(|catalog| catalog.open_action.is_some())
|
||||
{
|
||||
return self.fail("PDF catalog duplicate of openaction");
|
||||
}
|
||||
let action = self.scan_catalog_action(files)?;
|
||||
if enabled {
|
||||
// An action allocates a PDF object at the command boundary.
|
||||
self.pdf_page_data(files)?;
|
||||
self.state
|
||||
.pdf_catalog
|
||||
.get_or_insert_with(Default::default)
|
||||
.open_action = Some(action);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn finish_pdf_catalog(&mut self) -> Result<(), Error> {
|
||||
if !self.pdf_catalog_tokens.is_empty() {
|
||||
let tokens = std::mem::take(&mut self.pdf_catalog_tokens);
|
||||
let bytes = self.pdf_token_bytes(&tokens)?;
|
||||
self.state
|
||||
.pdf_catalog
|
||||
.get_or_insert_with(Default::default)
|
||||
.entries
|
||||
.extend(bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
use crate::pdf_device::{
|
||||
Affine, PdfGraphics,
|
||||
links::{
|
||||
AnnotationAction, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart,
|
||||
AnnotationAction, DestinationId, DestinationView, LinkAction, LinkAnnotation, LinkNode, LinkStart,
|
||||
PageDestination, PageLinks,
|
||||
},
|
||||
};
|
||||
@@ -100,12 +100,6 @@ impl ActiveLink {
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
fn link_tokens(&mut self, files: &mut impl SourceProvider) -> Result<Vec<Token>, Error> {
|
||||
self.with_scanner(ScannerStatus::Absorbing, |s| {
|
||||
s.scan_expanded_group_mode(files, false)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn scan_pdf_link(
|
||||
&mut self,
|
||||
command: Primitive,
|
||||
@@ -138,14 +132,14 @@ impl Executor {
|
||||
*target = Some(self.dimension(false, false, files)?.amount);
|
||||
}
|
||||
let attributes = if self.keyword("attr", files)? {
|
||||
self.link_tokens(files)?
|
||||
self.scan_pdf_tokens(files)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let action = if self.keyword("user", files)? {
|
||||
LinkAction::User(self.link_tokens(files)?)
|
||||
LinkAction::User(self.scan_pdf_tokens(files)?)
|
||||
} else if self.keyword("goto", files)? && self.keyword("name", files)? {
|
||||
LinkAction::GotoName(self.link_tokens(files)?)
|
||||
LinkAction::GotoName(self.scan_pdf_tokens(files)?)
|
||||
} else {
|
||||
return self.fail("expected a user or named goto PDF link action");
|
||||
};
|
||||
@@ -159,10 +153,13 @@ impl Executor {
|
||||
}
|
||||
Primitive::Pdfendlink => LinkNode::End,
|
||||
Primitive::Pdfdest => {
|
||||
if !self.keyword("name", files)? {
|
||||
return self.fail("expected a named PDF destination");
|
||||
}
|
||||
let name = self.link_tokens(files)?;
|
||||
let destination = if self.keyword("name", files)? {
|
||||
DestinationId::Name(self.scan_pdf_tokens(files)?)
|
||||
} else if self.keyword("num", files)? {
|
||||
DestinationId::Number(self.positive_pdf_number("destination number", files)?)
|
||||
} else {
|
||||
return self.fail("expected a PDF destination identifier");
|
||||
};
|
||||
let view = if self.keyword("xyz", files)? {
|
||||
let zoom = if self.keyword("zoom", files)? {
|
||||
Some(self.integer(files)?)
|
||||
@@ -187,7 +184,7 @@ impl Executor {
|
||||
}
|
||||
view.ok_or_else(|| self.error("expected PDF destination view", span))?
|
||||
};
|
||||
LinkNode::Destination { name, view }
|
||||
LinkNode::Destination { destination, view }
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
@@ -276,9 +273,15 @@ impl Executor {
|
||||
}
|
||||
link.end_segment(&mut output, x, margin);
|
||||
}
|
||||
LinkNode::Destination { name, view } => output.destinations.push(PageDestination {
|
||||
name: self.token_list_text(name), point: map_point(transform.0, x, y), view: *view,
|
||||
}),
|
||||
LinkNode::Destination { destination, view } => {
|
||||
let destination = match destination {
|
||||
DestinationId::Name(tokens) => DestinationId::Name(self.token_list_text(tokens)),
|
||||
DestinationId::Number(number) => DestinationId::Number(*number),
|
||||
};
|
||||
output.destinations.push(PageDestination {
|
||||
destination, point: map_point(transform.0, x, y), view: *view,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -71,6 +71,7 @@ impl Executor {
|
||||
if self.after_assignment.is_some() {
|
||||
c.usage.token_list_cells += 1;
|
||||
}
|
||||
c.usage.token_list_cells += self.pdf_catalog_tokens.len();
|
||||
for input in &self.inputs {
|
||||
match input {
|
||||
InputFrame::Source { mouth, .. } => {
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{
|
||||
path::Path,
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 22;
|
||||
const SCHEMA: u32 = 23;
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -352,6 +352,7 @@ pub enum Dependency {
|
||||
Parameter(Parameter),
|
||||
MagnificationState,
|
||||
PdfFileState,
|
||||
PdfCatalogState,
|
||||
PdfImages,
|
||||
GlyphUnicode,
|
||||
ResourceStatistics,
|
||||
|
||||
@@ -108,6 +108,7 @@ pub enum Primitive {
|
||||
Pdfstartlink,
|
||||
Pdfendlink,
|
||||
Pdfdest,
|
||||
Pdfcatalog,
|
||||
Pdfsetmatrix,
|
||||
Pdfrestore,
|
||||
Pdfglyphtounicode,
|
||||
@@ -594,6 +595,8 @@ pub struct State {
|
||||
pub(super) magnification_set: Option<i32>,
|
||||
pub(super) output_mode_set: Option<i32>,
|
||||
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
|
||||
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
|
||||
pub(super) hyphenation: super::hyphenation::HyphenationData,
|
||||
}
|
||||
@@ -634,6 +637,7 @@ impl Default for State {
|
||||
magnification_set: None,
|
||||
output_mode_set: None,
|
||||
pdf_file_options: None,
|
||||
pdf_catalog: None,
|
||||
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
|
||||
hyphenation: super::hyphenation::HyphenationData::default(),
|
||||
};
|
||||
@@ -854,6 +858,7 @@ impl Default for State {
|
||||
("pdfstartlink", Pdfstartlink),
|
||||
("pdfendlink", Pdfendlink),
|
||||
("pdfdest", Pdfdest),
|
||||
("pdfcatalog", Pdfcatalog),
|
||||
("pdfsetmatrix", Pdfsetmatrix),
|
||||
("pdfrestore", Pdfrestore),
|
||||
("pdfglyphtounicode", Pdfglyphtounicode),
|
||||
@@ -1239,6 +1244,7 @@ impl State {
|
||||
self.magnification_set = None;
|
||||
self.output_mode_set = None;
|
||||
self.pdf_file_options = None;
|
||||
self.pdf_catalog = None;
|
||||
self
|
||||
}
|
||||
pub fn is_initex(&self) -> bool {
|
||||
@@ -1251,6 +1257,7 @@ impl State {
|
||||
compression: self.parameter(Parameter::Pdfcompresslevel).width(),
|
||||
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
|
||||
glyph_unicode: &self.glyph_unicode,
|
||||
catalog: self.pdf_catalog.as_deref(),
|
||||
}
|
||||
}
|
||||
/// Job-wide decoding choice; it is not a scoped TeX assignment.
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -74,4 +74,5 @@ pub(crate) use color::{ColorResult, PdfColorStacks};
|
||||
pub use color::{PdfColorProgram, PdfColorStackAction};
|
||||
pub(crate) use graphics::Affine;
|
||||
pub use graphics::{PdfGraphics, PdfMatrix};
|
||||
pub mod catalog;
|
||||
pub mod links;
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Job-global additions to the PDF catalog and its initial action.
|
||||
use super::links::DestinationId;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfCatalog {
|
||||
pub(crate) entries: Vec<u8>,
|
||||
pub(crate) open_action: Option<CatalogAction>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum CatalogAction {
|
||||
User(Vec<u8>),
|
||||
GoTo {
|
||||
target: CatalogTarget,
|
||||
file: Option<Vec<u8>>,
|
||||
window: Option<bool>,
|
||||
structure: Option<Vec<u8>>,
|
||||
},
|
||||
Thread {
|
||||
destination: DestinationId<String>,
|
||||
file: Option<Vec<u8>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub(crate) enum CatalogTarget {
|
||||
Destination(DestinationId<String>),
|
||||
Page { number: i32, view: Vec<u8> },
|
||||
}
|
||||
@@ -27,12 +27,20 @@ pub enum DestinationView {
|
||||
FitBV,
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
|
||||
)]
|
||||
pub enum DestinationId<T> {
|
||||
Name(T),
|
||||
Number(i32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum LinkNode {
|
||||
Start(LinkStart),
|
||||
End,
|
||||
Destination {
|
||||
name: Vec<Token>,
|
||||
destination: DestinationId<Vec<Token>>,
|
||||
view: DestinationView,
|
||||
},
|
||||
}
|
||||
@@ -53,7 +61,7 @@ pub struct LinkAnnotation {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PageDestination {
|
||||
pub name: String,
|
||||
pub destination: DestinationId<String>,
|
||||
pub point: [i64; 2],
|
||||
pub view: DestinationView,
|
||||
}
|
||||
|
||||
@@ -32,9 +32,16 @@ pub(super) fn serialize(
|
||||
let mut pdf = format!("%PDF-{}.{}\n", options.major, options.minor).into_bytes();
|
||||
let mut offsets = vec![0u64; objects.len() + 1];
|
||||
let mut packed = vec![None; objects.len() + 1];
|
||||
let mut free = vec![None; objects.len() + 1];
|
||||
let mut last_free = 0;
|
||||
let mut groups: Vec<Vec<usize>> = Vec::new();
|
||||
for (i, body) in objects.iter().enumerate() {
|
||||
let id = i + 1;
|
||||
if body.is_empty() {
|
||||
free[last_free] = Some(id);
|
||||
last_free = id;
|
||||
continue;
|
||||
}
|
||||
let level = if Some(id) == info {
|
||||
3
|
||||
} else if body.windows(19).any(|s| s == b"/Subtype /TrueType ")
|
||||
@@ -61,6 +68,7 @@ pub(super) fn serialize(
|
||||
pdf.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
}
|
||||
free[last_free] = Some(0);
|
||||
for (i, ids) in groups.iter().enumerate() {
|
||||
let id = objects.len() + 1 + i;
|
||||
offsets.push(pdf.len() as u64);
|
||||
@@ -86,11 +94,14 @@ pub(super) fn serialize(
|
||||
let info_ref = info.map_or_else(String::new, |id| format!(" /Info {id} 0 R"));
|
||||
let xref = pdf.len();
|
||||
if options.object_compression == 0 {
|
||||
pdf.extend_from_slice(
|
||||
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
|
||||
);
|
||||
for off in offsets.iter().skip(1) {
|
||||
pdf.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
|
||||
pdf.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
|
||||
for (id, (offset, next)) in offsets.iter().zip(&free).enumerate() {
|
||||
if let Some(next) = next {
|
||||
let generation = if id == 0 { 65535 } else { 0 };
|
||||
pdf.extend_from_slice(format!("{next:010} {generation:05} f \n").as_bytes());
|
||||
} else {
|
||||
pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
}
|
||||
pdf.extend_from_slice(
|
||||
format!(
|
||||
@@ -104,8 +115,8 @@ pub(super) fn serialize(
|
||||
offsets.push(xref as u64);
|
||||
let mut entries = Vec::new();
|
||||
for (obj, offset) in offsets.iter().enumerate() {
|
||||
let (kind, a, b) = if obj == 0 {
|
||||
(0u8, 0u64, 65535u32)
|
||||
let (kind, a, b) = if let Some(Some(next)) = free.get(obj) {
|
||||
(0u8, *next as u64, if obj == 0 { 65535 } else { 0 })
|
||||
} else if let Some(Some((stm, index))) = packed.get(obj) {
|
||||
(2, *stm as u64, *index as u32)
|
||||
} else {
|
||||
|
||||
@@ -122,12 +122,13 @@ impl GlyphUnicodeMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters consumed when final font objects are written, after all shipouts.
|
||||
/// Parameters and job data consumed by the PDF writer after all shipouts.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PdfFinalOptions<'a> {
|
||||
pub compression: i32,
|
||||
pub generate_unicode: i32,
|
||||
pub glyph_unicode: &'a GlyphUnicodeMap,
|
||||
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in new issue
Block a user