Import named PDF pages and images in the XeLaTeX device

This commit is contained in:
gloamxun committed 2026-11-28 20:13:51 +08:00
1 parent 5ad5c40002
commit d875b69280
10 files changed
+797 -292

No files matched your search

@@ -646,20 +646,6 @@ impl Executor {
None
} else if xdv && self.xdv_setup_special(&special)? {
None
} else if xdv && let Some(image) = crate::pdf_device::xdv_image::ImageSpecial::parse(
&special.bytes, device.magnification,
).map_err(|error| self.error(error, special.span))?
{
if let Some(image) = self.ship_xdv_raster_special(image, special.span, files)? {
shipout.pdf_special_images.insert(
shipout.pdf_graphics_steps.len(),
(image, origin.unwrap_or(TokenOrigin {
span: special.span,
invocation: None,
})),
);
}
None
} else {
self.render_special(&special, pdf.driver, files)?
}
@@ -860,15 +846,24 @@ impl Executor {
}
let delta = [device.horizontal_origin - horizontal_origin, device.vertical_origin - vertical_origin];
for (index, graphics_step, [x, y], origin) in xdv_navigation {
if let Some(operation) = self.ship_xdv_navigation(
&shipout.specials[index],
crate::pdf_device::xdv_object::Position {
page: self.shipped_pages + 1,
coordinates: [x + delta[0], y + delta[1]],
height: device.page_height,
magnification,
},
graphics_step, &mut shipout.pdf_links, origin, files,
let special = &shipout.specials[index];
let position = crate::pdf_device::xdv_object::Position {
page: self.shipped_pages + 1,
coordinates: [x + delta[0], y + delta[1]],
height: device.page_height,
magnification,
};
if let Some((b"image", operands)) = super::specials::xdv_navigation_operand(&special.bytes) {
let source = origin.unwrap_or(TokenOrigin { span: special.span, invocation: None });
let (graphics, raster) = self.ship_xdv_image_special(operands, position, special.span, source, files)?;
if let Some(graphics) = graphics {
shipout.pdf_graphics_steps[graphics_step] = Some(graphics);
}
if let Some(raster) = raster {
shipout.pdf_special_images.insert(graphics_step, (raster, source));
}
} else if let Some(operation) = self.ship_xdv_navigation(
special, position, graphics_step, &mut shipout.pdf_links, origin, files,
)? {
shipout.pdf_graphics_steps[graphics_step] = Some(operation);
}
@@ -491,36 +491,73 @@ impl Executor {
Ok(())
}
pub(super) fn ship_xdv_raster_special(
pub(super) fn ship_xdv_image_special(
&mut self,
special: crate::pdf_device::xdv_image::ImageSpecial,
operands: &[u8],
position: crate::pdf_device::xdv_object::Position,
span: Span,
source: TokenOrigin,
files: &mut impl SourceProvider,
) -> Result<Option<Arc<PdfImageUse>>, Error> {
let from = self.source_name(span);
self.reads.insert(Dependency::FileLookup {
name: special.file.clone(),
from: from.clone(),
});
let resource = files
.resource(ResourceKind::PdfImage, &special.file, &from)
.map_err(|message| self.error(message, span))?;
let resource = self.decode_xdv_raster(resource, span)?;
let image = special.place(self.pdf_images.len() + 1, resource)
) -> Result<(Option<crate::pdf_device::PdfGraphics>, Option<Arc<PdfImageUse>>), Error> {
use crate::pdf_device::xdv_image::{ImageSpecial, ImportGeometry};
let (special, warnings) = ImageSpecial::parse(operands, position)
.map_err(|error| self.error(error, span))?;
let image = Arc::new(image);
let saved = self.state.is_initex().then(|| {
FormatPdfImage::capture(&image, &[], FormatImageKind::XdvShippedSpecial)
});
self.pdf_images.push(RegisteredImage {
image: image.clone(),
attributes: None,
saved,
pending_xdv: None,
});
let hidden = special.hidden;
self.emit_pdf_image_object(image.clone(), special.attributes, None, None);
Ok((!hidden).then_some(image))
for warning in warnings {
files.observe_diagnostic(WriteDestination::TerminalAndLog, &format!("xdvipdfmx: warning: {warning}\n"))
.map_err(|error| self.error(error, span))?;
}
let from = self.source_name(span);
self.reads.insert(Dependency::FileLookup { name: special.file.clone(), from: from.clone() });
let resource = files.resource(ResourceKind::PdfImage, &special.file, &from)
.map_err(|message| self.error(message, span))?;
self.check_cancellation()?;
let is_pdf = resource.data.starts_with(b"%PDF-")
|| resource.version.path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("pdf"));
let named = special.name.is_some();
if is_pdf || named {
self.reads.insert(Dependency::PdfCatalogState);
}
let existing = self.state.xdv_navigation.as_ref()
.filter(|_| is_pdf || named)
.and_then(|navigation| navigation.reused_image(&special, &resource.version));
let version = resource.version.clone();
let (id, geometry) = if let Some(existing) = existing {
existing
} else {
let id = self.pdf_images.len() + 1;
let (image, attributes, geometry) = if is_pdf {
let (image, source_box) = PdfImage::read_xdv_special(resource, &special.page, special.page_box)
.map_err(|error| self.error(error, span))?;
(PdfImage::from_xdv_special(id, Arc::new(image)), Vec::new(), special.page_geometry(source_box))
} else {
if !matches!(special.page, PageSelection::Number(0 | 1)) {
return Err(self.error("invalid XDV raster image page selection", span));
}
let resource = self.decode_xdv_raster(resource, span)?;
let (pixels, _) = resource.raster_frame().ok_or_else(|| self.error("XDV image is not raster", span))?;
let geometry = ImportGeometry::Raster { extent: resource.extent().map(f64::to_bits), pixels };
let image = special.place_raster(id, resource).map_err(|error| self.error(error, span))?;
let attributes = special.raster_attributes().map_err(|error| self.error(error, span))?;
(image, attributes, geometry)
};
let image = Arc::new(image);
let saved = self.state.is_initex().then(|| {
FormatPdfImage::capture(&image, &[], FormatImageKind::XdvShippedSpecial)
});
self.pdf_images.push(RegisteredImage {
image: image.clone(), attributes: None, saved, pending_xdv: None,
});
self.emit_pdf_image_object(image.clone(), attributes, None, None);
if !is_pdf && !named {
return Ok((None, (!special.hidden).then_some(image)));
}
(id, geometry)
};
self.check_cancellation()?;
let navigation = Arc::make_mut(self.state.xdv_navigation.get_or_insert_with(Default::default));
let graphics = navigation.import_image(special, version, id, geometry, source, (operands.len(), self.limits.tokens))
.map_err(|error| self.error(error, span))?;
Ok((graphics, None))
}
// A PDF image object is emitted once, when used at shipout or immediately.
@@ -369,6 +369,7 @@ pub(super) fn xdv_navigation_operand(data: &[u8]) -> Option<(&'static [u8], &[u8
(b"bxobj", b"bxobj"), (b"bform", b"bxobj"), (b"beginxobj", b"bxobj"),
(b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"),
(b"uxobj", b"uxobj"), (b"usexobj", b"uxobj"),
(b"image", b"image"), (b"img", b"image"), (b"epdf", b"image"),
] {
if let Some(operands) = xdv_operand(body, name) {
return Some((kind, operands));
+13 -7
View File
@@ -2971,9 +2971,14 @@ fn write_pdf(
);
(image.id, object)
}).collect();
let mut xdv_xobjects = BTreeMap::new();
for form in forms.iter().filter(|form| form.xdv.is_some()) {
objects.push(Vec::new());
device_objects.insert(form.form.number, objects.len() as u32);
xdv_xobjects.insert(form.form.number, objects.len() as u32);
}
let xdv = unicode.and_then(|options| options.xdv_navigation);
if let Some(xdv) = xdv {
xdv.bind_image_objects(&mut xdv_xobjects, &form_ids)?;
}
let append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> {
let images = list
@@ -2988,11 +2993,12 @@ fn write_pdf(
xobjects.push_str(&format!(" /PI{id} {} 0 R", form_ids[&id]));
}
let placements: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
DisplayItem::PdfForm { form, .. } => Some(form.number),
DisplayItem::PdfForm { form, .. } => Some((form.number, form.xdv.is_some())),
_ => None,
}).collect();
for number in placements {
let id = device_objects.get(&number).ok_or("missing native PDF Form canvas")?;
for (number, xdv) in placements {
let registry = if xdv { &xdv_xobjects } else { &device_objects };
let id = registry.get(&number).ok_or("missing native PDF Form canvas")?;
xobjects.push_str(&format!(" /Fm{number} {id} 0 R"));
}
Ok(())
@@ -3571,7 +3577,6 @@ fn write_pdf(
let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects);
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
}
let xdv = unicode.and_then(|options| options.xdv_navigation);
let keep_xdv_destinations = unicode.is_some_and(|options| options.xdv_keep_destinations);
let mut xdv_names = BTreeMap::new();
if !keep_xdv_destinations {
@@ -3617,7 +3622,7 @@ fn write_pdf(
destination.collect_references(&mut pending);
}
}
let named_objects = xdv_objects.reserve_objects(pending, &mut objects, &device_objects)?;
let named_objects = xdv_objects.reserve_objects(pending, &mut objects, &xdv_xobjects)?;
let references = crate::pdf_device::xdv_object::References {
pages: &navigation.pages,
named: &named_objects,
@@ -3625,8 +3630,9 @@ fn write_pdf(
let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?;
if let Some(xdv) = xdv {
xdv.write_image_attributes(&form_ids, &references, &mut objects)?;
for (form, resources, content) in xdv_forms {
let id = device_objects[&form.form.number] as usize;
let id = xdv_xobjects[&form.form.number] as usize;
objects[id - 1] = xdv.write_form(form, resources.as_bytes(), &content, &references, &mut objects, diagnostics)?;
}
xdv.write_page_dictionaries(pages, &references, &mut objects)?;
@@ -52,6 +52,8 @@ pub enum PdfGraphics {
number: u32,
options: super::xdv_navigation::FormOptions,
source: crate::execution::TokenOrigin,
#[serde(default)]
imported_available: bool,
},
}
+281 -146
View File
@@ -1,174 +1,231 @@
//! The xdvipdfmx raster image device special.
use super::Affine;
use crate::pdf_image::{PdfImage, PdfImageUse, real};
use lopdf::{Object, content::Content};
use std::{iter::Peekable, str::SplitAsciiWhitespace, sync::Arc};
//! Image selection and placement from the xdvipdfmx device specials.
use super::{
Affine,
xdv_navigation::FormOptions,
xdv_object::{
Dictionary, Position, Value, dictionary, identifier, parse_object_prefix, trim_pdf,
},
};
use crate::pdf_image::{PageBox, PageSelection, PdfImage, PdfImageUse, PdfPageGeometry, real};
use std::{iter::Peekable, sync::Arc};
pub(crate) struct ImageSpecial {
pub file: String,
pub attributes: Vec<u8>,
pub name: Option<Vec<u8>>,
pub(super) attributes: Dictionary,
pub hidden: bool,
bbox: Option<[f64; 4]>,
dimensions: [Option<f64>; 3],
transform: Affine,
clip: bool,
pub page: PageSelection,
pub page_box: PageBox,
pub placement: FormOptions,
}
impl ImageSpecial {
pub(crate) fn parse(data: &[u8], magnification: i32) -> Result<Option<Self>, String> {
let Some(body) = data.trim_ascii_start().strip_prefix(b"pdf:") else {
return Ok(None);
pub(crate) fn parse(input: &[u8], position: Position) -> Result<(Self, Vec<String>), String> {
let input = trim_pdf(input);
let (name, input) = if input.starts_with(b"@") {
let (name, rest) = identifier(input)?;
(Some(name.to_vec()), rest)
} else {
(None, input)
};
let body = body.trim_ascii_start();
let name_end = body
let mut quoted = false;
let mut escaped = false;
let file_pos = input
.iter()
.position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'(' | b'<'))
.unwrap_or(body.len());
if !matches!(&body[..name_end], b"image" | b"img") {
return Ok(None);
}
let body = &body[name_end..];
let file_pos = body
.iter()
.position(|byte| matches!(byte, b'(' | b'<'))
.position(|&byte| {
if escaped {
escaped = false;
} else if quoted && byte == b'\\' {
escaped = true;
} else if byte == b'"' {
quoted = !quoted;
} else if !quoted && matches!(byte, b'(' | b'<') {
return true;
}
false
})
.ok_or("missing XDV image filename string")?;
let parameters =
std::str::from_utf8(&body[..file_pos]).map_err(|error| error.to_string())?;
let mut words = parameters.split_ascii_whitespace().peekable();
let mut bbox = None;
let mut dimensions = [None; 3];
let mut clip = true;
std::str::from_utf8(&input[..file_pos]).map_err(|_| "invalid XDV image options")?;
let mut rest = parameters;
let mut words = std::iter::from_fn(|| {
rest = rest.trim_ascii_start();
if rest.is_empty() {
return None;
}
let end = if let Some(quoted) = rest.strip_prefix('"') {
let mut escaped = false;
quoted
.bytes()
.position(|byte| {
if escaped {
escaped = false;
} else if byte == b'\\' {
escaped = true;
} else if byte == b'"' {
return true;
}
false
})
.map_or(rest.len(), |index| index + 2)
} else {
rest.bytes()
.position(|byte| byte.is_ascii_whitespace())
.unwrap_or(rest.len())
};
let (word, tail) = rest.split_at(end);
rest = tail;
Some(word)
})
.peekable();
let mut page = 1;
let mut destination = None;
let mut page_box = PageBox::Crop;
let mut hidden = false;
let mut scales = [None; 2];
let mut overall_scale = None;
let mut rotation = 0.0;
let mut matrix = None;
let mut placement = FormOptions::default();
while let Some(parameter) = words.next() {
match parameter {
"bbox" => {
bbox = Some([
number(words.next())?,
number(words.next())?,
number(words.next())?,
number(words.next())?,
]);
}
"width" => dimensions[0] = Some(length(&mut words, magnification)?),
"height" => dimensions[1] = Some(length(&mut words, magnification)?),
"depth" => dimensions[2] = Some(length(&mut words, magnification)?),
"scale" => overall_scale = Some(number(words.next())?),
"xscale" => scales[0] = Some(number(words.next())?),
"yscale" => scales[1] = Some(number(words.next())?),
"rotate" => rotation = number(words.next())?,
"matrix" => {
matrix = Some(Affine([
number(words.next())?,
number(words.next())?,
number(words.next())?,
number(words.next())?,
number(words.next())?,
number(words.next())?,
]));
}
"clip" => clip = number(words.next())? != 0.0,
"hide" => hidden = true,
"page" if matches!(number(words.next())?, 0.0 | 1.0) => {}
_ => return Err(format!("unsupported XDV raster image option {parameter}")),
}
}
if overall_scale.is_some() && scales.iter().any(Option::is_some) {
return Err("XDV image scale conflicts with an axis scale".into());
}
if dimensions[0].is_some() && scales[0].is_some() {
scales[0] = None;
} else if (dimensions[1].is_some() || dimensions[2].is_some()) && scales[1].is_some() {
scales[1] = None;
}
let [sx, sy] = scales.map(|value| value.or(overall_scale).unwrap_or(1.0));
let (sin, cos) = rotation.to_radians().sin_cos();
let transform =
matrix.unwrap_or(Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0]));
// The suffix shares the PDF string and dictionary grammar. Decode
// the objects with the same parser used for native page resources.
let mut pdf_objects = body[file_pos..].to_vec();
pdf_objects.extend_from_slice(b"\nq");
let parsed = Content::decode(&pdf_objects).map_err(|error| error.to_string())?;
let [operation] = parsed.operations.as_slice() else {
return Err("invalid PDF objects in XDV image special".into());
};
let (file, dictionary) = match operation.operands.as_slice() {
[Object::String(file, _)] if operation.operator == "q" => (file, None),
[Object::String(file, _), Object::Dictionary(dict)] if operation.operator == "q" => {
(file, Some(dict))
}
_ => {
return Err("expected filename and optional XDV image attribute dictionary".into());
}
};
let file = String::from_utf8(file.clone()).map_err(|error| error.to_string())?;
let mut attributes = Vec::new();
if let Some(dictionary) = dictionary {
for (key, value) in dictionary.iter() {
match (key.as_slice(), value) {
(b"Decode", Object::Array(values)) => {
if values.is_empty() || values.len() % 2 != 0 {
return Err("XDV image Decode array requires pairs".into());
}
attributes.extend_from_slice(b"/Decode [");
for value in values {
let number = match value {
Object::Integer(value) => *value as f64,
Object::Real(value) if value.is_finite() => *value,
_ => {
return Err(
"XDV image Decode array requires finite numbers".into()
);
}
};
attributes.extend_from_slice(real(number).as_bytes());
attributes.push(b' ');
}
attributes.extend_from_slice(b"] ");
"page" => {
let requested = number(words.next())?.trunc();
if !(f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(&requested) {
return Err("XDV image page number out of range".into());
}
(b"Interpolate", Object::Boolean(value)) => {
attributes.extend_from_slice(if *value {
b"/Interpolate true "
page = requested as i32;
}
"pagebox" => {
page_box = match words.next().map(str::to_ascii_lowercase).as_deref() {
Some("mediabox") => PageBox::Media,
Some("cropbox") => PageBox::Crop,
Some("bleedbox") => PageBox::Bleed,
Some("trimbox") => PageBox::Trim,
Some("artbox") => PageBox::Art,
_ => return Err("invalid XDV image page box".into()),
};
}
"named" => {
let word = words
.next()
.and_then(|word| word.strip_prefix('"'))
.and_then(|word| word.strip_suffix('"'))
.ok_or("expected quoted XDV image page destination")?;
let mut bytes = word.bytes();
let mut name = Vec::with_capacity(word.len());
while let Some(byte) = bytes.next() {
name.push(if byte == b'\\' {
bytes
.next()
.ok_or("invalid XDV image page destination escape")?
} else {
b"/Interpolate false "
byte
});
}
_ => {
return Err(format!(
"unsupported XDV image attribute {}",
String::from_utf8_lossy(key)
));
destination = Some(name);
}
word if placement.read_option(word, &mut words, position.magnification)? => {}
word => return Err(format!("unsupported XDV image option {word}")),
}
}
let warnings = placement.finish()?;
let (Value::String(file), rest) = parse_object_prefix(&input[file_pos..], position)? else {
return Err("expected XDV image filename string".into());
};
let attributes = if rest.is_empty() {
Dictionary::new()
} else {
dictionary(rest, position)?
};
let file = String::from_utf8(file).map_err(|error| error.to_string())?;
Ok((
Self {
file,
name,
attributes,
hidden,
page: destination.map_or(PageSelection::Number(page), PageSelection::Named),
page_box,
placement,
},
warnings,
))
}
pub(crate) fn page_geometry(&self, geometry: PdfPageGeometry) -> ImportGeometry {
ImportGeometry::page(geometry, &self.attributes)
}
pub(crate) fn raster_attributes(&self) -> Result<Vec<u8>, String> {
let mut attributes = Vec::new();
for (key, value) in &self.attributes {
match (key.as_slice(), value) {
(b"Decode", Value::Array(values))
if !values.is_empty() && values.len() % 2 == 0 =>
{
attributes.extend_from_slice(b"/Decode [");
for value in values {
let number = match value {
Value::Integer(value) => *value as f64,
Value::Real(value) => f64::from_bits(*value),
_ => {
return Err("XDV image Decode array requires finite numbers".into());
}
};
attributes.extend_from_slice(real(number).as_bytes());
attributes.push(b' ');
}
attributes.extend_from_slice(b"] ");
}
(b"Interpolate", Value::Boolean(value)) => {
attributes.extend_from_slice(if *value {
b"/Interpolate true "
} else {
b"/Interpolate false "
});
}
_ => {
return Err(format!(
"unsupported XDV raster image attribute {}",
String::from_utf8_lossy(key)
));
}
}
}
Ok(Some(Self {
file,
attributes,
hidden,
bbox,
dimensions,
transform,
clip,
}))
Ok(attributes)
}
pub(crate) fn place(&self, id: usize, image: Arc<PdfImage>) -> Result<PdfImageUse, String> {
let [natural_w, natural_h] = image.extent();
let ([pixels_w, pixels_h], _) = image
pub(crate) fn place_raster(
&self,
id: usize,
image: Arc<PdfImage>,
) -> Result<PdfImageUse, String> {
let (pixels, _) = image
.raster_frame()
.ok_or("XDV special needs a raster image")?;
let [left, bottom, right, top] = self.bbox.unwrap_or([0.0, 0.0, natural_w, natural_h]);
let (matrix, annotation_box) = self.placement.raster_transform(image.extent(), pixels)?;
PdfImageUse::new_xdv_raster_special(
id,
image,
matrix,
annotation_box,
self.placement.clip_enabled(),
)
}
}
impl FormOptions {
pub(crate) fn raster_transform(
self,
[natural_w, natural_h]: [f64; 2],
[pixels_w, pixels_h]: [i64; 2],
) -> Result<(Affine, Option<[f64; 4]>), String> {
let [left, bottom, right, top] = self
.requested_box()
.unwrap_or([0.0, 0.0, natural_w, natural_h]);
let [box_w, box_h] = [right - left, top - bottom];
if box_w <= 0.0 || box_h <= 0.0 {
return Err("XDV image bounding box must have positive dimensions".into());
}
let [requested_w, requested_h, depth] = self.dimensions;
let [requested_w, requested_h, depth] = self.dimensions();
let requested_h = requested_h.or(depth.map(|_| 0.0));
let depth = depth.unwrap_or(0.0);
let [xscale, yscale] = [natural_w / box_w, natural_h / box_h];
@@ -191,26 +248,104 @@ impl ImageSpecial {
-left * width / natural_w,
-bottom * height / natural_h - depth,
]);
let annotation_box = self.bbox.is_some().then_some([
let annotation_box = self.requested_box().is_some().then_some([
left / natural_w,
bottom / natural_h,
box_w / natural_w,
box_h / natural_h,
]);
PdfImageUse::new_xdv_raster_special(
id, image, self.transform.concatenate(sizing), annotation_box, self.clip,
)
Ok((self.affine().concatenate(sizing), annotation_box))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) enum ImportGeometry {
Page { bounds: [u64; 4], fitting: [u64; 4] },
Raster { extent: [u64; 2], pixels: [i64; 2] },
}
impl ImportGeometry {
fn page(geometry: PdfPageGeometry, attributes: &Dictionary) -> Self {
let [left, bottom, right, top] = geometry.bounds;
let rect = |points: [[f64; 2]; 4]| {
let [x, y] = points[0];
points[1..]
.iter()
.fold([x, y, x, y], |[l, b, r, t], &[x, y]| {
[l.min(x), b.min(y), r.max(x), t.max(y)]
})
.map(f64::to_bits)
};
let normal = [[left, bottom], [right, bottom], [right, top], [left, top]]
.map(|[x, y]| geometry.matrix.point(x, y));
let mut sizing = normal;
// The reference driver's stored fitting rectangle also samples the
// unshifted lower edge and the transformed lower-right x-axis point.
sizing[0][1] = bottom;
sizing[1] = geometry.matrix.point(right, 0.0);
let [l, b, r, t] = numeric_attribute(attributes, b"BBox").unwrap_or(geometry.bounds);
let matrix = numeric_attribute(attributes, b"Matrix").map_or(geometry.matrix, Affine);
let painted = [[l, b], [r, b], [r, t], [l, t]].map(|[x, y]| matrix.point(x, y));
Self::Page {
bounds: rect(painted),
fitting: rect(sizing),
}
}
pub(crate) fn place(
&self,
number: u32,
options: FormOptions,
available: bool,
) -> Result<crate::pdf_device::forms::FormUse, String> {
match *self {
Self::Page { bounds, fitting } => options.place_xobject(
number,
bounds.map(f64::from_bits),
available.then(|| fitting.map(f64::from_bits)),
),
Self::Raster { extent, pixels } => {
let bounds = [0.0, 0.0, 1.0, 1.0];
if !available {
return options.place_xobject(number, bounds, None);
}
let (matrix, clip) =
options.raster_transform(extent.map(f64::from_bits), pixels)?;
let clip = clip
.filter(|_| options.clip_enabled())
.map(|[x, y, width, height]| [x, y, x + width, y + height]);
FormOptions::placed(number, bounds, matrix, clip)
}
}
}
}
fn numeric_attribute<const N: usize>(attributes: &Dictionary, name: &[u8]) -> Option<[f64; N]> {
let Value::Array(values) = attributes.get(name)? else {
return None;
};
if values.len() != N {
return None;
}
let mut numbers = [0.0; N];
for (number, value) in numbers.iter_mut().zip(values) {
*number = match value {
Value::Real(value) => f64::from_bits(*value),
Value::Integer(value) => *value as f64,
_ => return None,
};
}
Some(numbers)
}
pub(super) fn number(word: Option<&str>) -> Result<f64, &'static str> {
word.and_then(|word| word.parse::<f64>().ok())
.filter(|value| value.is_finite())
.ok_or("invalid XDV image number")
}
pub(super) fn length(
words: &mut Peekable<SplitAsciiWhitespace<'_>>,
pub(super) fn length<'a>(
words: &mut Peekable<impl Iterator<Item = &'a str>>,
magnification: i32,
) -> Result<f64, &'static str> {
let word = words.next().ok_or("missing XDV image length")?;
@@ -8,11 +8,13 @@ use crate::{
pdf_device::{
Affine, PdfGraphics, PdfLiteralMode,
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
xdv_image::{length, number},
xdv_image::{ImageSpecial, ImportGeometry, length, number},
xdv_page_origin,
},
pdf_image::{PageBox, PageSelection},
provenance::PaintSource,
render::{DisplayItem, DisplayList},
resources::ResourceVersion,
};
use super::super::xdv_object::{identifier, trim_pdf};
@@ -42,58 +44,71 @@ impl FormOptions {
.peekable();
let mut options = Self::default();
while let Some(word) = words.next() {
match word {
"bbox" => {
let mut bounds = [0; 4];
for entry in &mut bounds {
*entry = number(words.next())?.to_bits();
}
options.bbox = Some(bounds);
}
"width" | "height" | "depth" => {
let index = match word {
"width" => 0,
"height" => 1,
_ => 2,
};
options.size[index] = Some(length(&mut words, magnification)?.to_bits());
}
"scale" => options.scale = Some(number(words.next())?.to_bits()),
"xscale" | "yscale" => {
options.axis_scale[usize::from(word == "yscale")] =
Some(number(words.next())?.to_bits());
}
"rotate" => options.rotation = Some(number(words.next())?.to_bits()),
"matrix" => {
let mut matrix = [0; 6];
for entry in &mut matrix {
*entry = number(words.next())?.to_bits();
}
options.matrix = Some(matrix);
}
"clip" => options.clip = Some(number(words.next())? != 0.0),
"hide" => {}
_ => return Err(format!("unsupported XDV form option {word}")),
if word != "hide" && !options.read_option(word, &mut words, magnification)? {
return Err(format!("unsupported XDV form option {word}"));
}
}
if let Some(bounds) = options.bbox {
let warnings = options.finish()?;
Ok((options, warnings))
}
pub(crate) fn read_option<'a>(
&mut self,
word: &str,
words: &mut std::iter::Peekable<impl Iterator<Item = &'a str>>,
magnification: i32,
) -> Result<bool, String> {
match word {
"bbox" => {
let mut bounds = [0; 4];
for entry in &mut bounds {
*entry = number(words.next())?.to_bits();
}
self.bbox = Some(bounds);
}
"width" | "height" | "depth" => {
let index = match word {
"width" => 0,
"height" => 1,
_ => 2,
};
self.size[index] = Some(length(words, magnification)?.to_bits());
}
"scale" => self.scale = Some(number(words.next())?.to_bits()),
"xscale" | "yscale" => {
self.axis_scale[usize::from(word == "yscale")] =
Some(number(words.next())?.to_bits());
}
"rotate" => self.rotation = Some(number(words.next())?.to_bits()),
"matrix" => {
let mut matrix = [0; 6];
for entry in &mut matrix {
*entry = number(words.next())?.to_bits();
}
self.matrix = Some(matrix);
}
"clip" => self.clip = Some(number(words.next())? != 0.0),
_ => return Ok(false),
}
Ok(true)
}
pub(crate) fn finish(&mut self) -> Result<Vec<String>, String> {
if let Some(bounds) = self.bbox {
checked_box(bounds.map(f64::from_bits))?;
}
let [width, height, depth] = options.size;
let [sx, sy] = options.axis_scale;
let [width, height, depth] = self.size;
let [sx, sy] = self.axis_scale;
let warning = if width.is_some() && sx.is_some() {
options.axis_scale[0] = Some(1.0f64.to_bits());
self.axis_scale[0] = Some(1.0f64.to_bits());
Some("Can't supply both width and xscale. Ignore xscale.")
} else if (height.is_some() || depth.is_some()) && sy.is_some() {
options.axis_scale[1] = Some(1.0f64.to_bits());
self.axis_scale[1] = Some(1.0f64.to_bits());
Some("Can't supply both height/depth and yscale. Ignore yscale.")
} else if options.scale.is_some() && (sx.is_some() || sy.is_some()) {
} else if self.scale.is_some() && (sx.is_some() || sy.is_some()) {
return Err("XDV form scale conflicts with an axis scale".into());
} else if options.matrix.is_some()
&& (sx.is_some()
|| sy.is_some()
|| options.scale.is_some()
|| options.rotation.is_some())
} else if self.matrix.is_some()
&& (sx.is_some() || sy.is_some() || self.scale.is_some() || self.rotation.is_some())
{
Some(
"Can't supply transform matrix along with scales or rotate. Ignore scales and rotate.",
@@ -101,7 +116,7 @@ impl FormOptions {
} else {
None
};
Ok((options, warning.into_iter().map(String::from).collect()))
Ok(warning.into_iter().map(String::from).collect())
}
fn capture_bounds(self) -> Result<[u64; 4], String> {
@@ -124,34 +139,35 @@ impl FormOptions {
capture_y: Option<f64>,
) -> Result<FormUse, String> {
let captured = captured.map(f64::from_bits);
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
let transform = if let Some(matrix) = self.matrix {
Affine(matrix.map(f64::from_bits))
} else {
let [sx, sy] = self
.axis_scale
.map(|value| value.or(self.scale).map_or(1.0, f64::from_bits));
let (sin, cos) = self
.rotation
.map_or(0.0, f64::from_bits)
.to_radians()
.sin_cos();
Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0])
};
// A reserved forward XObject uses the external matrix and explicit
// clip at its use site. The driver has no Form dimensions there yet.
let transform = if let Some(capture_y) = capture_y {
let fitting = capture_y.map(|capture_y| {
let [left, bottom, right, top] = captured;
// xdvipdfmx 20260113 fits against a separate stored extent.
// Its vertical samples are the unshifted lower edge and the
// capture-origin-adjusted zero and upper edge (pdf_ximage_set_form).
// The reference Form extent uses the unshifted lower edge and
// the capture-origin-adjusted zero and upper edge.
let y = [-capture_y, top - capture_y];
let extent = y[0].max(y[1]).max(bottom) - y[0].min(y[1]).min(bottom);
[
left,
y[0].min(y[1]).min(bottom),
right,
y[0].max(y[1]).max(bottom),
]
});
self.place_xobject(number, captured, fitting)
}
pub(crate) fn place_xobject(
self,
number: u32,
captured: [f64; 4],
fitting: Option<[f64; 4]>,
) -> Result<FormUse, String> {
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
let transform = self.affine();
// A reserved forward reference has no natural dimensions yet.
let transform = if let Some([left, bottom, right, top]) = fitting {
let (natural, offset) = if let Some([x0, y0, x1, y1]) = user_bbox {
([x1 - x0, y1 - y0], [-x0, -y0])
} else {
([right - left, extent], [0.0, 0.0])
([right - left, top - bottom], [0.0, 0.0])
};
let [natural_x, natural_y] = natural.map(|n| if n == 0.0 { 1.0 } else { n });
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
@@ -174,12 +190,20 @@ impl FormOptions {
} else {
transform
};
let clip = user_bbox.filter(|_| self.clip_enabled());
Self::placed(number, captured, transform, clip)
}
pub(crate) fn placed(
number: u32,
captured: [f64; 4],
transform: Affine,
clip: Option<[f64; 4]>,
) -> Result<FormUse, String> {
let matrix = transform.0;
if !matrix.iter().all(|value| value.is_finite()) {
return Err("XDV form placement transform out of range".into());
}
let clip = user_bbox.filter(|_| self.clip.unwrap_or(true));
let [left, bottom, right, top] = if let Some([x0, y0, x1, y1]) = clip {
let [left, bottom, right, top] = captured;
let left = left.max(x0.min(x1));
@@ -214,6 +238,33 @@ impl FormOptions {
}),
})
}
pub(crate) fn affine(self) -> Affine {
if let Some(matrix) = self.matrix {
return Affine(matrix.map(f64::from_bits));
}
let [sx, sy] = self
.axis_scale
.map(|value| value.or(self.scale).map_or(1.0, f64::from_bits));
let (sin, cos) = self
.rotation
.map_or(0.0, f64::from_bits)
.to_radians()
.sin_cos();
Affine([cos * sx, sin * sx, -sin * sy, cos * sy, 0.0, 0.0])
}
pub(crate) fn requested_box(self) -> Option<[f64; 4]> {
self.bbox.map(|values| values.map(f64::from_bits))
}
pub(crate) fn dimensions(self) -> [Option<f64>; 3] {
self.size.map(|value| value.map(f64::from_bits))
}
pub(crate) fn clip_enabled(self) -> bool {
self.clip.unwrap_or(true)
}
}
fn to_sp(value: f64) -> Result<i64, String> {
@@ -234,6 +285,12 @@ pub(super) struct Forms {
names: BTreeMap<Vec<u8>, u32>,
definitions: BTreeMap<u32, Definition>,
active: Vec<Active>,
#[serde(default)]
next_number: u32,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
imports: BTreeMap<u32, usize>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
images: BTreeMap<usize, ImportedImage>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -250,21 +307,34 @@ struct Definition {
resources: Dictionary,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct ImportedImage {
geometry: ImportGeometry,
version: ResourceVersion,
page: PageSelection,
page_box: PageBox,
attributes: Dictionary,
}
impl Forms {
pub(super) fn is_empty(&self) -> bool {
self.names.is_empty()
self.names.is_empty() && self.images.is_empty()
}
pub(super) fn number(&self, name: &[u8]) -> Option<u32> {
self.names.get(name).copied()
}
fn register(&mut self, name: &[u8]) -> Result<u32, String> {
if let Some(number) = self.number(name) {
fn register(&mut self, name: Option<&[u8]>) -> Result<u32, String> {
if let Some(number) = name.and_then(|name| self.number(name)) {
return Ok(number);
}
let number = u32::try_from(self.names.len() + 1).map_err(|_| "XDV form limit exceeded")?;
self.names.insert(name.to_vec(), number);
let previous = self.next_number.max(self.names.len() as u32);
let number = previous.checked_add(1).ok_or("XDV form limit exceeded")?;
self.next_number = number;
if let Some(name) = name {
self.names.insert(name.to_vec(), number);
}
Ok(number)
}
@@ -273,6 +343,11 @@ impl Forms {
.definitions
.values()
.flat_map(|entry| entry.attributes.values().chain(entry.resources.values()))
.chain(
self.images
.values()
.flat_map(|image| image.attributes.values()),
)
{
value.collect_references(pending);
}
@@ -280,6 +355,106 @@ impl Forms {
}
impl Navigation {
pub(crate) fn reused_image(
&self,
special: &ImageSpecial,
version: &ResourceVersion,
) -> Option<(usize, ImportGeometry)> {
self.forms.images.iter().find_map(|(&id, image)| {
(image.version == *version
&& image.page == special.page
&& image.page_box == special.page_box
&& image.attributes == special.attributes)
.then(|| (id, image.geometry.clone()))
})
}
pub(crate) fn import_image(
&mut self,
special: ImageSpecial,
version: ResourceVersion,
id: usize,
geometry: ImportGeometry,
source: TokenOrigin,
payload: (usize, usize),
) -> Result<Option<PdfGraphics>, String> {
self.add_payload(payload.0, payload.1)?;
let name = special.name.as_deref();
let number = self.forms.register(name)?;
if self.forms.definitions.contains_key(&number)
|| self.forms.active.iter().any(|form| form.number == number)
|| name.is_some_and(|name| self.objects.contains_key(name))
|| self
.forms
.imports
.get(&number)
.is_some_and(|&other| other != id)
{
return Err("duplicate XDV XObject definition".into());
}
self.forms.images.entry(id).or_insert(ImportedImage {
geometry,
version,
page: special.page,
page_box: special.page_box,
attributes: special.attributes,
});
self.forms.imports.insert(number, id);
Ok((!special.hidden).then_some(PdfGraphics::XdvFormUse {
number,
options: special.placement,
source,
imported_available: true,
}))
}
pub(crate) fn bind_image_objects(
&self,
xobjects: &mut BTreeMap<u32, u32>,
objects: &BTreeMap<usize, usize>,
) -> Result<(), String> {
for (&number, id) in &self.forms.imports {
let object = *objects.get(id).ok_or("missing XDV image declaration")?;
xobjects.insert(
number,
u32::try_from(object).map_err(|_| "PDF object ID out of range")?,
);
}
Ok(())
}
pub(crate) fn write_image_attributes(
&self,
imported_objects: &BTreeMap<usize, usize>,
references: &References<'_>,
objects: &mut [Vec<u8>],
) -> Result<(), String> {
for (id, image) in &self.forms.images {
if image.attributes.is_empty()
|| matches!(image.geometry, ImportGeometry::Raster { .. })
{
continue;
}
let attributes = output_dictionary(&image.attributes, references)?;
let object = &mut objects[imported_objects[id] - 1];
let end = object
.windows(b"\nstream\n".len())
.position(|bytes| bytes == b"\nstream\n")
.ok_or("missing native XDV image stream")?;
let Object::Dictionary(mut fields) = parse_value(&object[..end])? else {
return Err("invalid native XDV image dictionary".into());
};
for (name, value) in &attributes {
if name.as_slice() != b"Length" {
fields.set(name.clone(), value.clone());
}
}
let encoded = encode_device_value(Object::Dictionary(fields))?;
object.splice(..end, encoded);
}
Ok(())
}
pub(crate) fn form_special(
&mut self,
kind: &[u8],
@@ -315,9 +490,10 @@ impl Navigation {
}
let (name, rest) = identifier(input)?;
let (options, warnings) = FormOptions::parse(rest, position.magnification)?;
let number = self.forms.register(name)?;
let number = self.forms.register(Some(name))?;
let command = if kind == b"bxobj" {
if self.forms.definitions.contains_key(&number)
|| self.forms.imports.contains_key(&number)
|| self.forms.active.iter().any(|form| form.number == number)
|| self.objects.contains_key(name)
{
@@ -339,6 +515,7 @@ impl Navigation {
number,
options,
source,
imported_available: self.forms.imports.contains_key(&number),
}
};
Ok((command, warnings))
@@ -443,19 +620,28 @@ impl Navigation {
number,
options,
source,
imported_available,
},
} => {
let bounds = self
.forms
.definitions
.get(&number)
.ok_or("referenced XDV form is undefined")?
.bounds;
let form = options.place(
number,
bounds,
capture_positions.get(&number).copied(),
)?;
let form = if let Some(import) = self.forms.imports.get(&number) {
self.forms.images[import].geometry.place(
number,
options,
imported_available,
)?
} else {
let bounds = self
.forms
.definitions
.get(&number)
.ok_or("referenced XDV form is undefined")?
.bounds;
options.place(
number,
bounds,
capture_positions.get(&number).copied(),
)?
};
(
DisplayItem::PdfForm { x, y, form },
Some(PaintSource::token(source)),
+45 -3
View File
@@ -21,12 +21,13 @@ use std::{
sync::Arc,
};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(crate) enum PageSelection {
Number(i32),
Named(Vec<u8>),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[repr(i32)]
pub(crate) enum PageBox {
Media = 1,
@@ -43,6 +44,11 @@ enum PageBoxSelection {
Xdv(PageBox),
}
pub(crate) struct PdfPageGeometry {
pub(crate) bounds: [f64; 4],
pub(crate) matrix: Affine,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfImage {
pub version: ResourceVersion,
@@ -744,6 +750,42 @@ impl PdfImage {
.then(|| page.clamp(1, pages) as u32)
.ok_or_else(|| "required page does not exist".into())
})
.map(|(image, geometry)| {
let [left, bottom, ..] = geometry.bounds;
(image, [left, bottom])
})
}
pub(crate) fn read_xdv_special(
resource: LoadedResource,
selection: &PageSelection,
kind: PageBox,
) -> Result<(Self, PdfPageGeometry), String> {
let doc = Self::open_pdf(&resource)?;
Self::read_page(resource, doc, PageBoxSelection::Xdv(kind), false, |doc, pages| {
match selection {
PageSelection::Number(page) => u32::try_from(if *page == 0 { 1 } else { *page })
.ok()
.filter(|page| pages.contains_key(page))
.ok_or_else(|| format!("invalid XDV PDF image page number: {page}")),
PageSelection::Named(name) => destinations::page(doc, pages, name),
}
})
}
pub(crate) fn from_xdv_special(id: usize, image: Arc<Self>) -> PdfImageUse {
let [width, height] = image.natural;
PdfImageUse {
id,
pdf_object_number: None,
png_group: None,
pdftex_file_name: None,
image,
width,
height,
depth: 0,
xdv: None,
}
}
pub(crate) fn count_pages(resource: &LoadedResource) -> usize {
@@ -769,7 +811,7 @@ impl PdfImage {
box_selection: PageBoxSelection,
remap_type1: bool,
select_page: impl FnOnce(&Document, &BTreeMap<u32, ObjectId>) -> Result<u32, String>,
) -> Result<(Self, [f64; 2]), String> {
) -> Result<(Self, PdfPageGeometry), String> {
let pages = doc.get_pages();
let page = select_page(&doc, &pages)?;
let page_id = pages
@@ -930,7 +972,7 @@ impl PdfImage {
device_cid_cff_fonts: fonts.cid_cff,
pdftex_source,
},
[left, bottom],
PdfPageGeometry { bounds: [left, bottom, right, top], matrix: Affine(matrix) },
))
}
@@ -1120,3 +1120,74 @@ fn xdv_form_placement_respects_definition_order_and_crop() {
let operations = Content::decode(&contents).unwrap().operations;
assert_eq!(&matrices(&operations)[0][..4], &[1.75, 0.0, 0.0, 0.80132]);
}
#[test]
fn xdv_imported_image_matches_forward_catalog_and_page_references() {
use lopdf::{Document, Object, Stream, dictionary};
use sha2::{Digest, Sha256};
use texrra_tex_core::{
pdf::shipout_lists_to_native_pdf_document,
resources::{LoadedResource, ResourceKind, ResourceVersion},
};
struct ImageDevice(LoadedResource);
impl SourceProvider for ImageDevice {
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
TestDevice.read(name, from)
}
fn default_pk_resolution(&mut self) -> Result<i32, String> {
TestDevice.default_pk_resolution()
}
fn resource(&mut self, kind: ResourceKind, name: &str, _: &str) -> Result<LoadedResource, String> {
assert_eq!((kind, name), (ResourceKind::PdfImage, "drawing.pdf"));
Ok(LoadedResource { version: self.0.version.clone(), data: self.0.data.clone() })
}
}
let mut drawing = Document::with_version("1.5");
let pages = drawing.new_object_id();
let stream = drawing.add_object(Stream::new(dictionary! {}, b"1 0 0 rg 0 0 18 20 re f".to_vec()));
let page = drawing.add_object(dictionary! { "Type" => "Page", "Parent" => pages, "Contents" => stream });
drawing.objects.insert(pages, Object::Dictionary(dictionary! {
"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1,
"MediaBox" => vec![0.into(), 0.into(), 18.into(), 20.into()], "Resources" => dictionary! {},
}));
let root = drawing.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages });
drawing.trailer.set("Root", root);
let mut bytes = Vec::new();
drawing.save_to(&mut bytes).unwrap();
let mut device = ImageDevice(LoadedResource {
version: ResourceVersion {
path: "drawing.pdf".into(),
sha256: format!("{:x}", Sha256::digest(&bytes)),
bytes: bytes.len() as u64,
},
data: bytes,
});
let state = State::initex().with_etex().with_input_profile(InputProfile::XeTeX);
let result = Executor::new(state, Limits::default()).with_native_pages().run(
source(r"\catcode123=1 \catcode125=2
\shipout\hbox{\special{pdf:uxobj @Sheet}\special{pdf:put @catalog << /Sheet @Sheet >>}}
\shipout\hbox{\special{pdf:epdf @Sheet pagebox mediabox hide (drawing.pdf) << /Stamp @Tag >>}%
\special{pdf:obj @Tag (proof)}\special{pdf:usexobj @Sheet width 36bp}}
\end"),
&mut device,
).unwrap();
let pages = result.shipout_display_lists().unwrap();
let pdf = shipout_lists_to_native_pdf_document(&pages, result.state.pdf_final_options()).unwrap();
let pdf = Document::load_mem(&pdf.bytes).unwrap();
let reference = pdf.catalog().unwrap().get(b"Sheet").unwrap().as_reference().unwrap();
for page in pdf.get_pages().into_values() {
let page = pdf.get_dictionary(page).unwrap();
let xobjects = page.get(b"Resources").unwrap().as_dict().unwrap()
.get(b"XObject").unwrap().as_dict().unwrap();
assert_eq!(xobjects.len(), 1);
assert_eq!(xobjects.iter().next().unwrap().1.as_reference().unwrap(), reference);
}
let form = pdf.get_object(reference).unwrap().as_stream().unwrap();
let stamp = form.dict.get(b"Stamp").unwrap().as_reference().unwrap();
assert_eq!(pdf.get_object(stamp).unwrap().as_str().unwrap(), b"proof");
assert_eq!(form.dict.get(b"Subtype").unwrap().as_name().unwrap(), b"Form");
}