Resolve XDV named destinations at PDF shipout
This commit is contained in:
1 parent
dd695a8945
commit
cc147e93d8
12 files changed
+456
-9
No files matched your search
@@ -101,10 +101,12 @@ pub struct PageDestination {
|
||||
pub struct PageLinks {
|
||||
pub annotations: Vec<LinkAnnotation>,
|
||||
pub destinations: Vec<PageDestination>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub(crate) xdv_destinations: Vec<super::xdv_destination::Destination>,
|
||||
}
|
||||
|
||||
impl PageLinks {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.annotations.is_empty() && self.destinations.is_empty()
|
||||
self.annotations.is_empty() && self.destinations.is_empty() && self.xdv_destinations.is_empty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! The symbolic operands of a shipped XDV named destination.
|
||||
use lopdf::Object;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::page_resources::{parse_name, parse_value};
|
||||
use super::{PdfFileOptions, magnify, print_sp};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(crate) struct Setup {
|
||||
major: Option<i32>,
|
||||
minor: Option<u8>,
|
||||
pub(crate) keep_destinations: bool,
|
||||
}
|
||||
|
||||
impl Setup {
|
||||
pub(crate) fn is_default(&self) -> bool {
|
||||
self == &Self::default()
|
||||
}
|
||||
|
||||
pub(crate) fn set_version(&mut self, major: bool, input: &[u8]) -> Result<(), String> {
|
||||
let input = input.trim_ascii_start();
|
||||
let input = input.strip_prefix(b"=").unwrap_or(input).trim_ascii();
|
||||
let value = std::str::from_utf8(input)
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<i32>().ok())
|
||||
.ok_or("invalid XDV PDF version special")?;
|
||||
if major && value >= 1 {
|
||||
self.major = Some(value);
|
||||
} else if !major && (0..=9).contains(&value) {
|
||||
self.minor = Some(value as u8);
|
||||
} else {
|
||||
return Err("invalid XDV PDF version special".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn configure(&mut self, input: &[u8]) -> Result<(), String> {
|
||||
let mut words = input
|
||||
.split(|b| b.is_ascii_whitespace())
|
||||
.filter(|word| !word.is_empty());
|
||||
if words.next() != Some(b"C") {
|
||||
return Err("unsupported XDV configuration option".into());
|
||||
}
|
||||
let value = words
|
||||
.next()
|
||||
.and_then(|word| std::str::from_utf8(word).ok())
|
||||
.ok_or("invalid XDV configuration flags")?;
|
||||
let (sign, digits) = if let Some(rest) = value.strip_prefix('-') {
|
||||
(-1, rest)
|
||||
} else {
|
||||
(1, value.strip_prefix('+').unwrap_or(value))
|
||||
};
|
||||
let (radix, digits) = if let Some(rest) = digits
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| digits.strip_prefix("0X"))
|
||||
{
|
||||
(16, rest)
|
||||
} else if digits.starts_with('0') {
|
||||
(8, digits)
|
||||
} else {
|
||||
(10, digits)
|
||||
};
|
||||
let flags =
|
||||
u32::from_str_radix(digits, radix).map_err(|_| "invalid XDV configuration flags")?;
|
||||
if words.next().is_some() || flags & !0x10 != 0 {
|
||||
return Err("unsupported XDV configuration flags".into());
|
||||
}
|
||||
if (sign < 0 && flags != 0) || flags & 0x10 != 0 {
|
||||
self.keep_destinations = flags & 0x10 != 0;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn apply_version(&self, options: &mut PdfFileOptions) {
|
||||
if let Some(value) = self.major {
|
||||
options.major = value;
|
||||
}
|
||||
if let Some(value) = self.minor {
|
||||
options.minor = value;
|
||||
}
|
||||
if options.major == 1 && options.minor < 5 {
|
||||
options.object_compression = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Destination {
|
||||
pub(crate) name: Vec<u8>,
|
||||
pub(crate) page: usize,
|
||||
view: String,
|
||||
operands: Vec<Operand>,
|
||||
point: [i64; 2],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
enum Operand {
|
||||
Number(String),
|
||||
Null,
|
||||
CurrentX,
|
||||
CurrentY,
|
||||
}
|
||||
|
||||
fn trim_pdf(mut bytes: &[u8]) -> &[u8] {
|
||||
loop {
|
||||
bytes = bytes.trim_ascii_start();
|
||||
if !bytes.starts_with(b"%") {
|
||||
return bytes;
|
||||
}
|
||||
bytes = bytes
|
||||
.iter()
|
||||
.position(|byte| matches!(byte, b'\r' | b'\n'))
|
||||
.map_or(&[][..], |end| &bytes[end + 1..]);
|
||||
}
|
||||
}
|
||||
|
||||
fn split_string(bytes: &[u8]) -> Result<(&[u8], &[u8]), String> {
|
||||
let end = match bytes.first() {
|
||||
Some(b'<') => bytes.iter().position(|&byte| byte == b'>'),
|
||||
Some(b'(') => {
|
||||
let mut depth = 1;
|
||||
let mut cursor = bytes.iter().enumerate().skip(1);
|
||||
loop {
|
||||
match cursor.next() {
|
||||
Some((_, b'\\')) => {
|
||||
cursor.next();
|
||||
}
|
||||
Some((_, b'(')) => depth += 1,
|
||||
Some((index, b')')) => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break Some(index);
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break None,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
.ok_or("pdf:dest requires a destination string")?;
|
||||
Ok(bytes.split_at(end + 1))
|
||||
}
|
||||
|
||||
fn atom(bytes: &[u8]) -> (&[u8], &[u8]) {
|
||||
let bytes = trim_pdf(bytes);
|
||||
let end = bytes
|
||||
.iter()
|
||||
.skip(1)
|
||||
.position(|&b| {
|
||||
b.is_ascii_whitespace()
|
||||
|| matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'/' | b'%')
|
||||
})
|
||||
.map_or(bytes.len(), |index| index + 1);
|
||||
bytes.split_at(end)
|
||||
}
|
||||
|
||||
impl Destination {
|
||||
pub(crate) fn parse(
|
||||
input: &[u8],
|
||||
current_page: usize,
|
||||
point: [i64; 2],
|
||||
) -> Result<Self, String> {
|
||||
let (name, rest) = split_string(trim_pdf(input))?;
|
||||
let Object::String(name, _) = parse_value(name)? else {
|
||||
return Err("pdf:dest requires a destination string".into());
|
||||
};
|
||||
let array = trim_pdf(rest)
|
||||
.strip_prefix(b"[")
|
||||
.ok_or("pdf:dest requires an array")?;
|
||||
let (page, rest) = atom(array);
|
||||
let page = match page {
|
||||
b"@thispage" => Some(current_page),
|
||||
b"@prevpage" => current_page.checked_sub(1).filter(|number| *number != 0),
|
||||
b"@nextpage" => current_page.checked_add(1),
|
||||
_ => page
|
||||
.strip_prefix(b"@page")
|
||||
.and_then(|number| std::str::from_utf8(number).ok())
|
||||
.and_then(|number| number.parse::<usize>().ok())
|
||||
.filter(|number| *number != 0),
|
||||
}
|
||||
.ok_or("pdf:dest requires an XDV page reference")?;
|
||||
let (view, mut rest) = atom(rest);
|
||||
let view = parse_name(view)?;
|
||||
let count = match view.as_slice() {
|
||||
b"Fit" | b"FitB" => 0,
|
||||
b"FitH" | b"FitV" | b"FitBH" | b"FitBV" => 1,
|
||||
b"XYZ" => 3,
|
||||
b"FitR" => 4,
|
||||
_ => return Err("unsupported XDV destination view".into()),
|
||||
};
|
||||
let mut operands = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let (token, tail) = atom(rest);
|
||||
let operand = match token {
|
||||
b"@xpos" => Operand::CurrentX,
|
||||
b"@ypos" => Operand::CurrentY,
|
||||
b"null" => Operand::Null,
|
||||
number => match parse_value(number)? {
|
||||
Object::Integer(_) | Object::Real(_) => Operand::Number(
|
||||
std::str::from_utf8(number)
|
||||
.map_err(|_| "invalid XDV destination number")?
|
||||
.into(),
|
||||
),
|
||||
_ => return Err("invalid XDV destination coordinate".into()),
|
||||
},
|
||||
};
|
||||
operands.push(operand);
|
||||
rest = tail;
|
||||
}
|
||||
let tail = trim_pdf(rest)
|
||||
.strip_prefix(b"]")
|
||||
.ok_or("invalid XDV destination array length")?;
|
||||
if !trim_pdf(tail).is_empty() {
|
||||
return Err("unexpected material after XDV destination array".into());
|
||||
}
|
||||
let view = String::from_utf8(view).expect("known destination view is ASCII");
|
||||
Ok(Self {
|
||||
name,
|
||||
page,
|
||||
view,
|
||||
operands,
|
||||
point,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn array(&self, page_object: usize, height: i64, magnification: i32) -> String {
|
||||
let mut output = format!("[{page_object} 0 R /{}", self.view);
|
||||
for operand in &self.operands {
|
||||
use std::fmt::Write as _;
|
||||
match operand {
|
||||
Operand::Number(text) => write!(output, " {text}").unwrap(),
|
||||
Operand::Null => output.push_str(" null"),
|
||||
Operand::CurrentX | Operand::CurrentY => {
|
||||
let value = match operand {
|
||||
Operand::CurrentX => self.point[0],
|
||||
_ => height - self.point[1],
|
||||
};
|
||||
write!(output, " {}", print_sp(magnify(value, magnification), 2)).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
output.push(']');
|
||||
output
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user