Capture and reuse XeLaTeX PDF form contents
This commit is contained in:
1 parent
009fde04f7
commit
c0e2346b05
16 files changed
+706
-53
No files matched your search
@@ -10,6 +10,20 @@ pub struct FormUse {
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
pub depth: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) xdv: Option<XdvPlacement>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(crate) struct XdvPlacement {
|
||||
pub(crate) matrix: [u64; 6],
|
||||
pub(crate) bounds: [i64; 4],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct XdvCanvas {
|
||||
pub(crate) anchor: [i64; 2],
|
||||
pub(crate) bounds: [i64; 4],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -45,4 +59,5 @@ pub struct FormDisplay {
|
||||
pub form: FormUse,
|
||||
pub resource_number: u32,
|
||||
pub list: DisplayList,
|
||||
pub(crate) xdv: Option<XdvCanvas>,
|
||||
}
|
||||
@@ -46,6 +46,13 @@ pub enum PdfGraphics {
|
||||
SaveMatrix(PdfMatrix),
|
||||
/// An XDV special switched the device from text to graphics mode.
|
||||
TextBoundary,
|
||||
XdvFormBegin(u32),
|
||||
XdvFormEnd(u32),
|
||||
XdvFormUse {
|
||||
number: u32,
|
||||
options: super::xdv_navigation::FormOptions,
|
||||
source: crate::execution::TokenOrigin,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -14,6 +14,9 @@ use super::xdv_object::{
|
||||
mod named_objects;
|
||||
mod page_dictionaries;
|
||||
mod page_resources;
|
||||
mod forms;
|
||||
pub use forms::FormOptions;
|
||||
use forms::Forms;
|
||||
use page_resources::PageResources;
|
||||
use page_dictionaries::PageDictionaries;
|
||||
pub(crate) use named_objects::ObjectCommand;
|
||||
@@ -31,6 +34,8 @@ pub(crate) struct Navigation {
|
||||
page_dictionaries: PageDictionaries,
|
||||
#[serde(default, skip_serializing_if = "PageResources::is_empty")]
|
||||
page_resources: PageResources,
|
||||
#[serde(default, skip_serializing_if = "Forms::is_empty")]
|
||||
forms: Forms,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -123,12 +128,14 @@ impl Navigation {
|
||||
}
|
||||
self.page_dictionaries.collect_references(pending);
|
||||
self.page_resources.collect_references(pending);
|
||||
self.forms.collect_references(pending);
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_objects<'a>(
|
||||
&'a self,
|
||||
mut pending: Vec<&'a [u8]>,
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
device_objects: &BTreeMap<u32, u32>,
|
||||
) -> Result<BTreeMap<Vec<u8>, u32>, String> {
|
||||
let mut names = BTreeSet::new();
|
||||
while let Some(name) = pending.pop() {
|
||||
@@ -137,6 +144,9 @@ impl Navigation {
|
||||
}
|
||||
}
|
||||
names.into_iter().map(|name| {
|
||||
if let Some(number) = self.forms.number(name) {
|
||||
return Ok((name.to_vec(), *device_objects.get(&number).ok_or("unallocated XDV form reference")?));
|
||||
}
|
||||
objects.push(Vec::new());
|
||||
let id = u32::try_from(objects.len()).map_err(|_| "XDV PDF object ID out of range")?;
|
||||
Ok((name.to_vec(), id))
|
||||
@@ -151,6 +161,9 @@ impl Navigation {
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
for (name, &id) in references.named {
|
||||
if self.forms.number(name).is_some() {
|
||||
continue;
|
||||
}
|
||||
objects[id as usize - 1] = if let Some(object) = self.objects.get(name) {
|
||||
object.pdf(references, compression)?
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use lopdf::{Dictionary as PdfDictionary, Object};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
execution::TokenOrigin,
|
||||
pdf_device::{
|
||||
Affine, DeviceOrigin, PdfGraphics,
|
||||
forms::{FormDisplay, FormUse, XdvCanvas, XdvPlacement},
|
||||
xdv_image::{length, number},
|
||||
xdv_page_origin,
|
||||
},
|
||||
provenance::PaintSource,
|
||||
render::{DisplayItem, DisplayList},
|
||||
};
|
||||
|
||||
use super::super::xdv_object::{identifier, trim_pdf};
|
||||
use super::{
|
||||
Dictionary, Navigation, Position, References, dictionary, encode_device_value,
|
||||
output_dictionary, page_resources::merge_output_resources, parse_value,
|
||||
};
|
||||
|
||||
const SP_PER_BP: f64 = 65536.0 * 803.0 / 800.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct FormOptions {
|
||||
bbox: Option<[u64; 4]>,
|
||||
size: [Option<u64>; 3],
|
||||
scale: [Option<u64>; 2],
|
||||
offset: [u64; 2],
|
||||
rotation: u64,
|
||||
}
|
||||
|
||||
impl FormOptions {
|
||||
fn parse(input: &[u8], magnification: i32) -> Result<Self, String> {
|
||||
let mut words = std::str::from_utf8(input)
|
||||
.map_err(|_| "invalid XDV form options")?
|
||||
.split_ascii_whitespace()
|
||||
.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());
|
||||
}
|
||||
"xoffset" | "yoffset" => {
|
||||
options.offset[usize::from(word == "yoffset")] =
|
||||
length(&mut words, magnification)?.to_bits();
|
||||
}
|
||||
"scale" => options.scale = [Some(number(words.next())?.to_bits()); 2],
|
||||
"xscale" | "yscale" => {
|
||||
options.scale[usize::from(word == "yscale")] =
|
||||
Some(number(words.next())?.to_bits());
|
||||
}
|
||||
"rotate" => options.rotation = number(words.next())?.to_bits(),
|
||||
_ => return Err(format!("unsupported XDV form option {word}")),
|
||||
}
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn capture_bounds(self) -> Result<[i64; 4], String> {
|
||||
let [width, height, depth] = self.size.map(|v| v.map_or(0.0, f64::from_bits));
|
||||
let bbox = self
|
||||
.bbox
|
||||
.map_or([0.0, -depth, width, height], |v| v.map(f64::from_bits));
|
||||
let [left, bottom, right, top] = checked_box(bbox)?;
|
||||
if left >= right || bottom >= top {
|
||||
return Err("XDV form bounding box must have positive dimensions".into());
|
||||
}
|
||||
Ok([left, bottom, right, top])
|
||||
}
|
||||
|
||||
fn place(self, number: u32, bounds: [i64; 4]) -> Result<FormUse, String> {
|
||||
if self.bbox.is_some() {
|
||||
return Err("unsupported XDV form placement bounding box".into());
|
||||
}
|
||||
let [left, bottom, right, top] = bounds.map(|p| p as f64 / SP_PER_BP);
|
||||
let natural = [right - left, top - bottom];
|
||||
let [width, height, depth] = self.size.map(|v| v.map(f64::from_bits));
|
||||
let vertical = height
|
||||
.or(depth.map(|_| 0.0))
|
||||
.map(|h| h + depth.unwrap_or(0.0));
|
||||
let requested = [
|
||||
width.map(|w| w / natural[0]),
|
||||
vertical.map(|h| h / natural[1]),
|
||||
];
|
||||
let scales = self.scale.map(|v| v.map(f64::from_bits));
|
||||
let sx = requested[0].or(scales[0]).or(requested[1]).unwrap_or(1.0);
|
||||
let sy = requested[1].or(scales[1]).or(requested[0]).unwrap_or(1.0);
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err("zero XDV form placement scale".into());
|
||||
}
|
||||
let [dx, dy] = self.offset.map(f64::from_bits);
|
||||
let (sin, cos) = f64::from_bits(self.rotation).to_radians().sin_cos();
|
||||
let matrix = [
|
||||
cos * sx,
|
||||
sin * sx,
|
||||
-sin * sy,
|
||||
cos * sy,
|
||||
dx,
|
||||
dy + vertical.map_or(0.0, |_| -depth.unwrap_or(0.0) - bottom * sy),
|
||||
];
|
||||
let transform = Affine(matrix);
|
||||
let mut extent = [
|
||||
f64::INFINITY,
|
||||
f64::INFINITY,
|
||||
f64::NEG_INFINITY,
|
||||
f64::NEG_INFINITY,
|
||||
];
|
||||
for [x, y] in [[left, bottom], [left, top], [right, bottom], [right, top]] {
|
||||
let [x, y] = transform.point(x, y);
|
||||
extent = [
|
||||
extent[0].min(x),
|
||||
extent[1].min(y),
|
||||
extent[2].max(x),
|
||||
extent[3].max(y),
|
||||
];
|
||||
}
|
||||
let bounds = checked_box(extent)?;
|
||||
Ok(FormUse {
|
||||
number,
|
||||
width: bounds[2] - bounds[0],
|
||||
height: bounds[3],
|
||||
depth: -bounds[1],
|
||||
xdv: Some(XdvPlacement {
|
||||
matrix: matrix.map(f64::to_bits),
|
||||
bounds,
|
||||
}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn to_sp(value: f64) -> Result<i64, String> {
|
||||
let value = (value * SP_PER_BP).round();
|
||||
if !(-1_073_741_823.0..=1_073_741_823.0).contains(&value) {
|
||||
return Err("XDV form dimension out of range".into());
|
||||
}
|
||||
Ok(value as i64)
|
||||
}
|
||||
|
||||
fn checked_box(values: [f64; 4]) -> Result<[i64; 4], String> {
|
||||
let [a, b, c, d] = values.map(to_sp);
|
||||
Ok([a?, b?, c?, d?])
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct Forms {
|
||||
names: BTreeMap<Vec<u8>, u32>,
|
||||
definitions: BTreeMap<u32, Definition>,
|
||||
active: Vec<Active>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct Active {
|
||||
number: u32,
|
||||
bounds: [i64; 4],
|
||||
outer_resources: Dictionary,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
struct Definition {
|
||||
bounds: [i64; 4],
|
||||
attributes: Dictionary,
|
||||
resources: Dictionary,
|
||||
}
|
||||
|
||||
impl Forms {
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
self.names.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) {
|
||||
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);
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(super) fn collect_references<'a>(&'a self, pending: &mut Vec<&'a [u8]>) {
|
||||
for value in self
|
||||
.definitions
|
||||
.values()
|
||||
.flat_map(|entry| entry.attributes.values().chain(entry.resources.values()))
|
||||
{
|
||||
value.collect_references(pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Navigation {
|
||||
pub(crate) fn form_special(
|
||||
&mut self,
|
||||
kind: &[u8],
|
||||
input: &[u8],
|
||||
position: Position,
|
||||
source: TokenOrigin,
|
||||
limit: usize,
|
||||
) -> Result<(PdfGraphics, Vec<String>), String> {
|
||||
self.add_payload(input.len(), limit)?;
|
||||
if kind == b"exobj" {
|
||||
let attributes = if trim_pdf(input).is_empty() {
|
||||
Dictionary::new()
|
||||
} else {
|
||||
dictionary(input, position)?
|
||||
};
|
||||
let form = self
|
||||
.forms
|
||||
.active
|
||||
.pop()
|
||||
.ok_or("XDV form capture was not started")?;
|
||||
let warnings = self.merge_resources((*self.page_resources.defaults).clone(), true)?;
|
||||
let resources =
|
||||
std::mem::replace(&mut self.page_resources.current, form.outer_resources);
|
||||
self.forms.definitions.insert(
|
||||
form.number,
|
||||
Definition {
|
||||
bounds: form.bounds,
|
||||
attributes,
|
||||
resources,
|
||||
},
|
||||
);
|
||||
return Ok((PdfGraphics::XdvFormEnd(form.number), warnings));
|
||||
}
|
||||
let (name, rest) = identifier(input)?;
|
||||
let options = FormOptions::parse(rest, position.magnification)?;
|
||||
let number = self.forms.register(name)?;
|
||||
let command = if kind == b"bxobj" {
|
||||
if self.forms.definitions.contains_key(&number)
|
||||
|| self.forms.active.iter().any(|form| form.number == number)
|
||||
|| self.objects.contains_key(name)
|
||||
{
|
||||
return Err("duplicate XDV form definition".into());
|
||||
}
|
||||
if self.forms.active.len() >= 64 {
|
||||
return Err("XDV form nesting limit exceeded".into());
|
||||
}
|
||||
let bounds = options.capture_bounds()?;
|
||||
let outer_resources = std::mem::take(&mut self.page_resources.current);
|
||||
self.forms.active.push(Active {
|
||||
number,
|
||||
bounds,
|
||||
outer_resources,
|
||||
});
|
||||
PdfGraphics::XdvFormBegin(number)
|
||||
} else {
|
||||
PdfGraphics::XdvFormUse {
|
||||
number,
|
||||
options,
|
||||
source,
|
||||
}
|
||||
};
|
||||
Ok((command, Vec::new()))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_form_boundary(&self) -> Result<(), &'static str> {
|
||||
if self.forms.active.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("unclosed XDV form capture at shipout")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn split_forms(
|
||||
&self,
|
||||
pages: &mut [DisplayList],
|
||||
) -> Result<Vec<FormDisplay>, String> {
|
||||
if self.forms.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut forms = Vec::new();
|
||||
for page in pages {
|
||||
let mut captures: Vec<(u32, XdvCanvas, DisplayList)> = Vec::new();
|
||||
let mut sources = std::mem::take(&mut page.sources);
|
||||
let mut packets = page.prepared_virtual_glyphs.as_mut().map(std::mem::take);
|
||||
for (index, item) in std::mem::take(&mut page.items).into_iter().enumerate() {
|
||||
let origin = sources.remove(&index);
|
||||
let packet = packets.as_mut().and_then(|packets| packets.remove(&index));
|
||||
let (item, origin) = match item {
|
||||
DisplayItem::PdfGraphics {
|
||||
x,
|
||||
y,
|
||||
operation: PdfGraphics::XdvFormBegin(number),
|
||||
} => {
|
||||
let bounds = self.forms.definitions[&number].bounds;
|
||||
let list = DisplayList {
|
||||
width: page.width,
|
||||
height: page.height,
|
||||
units: page.units,
|
||||
magnification: page.magnification,
|
||||
pdf: page.pdf.clone(),
|
||||
pdf_font_bindings: page.pdf_font_bindings.clone(),
|
||||
prepared_virtual_glyphs: packets.as_ref().map(|_| BTreeMap::new()),
|
||||
..Default::default()
|
||||
};
|
||||
captures.push((
|
||||
number,
|
||||
XdvCanvas {
|
||||
anchor: [x, y],
|
||||
bounds,
|
||||
},
|
||||
list,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
DisplayItem::PdfGraphics {
|
||||
operation: PdfGraphics::XdvFormEnd(expected),
|
||||
..
|
||||
} => {
|
||||
let (number, geometry, list) =
|
||||
captures.pop().ok_or("missing started XDV form")?;
|
||||
if number != expected {
|
||||
return Err("mismatched XDV form capture".into());
|
||||
}
|
||||
let form = FormOptions::default().place(number, geometry.bounds)?;
|
||||
forms.push(FormDisplay {
|
||||
form,
|
||||
resource_number: 0,
|
||||
list,
|
||||
xdv: Some(geometry),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
DisplayItem::PdfGraphics {
|
||||
x,
|
||||
y,
|
||||
operation:
|
||||
PdfGraphics::XdvFormUse {
|
||||
number,
|
||||
options,
|
||||
source,
|
||||
},
|
||||
} => {
|
||||
let bounds = self
|
||||
.forms
|
||||
.definitions
|
||||
.get(&number)
|
||||
.ok_or("referenced XDV form is undefined")?
|
||||
.bounds;
|
||||
let form = options.place(number, bounds)?;
|
||||
(
|
||||
DisplayItem::PdfForm { x, y, form },
|
||||
Some(PaintSource::token(source)),
|
||||
)
|
||||
}
|
||||
item => (item, origin),
|
||||
};
|
||||
let output = if let Some((_, _, form)) = captures.last_mut() {
|
||||
form
|
||||
} else {
|
||||
&mut *page
|
||||
};
|
||||
if let Some(source) = origin {
|
||||
output.sources.insert(output.items.len(), source);
|
||||
}
|
||||
if let Some(packet) = packet {
|
||||
output
|
||||
.prepared_virtual_glyphs
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.insert(output.items.len(), packet);
|
||||
}
|
||||
output.items.push(item);
|
||||
}
|
||||
if !captures.is_empty() {
|
||||
return Err("incomplete XDV form display list".into());
|
||||
}
|
||||
}
|
||||
Ok(forms)
|
||||
}
|
||||
|
||||
pub(crate) fn write_form(
|
||||
&self,
|
||||
form: &FormDisplay,
|
||||
resources: &[u8],
|
||||
content: &[u8],
|
||||
references: &References<'_>,
|
||||
objects: &mut [Vec<u8>],
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let geometry = form.xdv.expect("XDV form geometry");
|
||||
let list = &form.list;
|
||||
let magnification = f64::from(list.magnification) / 1000.0;
|
||||
let scale = magnification / SP_PER_BP;
|
||||
let digits = list.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
|
||||
let mut origin = DeviceOrigin::default();
|
||||
origin.move_to(
|
||||
xdv_page_origin(list.units, list.height, list.magnification),
|
||||
list.units,
|
||||
digits,
|
||||
);
|
||||
let [x, y] = geometry.anchor;
|
||||
let anchor = origin
|
||||
.move_to([x, list.height - y], list.units, digits)
|
||||
.unwrap_or([0, 0])
|
||||
.map(|value| value as f64 * magnification / 10f64.powi(i32::from(digits)));
|
||||
let round = |value: f64| (value * 1000.0).round() / 1000.0;
|
||||
let mut attributes = PdfDictionary::new();
|
||||
attributes.set("Type", Object::Name(b"XObject".to_vec()));
|
||||
attributes.set("Subtype", Object::Name(b"Form".to_vec()));
|
||||
attributes.set("FormType", 1);
|
||||
let bbox = geometry
|
||||
.bounds
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(axis, n)| Object::Real(round(anchor[axis % 2] + scale * n as f64)))
|
||||
.collect();
|
||||
attributes.set("BBox", Object::Array(bbox));
|
||||
attributes.set(
|
||||
"Matrix",
|
||||
Object::Array(
|
||||
[1.0, 0.0, 0.0, 1.0, round(-anchor[0]), round(-anchor[1])]
|
||||
.map(Object::Real)
|
||||
.into(),
|
||||
),
|
||||
);
|
||||
let definition = &self.forms.definitions[&form.form.number];
|
||||
for (key, value) in &output_dictionary(&definition.attributes, references)? {
|
||||
attributes.set(key.clone(), value.clone());
|
||||
}
|
||||
let Object::Dictionary(mut resources) = parse_value(resources)? else {
|
||||
unreachable!("generated XDV form resources");
|
||||
};
|
||||
merge_output_resources(
|
||||
&mut resources,
|
||||
&definition.resources,
|
||||
references,
|
||||
objects,
|
||||
diagnostics,
|
||||
)?;
|
||||
attributes.set("Resources", Object::Dictionary(resources));
|
||||
let encoded = encode_device_value(Object::Dictionary(attributes))?;
|
||||
Ok(crate::pdf::objects::stream_bytes(
|
||||
&encoded[2..encoded.len() - 2],
|
||||
content,
|
||||
list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@ use super::{
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct PageResources {
|
||||
current: Dictionary,
|
||||
defaults: Arc<Dictionary>,
|
||||
pub(super) current: Dictionary,
|
||||
pub(super) defaults: Arc<Dictionary>,
|
||||
pages: BTreeMap<usize, Dictionary>,
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ impl Navigation {
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn merge_resources(
|
||||
pub(super) fn merge_resources(
|
||||
&mut self,
|
||||
additions: Dictionary,
|
||||
deferred: bool,
|
||||
@@ -131,36 +131,7 @@ impl Navigation {
|
||||
.as_dict()
|
||||
.map_err(|_| "expected inline XDV resource dictionary")?
|
||||
.clone();
|
||||
for (category, new) in &output_dictionary(fields, references)? {
|
||||
let generated = resources.remove(category);
|
||||
let generated = generated
|
||||
.as_ref()
|
||||
.map(Object::as_dict)
|
||||
.transpose()
|
||||
.map_err(|_| "cannot merge a non-dictionary generated resource category")?;
|
||||
let effective = match new {
|
||||
Object::Dictionary(fields) => {
|
||||
if let Some(generated) = generated {
|
||||
let mut combined = generated.clone();
|
||||
merge_pdf_entries(&mut combined, fields, diagnostics);
|
||||
Object::Dictionary(combined)
|
||||
} else {
|
||||
new.clone()
|
||||
}
|
||||
}
|
||||
Object::Reference((number, 0)) => {
|
||||
if let Some(generated) = generated {
|
||||
let slot = &mut objects[*number as usize - 1];
|
||||
let mut shared = pdf_dictionary(slot)?;
|
||||
merge_pdf_entries(&mut shared, generated, diagnostics);
|
||||
*slot = encode_device_value(Object::Dictionary(shared))?;
|
||||
}
|
||||
new.clone()
|
||||
}
|
||||
_ => unreachable!("typed PDF resource category"),
|
||||
};
|
||||
resources.set(category.clone(), effective);
|
||||
}
|
||||
merge_output_resources(&mut resources, fields, references, objects, diagnostics)?;
|
||||
dictionary.set("Resources", Object::Dictionary(resources));
|
||||
objects[id - 1] = encode_device_value(Object::Dictionary(dictionary))?;
|
||||
}
|
||||
@@ -168,6 +139,46 @@ impl Navigation {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn merge_output_resources(
|
||||
resources: &mut PdfDictionary,
|
||||
fields: &Dictionary,
|
||||
references: &References<'_>,
|
||||
objects: &mut [Vec<u8>],
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> Result<(), String> {
|
||||
for (category, new) in &output_dictionary(fields, references)? {
|
||||
let generated = resources.remove(category);
|
||||
let generated = generated
|
||||
.as_ref()
|
||||
.map(Object::as_dict)
|
||||
.transpose()
|
||||
.map_err(|_| "cannot merge a non-dictionary generated resource category")?;
|
||||
let effective = match new {
|
||||
Object::Dictionary(fields) => {
|
||||
if let Some(generated) = generated {
|
||||
let mut combined = generated.clone();
|
||||
merge_pdf_entries(&mut combined, fields, diagnostics);
|
||||
Object::Dictionary(combined)
|
||||
} else {
|
||||
new.clone()
|
||||
}
|
||||
}
|
||||
Object::Reference((number, 0)) => {
|
||||
if let Some(generated) = generated {
|
||||
let slot = &mut objects[*number as usize - 1];
|
||||
let mut shared = pdf_dictionary(slot)?;
|
||||
merge_pdf_entries(&mut shared, generated, diagnostics);
|
||||
*slot = encode_device_value(Object::Dictionary(shared))?;
|
||||
}
|
||||
new.clone()
|
||||
}
|
||||
_ => unreachable!("typed PDF resource category"),
|
||||
};
|
||||
resources.set(category.clone(), effective);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn category_fields<'a>(
|
||||
objects: &'a BTreeMap<Vec<u8>, NamedObject>,
|
||||
name: &[u8],
|
||||
|
||||
Reference in new issue
Block a user