Apply native PDF page dictionaries and viewport projection

This commit is contained in:
gloamxun committed 2026-11-21 03:31:00 +08:00
1 parent a6ba70aa46
commit d1ddf4bfeb
19 files changed
+410 -40

No files matched your search

@@ -0,0 +1,187 @@
//! Page dictionaries affect the PDF viewport independently of TeX's canvas.
use super::{
Affine, magnify,
page_resources::{PdfObjects, parse_entries, resolve_value},
print_sp,
};
use crate::render::DisplayList;
use lopdf::{Dictionary, Object};
/// The reference device suppresses its generated box when the token text
/// contains this spelling, even before the PDF consumer parses the dictionary.
pub(crate) fn supplies_media_box(attributes: &[u8]) -> bool {
attributes
.windows(b"/MediaBox".len())
.any(|part| part == b"/MediaBox")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Viewport {
crop: [u64; 4],
rotation: i64,
user_unit: u64,
}
impl Viewport {
pub(crate) fn unit(&self) -> f64 {
f64::from_bits(self.user_unit)
}
pub(crate) fn dimensions(&self) -> [f64; 2] {
let [x0, y0, x1, y1] = self.crop.map(f64::from_bits);
let [width, height] = [(x1 - x0) * self.unit(), (y1 - y0) * self.unit()];
if matches!(self.rotation, 90 | 270) {
[height, width]
} else {
[width, height]
}
}
/// Map y-down coordinates on the original TeX canvas to the PDF viewport.
pub(crate) fn transform(&self, original_height: f64) -> Affine {
let [x0, y0, x1, y1] = self.crop.map(f64::from_bits);
let matrix = match self.rotation {
90 => [0.0, 1.0, -1.0, 0.0, original_height - y0, -x0],
180 => [-1.0, 0.0, 0.0, -1.0, x1, original_height - y0],
270 => [0.0, -1.0, 1.0, 0.0, y1 - original_height, x1],
_ => [1.0, 0.0, 0.0, 1.0, -x0, y1 - original_height],
};
Affine(matrix.map(|value| value * self.unit()))
}
}
pub(crate) fn resolve(
pages: &mut [DisplayList],
root_bytes: &[u8],
objects: &PdfObjects,
) -> Result<(), String> {
if root_bytes.is_empty()
&& pages
.iter()
.all(|page| page.pdf_resources.attributes.is_empty())
{
return Ok(());
}
let root = parse_entries(root_bytes)?;
for page in pages {
let Some(pdf) = &page.pdf else {
continue;
};
let resource = &mut page.pdf_resources;
let local = if resource.attributes.is_empty() {
Dictionary::new()
} else {
parse_entries(&resource.attributes)?
};
// Custom content or font resources may change the meaning of native
// paint indices. Group composition still uses those same indices.
resource.overrides_paint = local.has(b"Contents") || local.has(b"Resources");
resource.needs_pdf_for_preview |= resource.overrides_paint || local.has(b"Group");
let supplied_media = supplies_media_box(&resource.attributes);
let media_value = if supplied_media {
attribute(&local, &root, b"MediaBox", objects)?
} else if local.has(b"MediaBox") {
attribute(&local, &Dictionary::new(), b"MediaBox", objects)?
} else {
None
};
let crop = attribute(&local, &root, b"CropBox", objects)?;
let rotation = attribute(&local, &root, b"Rotate", objects)?
.map_or(0, |value| value.as_i64().unwrap_or(0).rem_euclid(360));
let unit = attribute(&local, &Dictionary::new(), b"UserUnit", objects)?
.map_or(Ok(1.0), |value| finite_number(&value))?;
if unit <= 0.0 {
return Err("native PDF UserUnit must be positive".into());
}
let rotation = if rotation % 90 == 0 { rotation } else { 0 };
if !supplied_media
&& media_value.is_none()
&& crop.is_none()
&& rotation == 0
&& unit == 1.0
{
continue;
}
let dimension = |sp| {
print_sp(magnify(sp, page.magnification), pdf.file.decimal_digits)
.parse::<f64>()
.expect("formatted PDF page dimension is numeric")
};
let media = match media_value {
Some(value) => rectangle(value, objects)?,
None if supplied_media => [0.0, 0.0, 595.0, 842.0],
None => [0.0, 0.0, dimension(page.width), dimension(page.height)],
};
let crop = crop
.map(|value| rectangle(value, objects))
.transpose()?
.unwrap_or(media);
let x = crop[0].max(media[0]);
let y = crop[1].max(media[1]);
let intersection = [
x,
y,
crop[2].min(media[2]).max(x),
crop[3].min(media[3]).max(y),
];
let viewport = Viewport {
crop: intersection.map(f64::to_bits),
rotation,
user_unit: unit.to_bits(),
};
if viewport
.dimensions()
.into_iter()
.any(|value| !value.is_finite())
{
return Err("native PDF page viewport dimensions overflow".into());
}
resource.viewport = Some(viewport);
}
Ok(())
}
fn attribute(
local: &Dictionary,
root: &Dictionary,
name: &[u8],
objects: &PdfObjects,
) -> Result<Option<Object>, String> {
for dictionary in [local, root] {
if let Ok(entry) = dictionary.get(name) {
let value = resolve_value(entry.clone(), objects)?;
if !matches!(value, Object::Null) {
return Ok(Some(value));
}
}
}
Ok(None)
}
fn finite_number(value: &Object) -> Result<f64, String> {
let number = match value {
Object::Integer(n) => *n as f64,
Object::Real(n) => *n,
_ => return Err("native PDF page geometry must use numeric coordinates".into()),
};
if number.is_finite() {
Ok(number)
} else {
Err("native PDF page geometry must be finite".into())
}
}
fn rectangle(value: Object, objects: &PdfObjects) -> Result<[f64; 4], String> {
let Object::Array(values) = value else {
return Err("native PDF page box must be an array".into());
};
let Ok(values): Result<[Object; 4], _> = values.try_into() else {
return Err("native PDF page box requires four coordinates".into());
};
let [x0, y0, x1, y1] =
values.map(|entry| resolve_value(entry, objects).and_then(|v| finite_number(&v)));
let (x0, y0, x1, y1) = (x0?, y0?, x1?, y1?);
Ok([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
}
@@ -285,7 +285,10 @@ pub(crate) fn parse_name(bytes: &[u8]) -> Result<Vec<u8>, String> {
}
}
fn parse_entries(bytes: &[u8]) -> Result<Dictionary, String> {
pub(super) fn parse_entries(bytes: &[u8]) -> Result<Dictionary, String> {
if bytes.is_empty() {
return Ok(Dictionary::new());
}
let mut wrapped = b"<< ".to_vec();
wrapped.extend_from_slice(bytes);
wrapped.extend_from_slice(b"\n>>");
@@ -321,6 +324,9 @@ fn encode_value(object: Object) -> Result<Vec<u8>, String> {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PageResources {
pub(crate) entries: Arc<[u8]>,
pub(crate) attributes: Arc<[u8]>,
pub(crate) viewport: Option<super::page_attributes::Viewport>,
pub(crate) overrides_paint: bool,
pub(crate) opacity: BTreeMap<Vec<u8>, Transparency>,
pub(crate) needs_pdf_for_preview: bool,
}
@@ -331,20 +337,27 @@ pub(crate) struct Transparency {
pub stroke: Option<String>,
}
fn resolve_dictionary(entry: Object, objects: &PdfObjects) -> Result<Dictionary, String> {
let mut entry = entry;
pub(super) fn resolve_value(mut entry: Object, objects: &PdfObjects) -> Result<Object, String> {
let mut seen = BTreeSet::new();
loop {
match entry {
Object::Dictionary(dictionary) => return Ok(dictionary),
Object::Reference((number, 0)) if seen.insert(number) => {
entry = objects.written_body(number)?.parse()?;
}
_ => return Err("PDF resource must refer to a dictionary".into()),
Object::Reference(_) => return Err("invalid or circular native PDF reference".into()),
value => return Ok(value),
}
}
}
fn resolve_dictionary(entry: Object, objects: &PdfObjects) -> Result<Dictionary, String> {
if let Object::Dictionary(dictionary) = resolve_value(entry, objects)? {
Ok(dictionary)
} else {
Err("PDF resource must refer to a dictionary".into())
}
}
fn alpha(dictionary: &Dictionary, key: &[u8]) -> Result<Option<String>, String> {
let Ok(value) = dictionary.get(key) else {
return Ok(None);
@@ -363,12 +376,14 @@ fn alpha(dictionary: &Dictionary, key: &[u8]) -> Result<Option<String>, String>
impl PageResources {
pub(crate) fn from_page(
bytes: Arc<[u8]>,
attributes: Arc<[u8]>,
names: &BTreeSet<Vec<u8>>,
objects: &PdfObjects,
) -> Result<Self, String> {
if names.is_empty() {
return Ok(Self {
entries: bytes,
attributes,
..Self::default()
});
}
@@ -379,6 +394,7 @@ impl PageResources {
let definitions = resolve_dictionary(definitions.clone(), objects)?;
let mut resources = Self {
entries: bytes,
attributes,
..Self::default()
};
for name in names {
@@ -411,6 +427,8 @@ pub(crate) struct ResourceOutput {
page_references: BTreeMap<u32, u32>,
link_references: BTreeMap<u32, Option<(usize, usize)>>,
page_entries: Vec<Dictionary>,
page_attributes: Vec<Dictionary>,
page_tree_attributes: Dictionary,
font_entries: BTreeMap<FontId, Dictionary>,
annotation_entries: Vec<Vec<Option<Dictionary>>>,
catalog: Option<Dictionary>,
@@ -419,6 +437,8 @@ pub(crate) struct ResourceOutput {
pub(crate) struct RemappedResources {
pub pages: Vec<Vec<u8>>,
pub page_attributes: Vec<Vec<u8>>,
pub page_tree_attributes: Vec<u8>,
pub fonts: BTreeMap<FontId, Vec<u8>>,
pub page_objects: BTreeMap<usize, usize>,
pub link_objects: BTreeMap<(usize, usize), usize>,
@@ -432,6 +452,7 @@ impl ResourceOutput {
pages: &[crate::render::DisplayList],
objects: Option<&PdfObjects>,
fonts: BTreeMap<FontId, &[u8]>,
page_tree: &[u8],
catalog: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Self, String> {
@@ -453,10 +474,21 @@ impl ResourceOutput {
.into_iter()
.map(|(font, entries)| Ok((font, parse_entries(entries)?)))
.collect::<Result<BTreeMap<_, _>, String>>()?;
let page_attributes = pages
.iter()
.map(|page| parse_entries(&page.pdf_resources.attributes))
.collect::<Result<Vec<_>, _>>()?;
let page_tree_attributes = parse_entries(page_tree)?;
let catalog = catalog.map(parse_entries).transpose()?;
let info = info.map(parse_entries).transpose()?;
let mut pending = objects.written.clone();
for dictionary in page_entries.iter().chain(font_entries.values()).chain(&catalog).chain(&info) {
for dictionary in page_entries.iter()
.chain(&page_attributes)
.chain(std::iter::once(&page_tree_attributes))
.chain(font_entries.values())
.chain(&catalog)
.chain(&info)
{
for (_, entry) in dictionary.iter() {
references(entry, &mut pending)?;
}
@@ -522,6 +554,8 @@ impl ResourceOutput {
page_references: objects.page_references.clone(),
link_references,
page_entries,
page_attributes,
page_tree_attributes,
font_entries,
annotation_entries,
catalog,
@@ -581,6 +615,8 @@ impl ResourceOutput {
};
RemappedResources {
pages: self.page_entries.into_iter().map(&encode).collect(),
page_attributes: self.page_attributes.into_iter().map(&encode).collect(),
page_tree_attributes: encode(self.page_tree_attributes),
fonts: self.font_entries.into_iter()
.map(|(font, dictionary)| (font, encode(dictionary)))
.collect(),