Honor pdfTeX page box selection and inherited PDF bounds

This commit is contained in:
gloamxun committed 2026-11-26 17:56:57 +08:00
1 parent 58012d9397
commit e10e0cce53
9 files changed
+227 -66

No files matched your search

@@ -0,0 +1,91 @@
//! Page rectangles used by the two PDF inclusion devices.
use super::{PageBox, number, resolved};
use lopdf::{Dictionary, Document, Object};
fn rectangle(
doc: &Document,
value: &Object,
bounds: Option<(f64, f64)>,
) -> Result<[f64; 4], String> {
let coordinates = resolved(doc, value)?
.as_array()
.map_err(|error| error.to_string())?;
let [a, b, c, d] = coordinates.as_slice() else {
return Err("PDF image bounding box must contain four coordinates".into());
};
let coordinate =
|value| number(doc, value).map(|n| bounds.map_or(n, |(min, max)| n.clamp(min, max)));
let (a, b, c, d) = (
coordinate(a)?,
coordinate(b)?,
coordinate(c)?,
coordinate(d)?,
);
Ok([a.min(c), b.min(d), a.max(c), b.max(d)])
}
pub(super) fn pdftex(doc: &Document, chain: &[&Dictionary], spec: i32) -> Result<[f64; 4], String> {
let read =
|dict: &Dictionary, key: &[u8]| rectangle(doc, dict.get(key).ok()?, Some((-1e9, 1e9))).ok();
let inherit = |key: &[u8]| chain.iter().find_map(|dict| read(dict, key));
let media = inherit(b"MediaBox").unwrap_or([0.0, 0.0, 612.0, 792.0]);
let [left, bottom, right, top] = media;
let crop = || inherit(b"CropBox").unwrap_or(media);
let selected = match spec {
0 | 2 => crop(),
1 => return Ok(media),
3..=5 => {
let key: &[u8] = match spec {
3 => b"BleedBox",
4 => b"TrimBox",
_ => b"ArtBox",
};
read(chain[0], key).unwrap_or_else(crop)
}
_ => {
return Err(format!(
"PDF inclusion: unknown value of pagebox spec ({spec})"
));
}
};
Ok([
selected[0].clamp(left, right),
selected[1].clamp(bottom, top),
selected[2].clamp(left, right),
selected[3].clamp(bottom, top),
])
}
pub(super) fn pdftex_rotation(doc: &Document, chain: &[&Dictionary]) -> i64 {
chain
.iter()
.find_map(|dict| resolved(doc, dict.get(b"Rotate").ok()?).ok()?.as_i64().ok())
.unwrap_or(0)
}
pub(super) fn xdv(
doc: &Document,
chain: &[&Dictionary],
kind: PageBox,
) -> Result<[f64; 4], String> {
let requested: &[u8] = match kind {
PageBox::Media => b"MediaBox",
PageBox::Crop => b"CropBox",
PageBox::Bleed => b"BleedBox",
PageBox::Trim => b"TrimBox",
PageBox::Art => b"ArtBox",
};
let keys = [
requested,
b"CropBox",
b"MediaBox",
b"BleedBox",
b"TrimBox",
b"ArtBox",
];
let value = keys
.iter()
.find_map(|key| chain.iter().find_map(|dict| dict.get(key).ok()))
.ok_or("PDF image has no page bounding box")?;
rectangle(doc, value, None)
}