Import named PDF pages and images in the XeLaTeX device
This commit is contained in:
1 parent
5ad5c40002
commit
d875b69280
10 files changed
+797
-292
No files matched your search
@@ -646,20 +646,6 @@ impl Executor {
|
|||||||
None
|
None
|
||||||
} else if xdv && self.xdv_setup_special(&special)? {
|
} else if xdv && self.xdv_setup_special(&special)? {
|
||||||
None
|
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 {
|
} else {
|
||||||
self.render_special(&special, pdf.driver, files)?
|
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];
|
let delta = [device.horizontal_origin - horizontal_origin, device.vertical_origin - vertical_origin];
|
||||||
for (index, graphics_step, [x, y], origin) in xdv_navigation {
|
for (index, graphics_step, [x, y], origin) in xdv_navigation {
|
||||||
if let Some(operation) = self.ship_xdv_navigation(
|
let special = &shipout.specials[index];
|
||||||
&shipout.specials[index],
|
let position = crate::pdf_device::xdv_object::Position {
|
||||||
crate::pdf_device::xdv_object::Position {
|
page: self.shipped_pages + 1,
|
||||||
page: self.shipped_pages + 1,
|
coordinates: [x + delta[0], y + delta[1]],
|
||||||
coordinates: [x + delta[0], y + delta[1]],
|
height: device.page_height,
|
||||||
height: device.page_height,
|
magnification,
|
||||||
magnification,
|
};
|
||||||
},
|
if let Some((b"image", operands)) = super::specials::xdv_navigation_operand(&special.bytes) {
|
||||||
graphics_step, &mut shipout.pdf_links, origin, files,
|
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);
|
shipout.pdf_graphics_steps[graphics_step] = Some(operation);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -491,36 +491,73 @@ impl Executor {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn ship_xdv_raster_special(
|
pub(super) fn ship_xdv_image_special(
|
||||||
&mut self,
|
&mut self,
|
||||||
special: crate::pdf_device::xdv_image::ImageSpecial,
|
operands: &[u8],
|
||||||
|
position: crate::pdf_device::xdv_object::Position,
|
||||||
span: Span,
|
span: Span,
|
||||||
|
source: TokenOrigin,
|
||||||
files: &mut impl SourceProvider,
|
files: &mut impl SourceProvider,
|
||||||
) -> Result<Option<Arc<PdfImageUse>>, Error> {
|
) -> Result<(Option<crate::pdf_device::PdfGraphics>, Option<Arc<PdfImageUse>>), Error> {
|
||||||
let from = self.source_name(span);
|
use crate::pdf_device::xdv_image::{ImageSpecial, ImportGeometry};
|
||||||
self.reads.insert(Dependency::FileLookup {
|
let (special, warnings) = ImageSpecial::parse(operands, position)
|
||||||
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)
|
|
||||||
.map_err(|error| self.error(error, span))?;
|
.map_err(|error| self.error(error, span))?;
|
||||||
let image = Arc::new(image);
|
for warning in warnings {
|
||||||
let saved = self.state.is_initex().then(|| {
|
files.observe_diagnostic(WriteDestination::TerminalAndLog, &format!("xdvipdfmx: warning: {warning}\n"))
|
||||||
FormatPdfImage::capture(&image, &[], FormatImageKind::XdvShippedSpecial)
|
.map_err(|error| self.error(error, span))?;
|
||||||
});
|
}
|
||||||
self.pdf_images.push(RegisteredImage {
|
let from = self.source_name(span);
|
||||||
image: image.clone(),
|
self.reads.insert(Dependency::FileLookup { name: special.file.clone(), from: from.clone() });
|
||||||
attributes: None,
|
let resource = files.resource(ResourceKind::PdfImage, &special.file, &from)
|
||||||
saved,
|
.map_err(|message| self.error(message, span))?;
|
||||||
pending_xdv: None,
|
self.check_cancellation()?;
|
||||||
});
|
let is_pdf = resource.data.starts_with(b"%PDF-")
|
||||||
let hidden = special.hidden;
|
|| resource.version.path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("pdf"));
|
||||||
self.emit_pdf_image_object(image.clone(), special.attributes, None, None);
|
let named = special.name.is_some();
|
||||||
Ok((!hidden).then_some(image))
|
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.
|
// 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"bxobj", b"bxobj"), (b"bform", b"bxobj"), (b"beginxobj", b"bxobj"),
|
||||||
(b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"),
|
(b"exobj", b"exobj"), (b"eform", b"exobj"), (b"endxobj", b"exobj"),
|
||||||
(b"uxobj", b"uxobj"), (b"usexobj", b"uxobj"),
|
(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) {
|
if let Some(operands) = xdv_operand(body, name) {
|
||||||
return Some((kind, operands));
|
return Some((kind, operands));
|
||||||
|
|||||||
@@ -2971,9 +2971,14 @@ fn write_pdf(
|
|||||||
);
|
);
|
||||||
(image.id, object)
|
(image.id, object)
|
||||||
}).collect();
|
}).collect();
|
||||||
|
let mut xdv_xobjects = BTreeMap::new();
|
||||||
for form in forms.iter().filter(|form| form.xdv.is_some()) {
|
for form in forms.iter().filter(|form| form.xdv.is_some()) {
|
||||||
objects.push(Vec::new());
|
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 append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> {
|
||||||
let images = list
|
let images = list
|
||||||
@@ -2988,11 +2993,12 @@ fn write_pdf(
|
|||||||
xobjects.push_str(&format!(" /PI{id} {} 0 R", form_ids[&id]));
|
xobjects.push_str(&format!(" /PI{id} {} 0 R", form_ids[&id]));
|
||||||
}
|
}
|
||||||
let placements: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
|
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,
|
_ => None,
|
||||||
}).collect();
|
}).collect();
|
||||||
for number in placements {
|
for (number, xdv) in placements {
|
||||||
let id = device_objects.get(&number).ok_or("missing native PDF Form canvas")?;
|
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"));
|
xobjects.push_str(&format!(" /Fm{number} {id} 0 R"));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -3571,7 +3577,6 @@ fn write_pdf(
|
|||||||
let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects);
|
let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects);
|
||||||
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
|
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 keep_xdv_destinations = unicode.is_some_and(|options| options.xdv_keep_destinations);
|
||||||
let mut xdv_names = BTreeMap::new();
|
let mut xdv_names = BTreeMap::new();
|
||||||
if !keep_xdv_destinations {
|
if !keep_xdv_destinations {
|
||||||
@@ -3617,7 +3622,7 @@ fn write_pdf(
|
|||||||
destination.collect_references(&mut pending);
|
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 {
|
let references = crate::pdf_device::xdv_object::References {
|
||||||
pages: &navigation.pages,
|
pages: &navigation.pages,
|
||||||
named: &named_objects,
|
named: &named_objects,
|
||||||
@@ -3625,8 +3630,9 @@ fn write_pdf(
|
|||||||
let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
let compression = pages[0].pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
||||||
xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?;
|
xdv_objects.write_objects(&references, &mut objects, compression, diagnostics)?;
|
||||||
if let Some(xdv) = xdv {
|
if let Some(xdv) = xdv {
|
||||||
|
xdv.write_image_attributes(&form_ids, &references, &mut objects)?;
|
||||||
for (form, resources, content) in xdv_forms {
|
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)?;
|
objects[id - 1] = xdv.write_form(form, resources.as_bytes(), &content, &references, &mut objects, diagnostics)?;
|
||||||
}
|
}
|
||||||
xdv.write_page_dictionaries(pages, &references, &mut objects)?;
|
xdv.write_page_dictionaries(pages, &references, &mut objects)?;
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ pub enum PdfGraphics {
|
|||||||
number: u32,
|
number: u32,
|
||||||
options: super::xdv_navigation::FormOptions,
|
options: super::xdv_navigation::FormOptions,
|
||||||
source: crate::execution::TokenOrigin,
|
source: crate::execution::TokenOrigin,
|
||||||
|
#[serde(default)]
|
||||||
|
imported_available: bool,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,174 +1,231 @@
|
|||||||
//! The xdvipdfmx raster image device special.
|
//! Image selection and placement from the xdvipdfmx device specials.
|
||||||
use super::Affine;
|
use super::{
|
||||||
use crate::pdf_image::{PdfImage, PdfImageUse, real};
|
Affine,
|
||||||
use lopdf::{Object, content::Content};
|
xdv_navigation::FormOptions,
|
||||||
use std::{iter::Peekable, str::SplitAsciiWhitespace, sync::Arc};
|
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(crate) struct ImageSpecial {
|
||||||
pub file: String,
|
pub file: String,
|
||||||
pub attributes: Vec<u8>,
|
pub name: Option<Vec<u8>>,
|
||||||
|
pub(super) attributes: Dictionary,
|
||||||
pub hidden: bool,
|
pub hidden: bool,
|
||||||
bbox: Option<[f64; 4]>,
|
pub page: PageSelection,
|
||||||
dimensions: [Option<f64>; 3],
|
pub page_box: PageBox,
|
||||||
transform: Affine,
|
pub placement: FormOptions,
|
||||||
clip: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ImageSpecial {
|
impl ImageSpecial {
|
||||||
pub(crate) fn parse(data: &[u8], magnification: i32) -> Result<Option<Self>, String> {
|
pub(crate) fn parse(input: &[u8], position: Position) -> Result<(Self, Vec<String>), String> {
|
||||||
let Some(body) = data.trim_ascii_start().strip_prefix(b"pdf:") else {
|
let input = trim_pdf(input);
|
||||||
return Ok(None);
|
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 mut quoted = false;
|
||||||
let name_end = body
|
let mut escaped = false;
|
||||||
|
let file_pos = input
|
||||||
.iter()
|
.iter()
|
||||||
.position(|byte| byte.is_ascii_whitespace() || matches!(byte, b'(' | b'<'))
|
.position(|&byte| {
|
||||||
.unwrap_or(body.len());
|
if escaped {
|
||||||
if !matches!(&body[..name_end], b"image" | b"img") {
|
escaped = false;
|
||||||
return Ok(None);
|
} else if quoted && byte == b'\\' {
|
||||||
}
|
escaped = true;
|
||||||
let body = &body[name_end..];
|
} else if byte == b'"' {
|
||||||
let file_pos = body
|
quoted = !quoted;
|
||||||
.iter()
|
} else if !quoted && matches!(byte, b'(' | b'<') {
|
||||||
.position(|byte| matches!(byte, b'(' | b'<'))
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
})
|
||||||
.ok_or("missing XDV image filename string")?;
|
.ok_or("missing XDV image filename string")?;
|
||||||
let parameters =
|
let parameters =
|
||||||
std::str::from_utf8(&body[..file_pos]).map_err(|error| error.to_string())?;
|
std::str::from_utf8(&input[..file_pos]).map_err(|_| "invalid XDV image options")?;
|
||||||
let mut words = parameters.split_ascii_whitespace().peekable();
|
let mut rest = parameters;
|
||||||
let mut bbox = None;
|
let mut words = std::iter::from_fn(|| {
|
||||||
let mut dimensions = [None; 3];
|
rest = rest.trim_ascii_start();
|
||||||
let mut clip = true;
|
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 hidden = false;
|
||||||
let mut scales = [None; 2];
|
let mut placement = FormOptions::default();
|
||||||
let mut overall_scale = None;
|
|
||||||
let mut rotation = 0.0;
|
|
||||||
let mut matrix = None;
|
|
||||||
while let Some(parameter) = words.next() {
|
while let Some(parameter) = words.next() {
|
||||||
match parameter {
|
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,
|
"hide" => hidden = true,
|
||||||
"page" if matches!(number(words.next())?, 0.0 | 1.0) => {}
|
"page" => {
|
||||||
_ => return Err(format!("unsupported XDV raster image option {parameter}")),
|
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());
|
||||||
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"] ");
|
|
||||||
}
|
}
|
||||||
(b"Interpolate", Object::Boolean(value)) => {
|
page = requested as i32;
|
||||||
attributes.extend_from_slice(if *value {
|
}
|
||||||
b"/Interpolate true "
|
"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 {
|
} else {
|
||||||
b"/Interpolate false "
|
byte
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
_ => {
|
destination = Some(name);
|
||||||
return Err(format!(
|
}
|
||||||
"unsupported XDV image attribute {}",
|
word if placement.read_option(word, &mut words, position.magnification)? => {}
|
||||||
String::from_utf8_lossy(key)
|
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 {
|
Ok(attributes)
|
||||||
file,
|
|
||||||
attributes,
|
|
||||||
hidden,
|
|
||||||
bbox,
|
|
||||||
dimensions,
|
|
||||||
transform,
|
|
||||||
clip,
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn place(&self, id: usize, image: Arc<PdfImage>) -> Result<PdfImageUse, String> {
|
pub(crate) fn place_raster(
|
||||||
let [natural_w, natural_h] = image.extent();
|
&self,
|
||||||
let ([pixels_w, pixels_h], _) = image
|
id: usize,
|
||||||
|
image: Arc<PdfImage>,
|
||||||
|
) -> Result<PdfImageUse, String> {
|
||||||
|
let (pixels, _) = image
|
||||||
.raster_frame()
|
.raster_frame()
|
||||||
.ok_or("XDV special needs a raster image")?;
|
.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];
|
let [box_w, box_h] = [right - left, top - bottom];
|
||||||
if box_w <= 0.0 || box_h <= 0.0 {
|
if box_w <= 0.0 || box_h <= 0.0 {
|
||||||
return Err("XDV image bounding box must have positive dimensions".into());
|
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 requested_h = requested_h.or(depth.map(|_| 0.0));
|
||||||
let depth = depth.unwrap_or(0.0);
|
let depth = depth.unwrap_or(0.0);
|
||||||
let [xscale, yscale] = [natural_w / box_w, natural_h / box_h];
|
let [xscale, yscale] = [natural_w / box_w, natural_h / box_h];
|
||||||
@@ -191,26 +248,104 @@ impl ImageSpecial {
|
|||||||
-left * width / natural_w,
|
-left * width / natural_w,
|
||||||
-bottom * height / natural_h - depth,
|
-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,
|
left / natural_w,
|
||||||
bottom / natural_h,
|
bottom / natural_h,
|
||||||
box_w / natural_w,
|
box_w / natural_w,
|
||||||
box_h / natural_h,
|
box_h / natural_h,
|
||||||
]);
|
]);
|
||||||
PdfImageUse::new_xdv_raster_special(
|
Ok((self.affine().concatenate(sizing), annotation_box))
|
||||||
id, image, self.transform.concatenate(sizing), annotation_box, self.clip,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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> {
|
pub(super) fn number(word: Option<&str>) -> Result<f64, &'static str> {
|
||||||
word.and_then(|word| word.parse::<f64>().ok())
|
word.and_then(|word| word.parse::<f64>().ok())
|
||||||
.filter(|value| value.is_finite())
|
.filter(|value| value.is_finite())
|
||||||
.ok_or("invalid XDV image number")
|
.ok_or("invalid XDV image number")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn length(
|
pub(super) fn length<'a>(
|
||||||
words: &mut Peekable<SplitAsciiWhitespace<'_>>,
|
words: &mut Peekable<impl Iterator<Item = &'a str>>,
|
||||||
magnification: i32,
|
magnification: i32,
|
||||||
) -> Result<f64, &'static str> {
|
) -> Result<f64, &'static str> {
|
||||||
let word = words.next().ok_or("missing XDV image length")?;
|
let word = words.next().ok_or("missing XDV image length")?;
|
||||||
|
|||||||
@@ -8,11 +8,13 @@ use crate::{
|
|||||||
pdf_device::{
|
pdf_device::{
|
||||||
Affine, PdfGraphics, PdfLiteralMode,
|
Affine, PdfGraphics, PdfLiteralMode,
|
||||||
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
|
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
|
||||||
xdv_image::{length, number},
|
xdv_image::{ImageSpecial, ImportGeometry, length, number},
|
||||||
xdv_page_origin,
|
xdv_page_origin,
|
||||||
},
|
},
|
||||||
|
pdf_image::{PageBox, PageSelection},
|
||||||
provenance::PaintSource,
|
provenance::PaintSource,
|
||||||
render::{DisplayItem, DisplayList},
|
render::{DisplayItem, DisplayList},
|
||||||
|
resources::ResourceVersion,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::super::xdv_object::{identifier, trim_pdf};
|
use super::super::xdv_object::{identifier, trim_pdf};
|
||||||
@@ -42,58 +44,71 @@ impl FormOptions {
|
|||||||
.peekable();
|
.peekable();
|
||||||
let mut options = Self::default();
|
let mut options = Self::default();
|
||||||
while let Some(word) = words.next() {
|
while let Some(word) = words.next() {
|
||||||
match word {
|
if word != "hide" && !options.read_option(word, &mut words, magnification)? {
|
||||||
"bbox" => {
|
return Err(format!("unsupported XDV form option {word}"));
|
||||||
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 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))?;
|
checked_box(bounds.map(f64::from_bits))?;
|
||||||
}
|
}
|
||||||
let [width, height, depth] = options.size;
|
let [width, height, depth] = self.size;
|
||||||
let [sx, sy] = options.axis_scale;
|
let [sx, sy] = self.axis_scale;
|
||||||
let warning = if width.is_some() && sx.is_some() {
|
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.")
|
Some("Can't supply both width and xscale. Ignore xscale.")
|
||||||
} else if (height.is_some() || depth.is_some()) && sy.is_some() {
|
} 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.")
|
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());
|
return Err("XDV form scale conflicts with an axis scale".into());
|
||||||
} else if options.matrix.is_some()
|
} else if self.matrix.is_some()
|
||||||
&& (sx.is_some()
|
&& (sx.is_some() || sy.is_some() || self.scale.is_some() || self.rotation.is_some())
|
||||||
|| sy.is_some()
|
|
||||||
|| options.scale.is_some()
|
|
||||||
|| options.rotation.is_some())
|
|
||||||
{
|
{
|
||||||
Some(
|
Some(
|
||||||
"Can't supply transform matrix along with scales or rotate. Ignore scales and rotate.",
|
"Can't supply transform matrix along with scales or rotate. Ignore scales and rotate.",
|
||||||
@@ -101,7 +116,7 @@ impl FormOptions {
|
|||||||
} else {
|
} else {
|
||||||
None
|
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> {
|
fn capture_bounds(self) -> Result<[u64; 4], String> {
|
||||||
@@ -124,34 +139,35 @@ impl FormOptions {
|
|||||||
capture_y: Option<f64>,
|
capture_y: Option<f64>,
|
||||||
) -> Result<FormUse, String> {
|
) -> Result<FormUse, String> {
|
||||||
let captured = captured.map(f64::from_bits);
|
let captured = captured.map(f64::from_bits);
|
||||||
let user_bbox = self.bbox.map(|values| values.map(f64::from_bits));
|
let fitting = capture_y.map(|capture_y| {
|
||||||
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 [left, bottom, right, top] = captured;
|
let [left, bottom, right, top] = captured;
|
||||||
// xdvipdfmx 20260113 fits against a separate stored extent.
|
// The reference Form extent uses the unshifted lower edge and
|
||||||
// Its vertical samples are the unshifted lower edge and the
|
// the capture-origin-adjusted zero and upper edge.
|
||||||
// capture-origin-adjusted zero and upper edge (pdf_ximage_set_form).
|
|
||||||
let y = [-capture_y, top - capture_y];
|
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 {
|
let (natural, offset) = if let Some([x0, y0, x1, y1]) = user_bbox {
|
||||||
([x1 - x0, y1 - y0], [-x0, -y0])
|
([x1 - x0, y1 - y0], [-x0, -y0])
|
||||||
} else {
|
} 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 [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));
|
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
|
||||||
@@ -174,12 +190,20 @@ impl FormOptions {
|
|||||||
} else {
|
} else {
|
||||||
transform
|
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;
|
let matrix = transform.0;
|
||||||
if !matrix.iter().all(|value| value.is_finite()) {
|
if !matrix.iter().all(|value| value.is_finite()) {
|
||||||
return Err("XDV form placement transform out of range".into());
|
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] = if let Some([x0, y0, x1, y1]) = clip {
|
||||||
let [left, bottom, right, top] = captured;
|
let [left, bottom, right, top] = captured;
|
||||||
let left = left.max(x0.min(x1));
|
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> {
|
fn to_sp(value: f64) -> Result<i64, String> {
|
||||||
@@ -234,6 +285,12 @@ pub(super) struct Forms {
|
|||||||
names: BTreeMap<Vec<u8>, u32>,
|
names: BTreeMap<Vec<u8>, u32>,
|
||||||
definitions: BTreeMap<u32, Definition>,
|
definitions: BTreeMap<u32, Definition>,
|
||||||
active: Vec<Active>,
|
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)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
@@ -250,21 +307,34 @@ struct Definition {
|
|||||||
resources: Dictionary,
|
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 {
|
impl Forms {
|
||||||
pub(super) fn is_empty(&self) -> bool {
|
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> {
|
pub(super) fn number(&self, name: &[u8]) -> Option<u32> {
|
||||||
self.names.get(name).copied()
|
self.names.get(name).copied()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn register(&mut self, name: &[u8]) -> Result<u32, String> {
|
fn register(&mut self, name: Option<&[u8]>) -> Result<u32, String> {
|
||||||
if let Some(number) = self.number(name) {
|
if let Some(number) = name.and_then(|name| self.number(name)) {
|
||||||
return Ok(number);
|
return Ok(number);
|
||||||
}
|
}
|
||||||
let number = u32::try_from(self.names.len() + 1).map_err(|_| "XDV form limit exceeded")?;
|
let previous = self.next_number.max(self.names.len() as u32);
|
||||||
self.names.insert(name.to_vec(), number);
|
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)
|
Ok(number)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,6 +343,11 @@ impl Forms {
|
|||||||
.definitions
|
.definitions
|
||||||
.values()
|
.values()
|
||||||
.flat_map(|entry| entry.attributes.values().chain(entry.resources.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);
|
value.collect_references(pending);
|
||||||
}
|
}
|
||||||
@@ -280,6 +355,106 @@ impl Forms {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Navigation {
|
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(
|
pub(crate) fn form_special(
|
||||||
&mut self,
|
&mut self,
|
||||||
kind: &[u8],
|
kind: &[u8],
|
||||||
@@ -315,9 +490,10 @@ impl Navigation {
|
|||||||
}
|
}
|
||||||
let (name, rest) = identifier(input)?;
|
let (name, rest) = identifier(input)?;
|
||||||
let (options, warnings) = FormOptions::parse(rest, position.magnification)?;
|
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" {
|
let command = if kind == b"bxobj" {
|
||||||
if self.forms.definitions.contains_key(&number)
|
if self.forms.definitions.contains_key(&number)
|
||||||
|
|| self.forms.imports.contains_key(&number)
|
||||||
|| self.forms.active.iter().any(|form| form.number == number)
|
|| self.forms.active.iter().any(|form| form.number == number)
|
||||||
|| self.objects.contains_key(name)
|
|| self.objects.contains_key(name)
|
||||||
{
|
{
|
||||||
@@ -339,6 +515,7 @@ impl Navigation {
|
|||||||
number,
|
number,
|
||||||
options,
|
options,
|
||||||
source,
|
source,
|
||||||
|
imported_available: self.forms.imports.contains_key(&number),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Ok((command, warnings))
|
Ok((command, warnings))
|
||||||
@@ -443,19 +620,28 @@ impl Navigation {
|
|||||||
number,
|
number,
|
||||||
options,
|
options,
|
||||||
source,
|
source,
|
||||||
|
imported_available,
|
||||||
},
|
},
|
||||||
} => {
|
} => {
|
||||||
let bounds = self
|
let form = if let Some(import) = self.forms.imports.get(&number) {
|
||||||
.forms
|
self.forms.images[import].geometry.place(
|
||||||
.definitions
|
number,
|
||||||
.get(&number)
|
options,
|
||||||
.ok_or("referenced XDV form is undefined")?
|
imported_available,
|
||||||
.bounds;
|
)?
|
||||||
let form = options.place(
|
} else {
|
||||||
number,
|
let bounds = self
|
||||||
bounds,
|
.forms
|
||||||
capture_positions.get(&number).copied(),
|
.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 },
|
DisplayItem::PdfForm { x, y, form },
|
||||||
Some(PaintSource::token(source)),
|
Some(PaintSource::token(source)),
|
||||||
|
|||||||
@@ -21,12 +21,13 @@ use std::{
|
|||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
pub(crate) enum PageSelection {
|
pub(crate) enum PageSelection {
|
||||||
Number(i32),
|
Number(i32),
|
||||||
Named(Vec<u8>),
|
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)]
|
#[repr(i32)]
|
||||||
pub(crate) enum PageBox {
|
pub(crate) enum PageBox {
|
||||||
Media = 1,
|
Media = 1,
|
||||||
@@ -43,6 +44,11 @@ enum PageBoxSelection {
|
|||||||
Xdv(PageBox),
|
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)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct PdfImage {
|
pub struct PdfImage {
|
||||||
pub version: ResourceVersion,
|
pub version: ResourceVersion,
|
||||||
@@ -744,6 +750,42 @@ impl PdfImage {
|
|||||||
.then(|| page.clamp(1, pages) as u32)
|
.then(|| page.clamp(1, pages) as u32)
|
||||||
.ok_or_else(|| "required page does not exist".into())
|
.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 {
|
pub(crate) fn count_pages(resource: &LoadedResource) -> usize {
|
||||||
@@ -769,7 +811,7 @@ impl PdfImage {
|
|||||||
box_selection: PageBoxSelection,
|
box_selection: PageBoxSelection,
|
||||||
remap_type1: bool,
|
remap_type1: bool,
|
||||||
select_page: impl FnOnce(&Document, &BTreeMap<u32, ObjectId>) -> Result<u32, String>,
|
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 pages = doc.get_pages();
|
||||||
let page = select_page(&doc, &pages)?;
|
let page = select_page(&doc, &pages)?;
|
||||||
let page_id = pages
|
let page_id = pages
|
||||||
@@ -930,7 +972,7 @@ impl PdfImage {
|
|||||||
device_cid_cff_fonts: fonts.cid_cff,
|
device_cid_cff_fonts: fonts.cid_cff,
|
||||||
pdftex_source,
|
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;
|
let operations = Content::decode(&contents).unwrap().operations;
|
||||||
assert_eq!(&matrices(&operations)[0][..4], &[1.75, 0.0, 0.0, 0.80132]);
|
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");
|
||||||
|
}
|
||||||
@@ -18,6 +18,36 @@
|
|||||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
|
||||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||||
|
|
||||||
|
## 2026-11-28 XeLaTeX 命名 PDF 和位图导入
|
||||||
|
|
||||||
|
`pdf:image`、`pdf:img` 和 `pdf:epdf` 按出页顺序执行。PDF 直接
|
||||||
|
导入真实页树、页面框、正文流和资源图,支持编号和命名目的地选页。
|
||||||
|
命名 PDF 和位图可先登记后放置,也可从前页引用后页登记的对象。
|
||||||
|
页面、捕获 Form 和目录字段引用同一个间接对象。回执保留实际
|
||||||
|
资源指纹。调用方字典可覆盖对象属性并引用其他命名对象,流
|
||||||
|
长度由实际数据写出。
|
||||||
|
[参考驱动的 PDF 页导入](https://raw.githubusercontent.com/TeX-Live/texlive-source/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/dvipdfm-x/epdf.c)
|
||||||
|
|
||||||
|
编号/命名选页、裁切、矩阵、字典与位图直接对照,加上原样
|
||||||
|
graphicx 的 dvipdfmx 后端,共九页 144 DPI 彩色逐像素一致。
|
||||||
|
从原样 ACM 归档取出的 sampleteaser.pdf 在跨页和嵌套 Form 中
|
||||||
|
共享同一导入对象,保留实际图像及 ICC 流。graphicx 辅助文件
|
||||||
|
与参考逐字节一致。开发构建和十一项定向回归通过。
|
||||||
|
既有 xetex.def 的六处位图放置另有一页彩色与 aux 对照通过。
|
||||||
|
原先的位图原语对照仍有 680 个参考差异像素。新旧主线同版跑出的
|
||||||
|
这页光栅保持一致。
|
||||||
|
|
||||||
|
三页会话改动图形资源只更新两个使用页,调整单页裁切只更新
|
||||||
|
该页。图形损坏时仍保留上次发布的 PDF,恢复后用同一修订
|
||||||
|
独立全量核对 PDF、测量页、预览、来源映射和 aux。
|
||||||
|
资源与裁切编辑各复用 86 步,恢复复用 1,684 步,页面内容保持稳定。
|
||||||
|
|
||||||
|
回执在 `target/p3-xdv-named-pdf-import/receipt.json`,SHA-256
|
||||||
|
为 `c82d9645d5211f21e7265e8ae4915cab690fa46959b87305028cf07c5e772d3d`。下一入口是 XObject 的链接注释几何。参考
|
||||||
|
已用一张裁切导入图生成实际链接,当前输出缺该注释。输入与
|
||||||
|
两端 PDF 在 `target/p3-xdv-import-link-bounds`。原样出版
|
||||||
|
矩阵、统一发布版验收和 100 ms 可见时延继续按总目标执行。
|
||||||
|
|
||||||
## 2026-11-28 XeLaTeX PDF Form 尺寸、裁切与局部坐标
|
## 2026-11-28 XeLaTeX PDF Form 尺寸、裁切与局部坐标
|
||||||
|
|
||||||
Form 放置按出页指令顺序判定目标是否已定义。显式宽、高、深
|
Form 放置按出页指令顺序判定目标是否已定义。显式宽、高、深
|
||||||
|
|||||||
Reference in new issue
Block a user