Share pdfTeX image and page object numbers
This commit is contained in:
1 parent
57a7097857
commit
d12c4b034b
11 files changed
+320
-61
No files matched your search
@@ -28,6 +28,8 @@ pub struct ShipoutSpecial {
|
|||||||
pub struct NativeShipout {
|
pub struct NativeShipout {
|
||||||
pub box_node: NativeBox,
|
pub box_node: NativeBox,
|
||||||
pub device: ShipoutDevice,
|
pub device: ShipoutDevice,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub(super) pdf_objects: Option<crate::pdf_device::page_resources::PageObjects>,
|
||||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
pub(super) font_overrides: BTreeMap<FontId, Arc<crate::native_font::NativeFont>>,
|
pub(super) font_overrides: BTreeMap<FontId, Arc<crate::native_font::NativeFont>>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
@@ -84,6 +86,7 @@ impl NativeShipout {
|
|||||||
pdf_background: self.pdf_background.clone(),
|
pdf_background: self.pdf_background.clone(),
|
||||||
pdf_text_spaces: self.pdf_text_spaces.clone(),
|
pdf_text_spaces: self.pdf_text_spaces.clone(),
|
||||||
pdf_resources: crate::pdf_device::page_resources::PageResources {
|
pdf_resources: crate::pdf_device::page_resources::PageResources {
|
||||||
|
objects: self.pdf_objects,
|
||||||
entries: self.pdf_resource_entries.clone(),
|
entries: self.pdf_resource_entries.clone(),
|
||||||
attributes: self.pdf_page_attributes.clone(),
|
attributes: self.pdf_page_attributes.clone(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
|
|||||||
@@ -380,9 +380,19 @@ impl Executor {
|
|||||||
} else {
|
} else {
|
||||||
Default::default()
|
Default::default()
|
||||||
};
|
};
|
||||||
|
let pdf_objects = if !for_form && !unicode_pages && device.pdf.is_some() {
|
||||||
|
self.reads.insert(Dependency::PdfObjects);
|
||||||
|
let page_number = self.shipped_pages as u32 + 1;
|
||||||
|
let limit = self.limits.tokens;
|
||||||
|
Some(self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||||
|
.begin_page(page_number, limit).map_err(|message| self.error(message, current))?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let mut shipout = NativeShipout {
|
let mut shipout = NativeShipout {
|
||||||
box_node: b,
|
box_node: b,
|
||||||
device,
|
device,
|
||||||
|
pdf_objects,
|
||||||
font_overrides,
|
font_overrides,
|
||||||
virtual_glyphs: None,
|
virtual_glyphs: None,
|
||||||
pdf_font_bindings: self.pdf_virtual_fonts.captured_font_bindings(),
|
pdf_font_bindings: self.pdf_virtual_fonts.captured_font_bindings(),
|
||||||
@@ -689,6 +699,12 @@ impl Executor {
|
|||||||
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
||||||
shipout.pdf_links = links;
|
shipout.pdf_links = links;
|
||||||
}
|
}
|
||||||
|
if let Some(objects) = &mut shipout.pdf_objects {
|
||||||
|
let limit = self.limits.tokens;
|
||||||
|
objects.parent = self.state.pdf_objects.as_deref_mut().expect("allocated PDF page")
|
||||||
|
.finish_page(self.shipped_pages as u32 + 1, limit)
|
||||||
|
.map_err(|message| self.error(message, current))?;
|
||||||
|
}
|
||||||
if reopened_images {
|
if reopened_images {
|
||||||
self.rebind_shipped_format_images(&mut shipout.box_node)?;
|
self.rebind_shipped_format_images(&mut shipout.box_node)?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ impl Executor {
|
|||||||
images: Vec<Arc<PdfImageUse>>,
|
images: Vec<Arc<PdfImageUse>>,
|
||||||
warnings: Vec<String>,
|
warnings: Vec<String>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
if let Some(last) = images.iter().rfind(|image| image.xdv.is_none() && image.pdf_object_number.is_none()) {
|
||||||
|
self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||||
|
.retain_legacy_image_numbers(last.id);
|
||||||
|
}
|
||||||
self.restored_pdf_image_count = images.len();
|
self.restored_pdf_image_count = images.len();
|
||||||
self.pdf_images = definitions.iter().zip(images).map(|(saved, image)| {
|
self.pdf_images = definitions.iter().zip(images).map(|(saved, image)| {
|
||||||
RegisteredImage {
|
RegisteredImage {
|
||||||
@@ -39,9 +43,6 @@ impl Executor {
|
|||||||
if image.saved.is_none() {
|
if image.saved.is_none() {
|
||||||
return self.fail("cannot dump a format with an unrecorded image object");
|
return self.fail("cannot dump a format with an unrecorded image object");
|
||||||
}
|
}
|
||||||
if image.image.image.color_space.is_some() {
|
|
||||||
return self.fail("cannot dump a format with image color-space object references");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -71,7 +72,8 @@ impl Executor {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
match (command, self.pdf_images.last()) {
|
match (command, self.pdf_images.last()) {
|
||||||
(Primitive::Pdflastximage, Some(image)) => image.image.id as i32,
|
(Primitive::Pdflastximage, Some(image)) => image.image.pdf_object_number
|
||||||
|
.map_or(image.image.id as i32, |number| number as i32),
|
||||||
(Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32,
|
(Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32,
|
||||||
(Primitive::Pdflastximagecolordepth, Some(image)) => image
|
(Primitive::Pdflastximagecolordepth, Some(image)) => image
|
||||||
.image
|
.image
|
||||||
@@ -224,9 +226,14 @@ impl Executor {
|
|||||||
PdfImage::read(source, doc, page, page_box, remap_type1)
|
PdfImage::read(source, doc, page, page_box, remap_type1)
|
||||||
.map_err(|error| self.error(error, token.span))?
|
.map_err(|error| self.error(error, token.span))?
|
||||||
};
|
};
|
||||||
let image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions)
|
let mut image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions)
|
||||||
.map_err(|error| self.error(error, token.span))?;
|
.map_err(|error| self.error(error, token.span))?;
|
||||||
let id = image.id;
|
let id = image.id;
|
||||||
|
if pdftex {
|
||||||
|
self.reads.insert(Dependency::PdfObjects);
|
||||||
|
image.pdf_object_number = Some(self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||||
|
.reserve_image(id, self.limits.tokens).map_err(|error| self.error(error, token.span))?);
|
||||||
|
}
|
||||||
let saved = (pdftex && self.state.is_initex())
|
let saved = (pdftex && self.state.is_initex())
|
||||||
.then(|| FormatPdfImage::capture(&image, &attributes, format_kind));
|
.then(|| FormatPdfImage::capture(&image, &attributes, format_kind));
|
||||||
self.pdf_images.push(RegisteredImage {
|
self.pdf_images.push(RegisteredImage {
|
||||||
@@ -591,10 +598,21 @@ impl Executor {
|
|||||||
self.check_pdf_image()?;
|
self.check_pdf_image()?;
|
||||||
let id = self.integer(files)?;
|
let id = self.integer(files)?;
|
||||||
self.reads.insert(Dependency::PdfImages);
|
self.reads.insert(Dependency::PdfImages);
|
||||||
let image = usize::try_from(id)
|
let slot = if self.state.input_profile() == InputProfile::TeX8Bit {
|
||||||
.ok()
|
self.reads.insert(Dependency::PdfObjects);
|
||||||
.and_then(|id| id.checked_sub(1))
|
u32::try_from(id).ok()
|
||||||
.and_then(|index| self.pdf_images.get(index))
|
.and_then(|number| self.state.pdf_objects.as_deref()?.image_slot(number))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let image = slot.or_else(|| {
|
||||||
|
// Existing format images keep the positional numbers embedded in their macros.
|
||||||
|
let id = usize::try_from(id).ok()?;
|
||||||
|
self.pdf_images.get(id.checked_sub(1)?)
|
||||||
|
.filter(|registered| registered.image.pdf_object_number.is_none())
|
||||||
|
.map(|_| id)
|
||||||
|
})
|
||||||
|
.and_then(|id| self.pdf_images.get(id - 1))
|
||||||
.map(|registered| registered.image.clone())
|
.map(|registered| registered.image.clone())
|
||||||
.ok_or_else(|| self.error(format!("cannot find referenced object {id}"), token.span))?;
|
.ok_or_else(|| self.error(format!("cannot find referenced object {id}"), token.span))?;
|
||||||
self.defer_image(image, token)
|
self.defer_image(image, token)
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ use std::{
|
|||||||
sync::{Arc, Mutex, OnceLock, Weak},
|
sync::{Arc, Mutex, OnceLock, Weak},
|
||||||
};
|
};
|
||||||
|
|
||||||
const SCHEMA: u32 = 86;
|
const SCHEMA: u32 = 87;
|
||||||
const COMPATIBLE_SCHEMAS: [u32; 53] = [
|
const COMPATIBLE_SCHEMAS: [u32; 54] = [
|
||||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, SCHEMA,
|
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, SCHEMA,
|
||||||
];
|
];
|
||||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||||
|
|
||||||
@@ -191,6 +191,8 @@ impl FormatImage {
|
|||||||
Parameter::Pdfoptionalwaysusepdfpagebox,
|
Parameter::Pdfoptionalwaysusepdfpagebox,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
let pdf_objects = image.state.pdf_objects.as_deref();
|
||||||
|
let mut numbered_images = 0;
|
||||||
for (index, saved) in image.pdf_images.iter().enumerate() {
|
for (index, saved) in image.pdf_images.iter().enumerate() {
|
||||||
let valid_profile = if saved.kind.reads_at_load() {
|
let valid_profile = if saved.kind.reads_at_load() {
|
||||||
image.schema >= 83 && image.state.input_profile() == InputProfile::TeX8Bit
|
image.schema >= 83 && image.state.input_profile() == InputProfile::TeX8Bit
|
||||||
@@ -199,14 +201,24 @@ impl FormatImage {
|
|||||||
image.schema >= 84 && image.state.input_profile() == InputProfile::XeTeX
|
image.schema >= 84 && image.state.input_profile() == InputProfile::XeTeX
|
||||||
&& saved.image.xdv.is_some()
|
&& saved.image.xdv.is_some()
|
||||||
};
|
};
|
||||||
|
let valid_number = if let Some(number) = saved.image.pdf_object_number {
|
||||||
|
numbered_images += 1;
|
||||||
|
image.schema >= 87 && saved.kind.reads_at_load()
|
||||||
|
&& pdf_objects.and_then(|objects| objects.image_slot(number)) == Some(index + 1)
|
||||||
|
} else {
|
||||||
|
saved.image.image.color_space.is_none()
|
||||||
|
};
|
||||||
if !valid_profile
|
if !valid_profile
|
||||||
|
|| !valid_number
|
||||||
|| saved.image.id != index + 1
|
|| saved.image.id != index + 1
|
||||||
|| saved.image.image.color_space.is_some()
|
|
||||||
|| saved.path().as_os_str().is_empty()
|
|| saved.path().as_os_str().is_empty()
|
||||||
{
|
{
|
||||||
return Err("invalid native format image registry".into());
|
return Err("invalid native format image registry".into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if numbered_images != pdf_objects.map_or(0, |objects| objects.image_count()) {
|
||||||
|
return Err("invalid native format PDF image numbers".into());
|
||||||
|
}
|
||||||
if (!image.state.pdf_forms.is_empty()
|
if (!image.state.pdf_forms.is_empty()
|
||||||
&& (image.schema < 86 || image.state.input_profile() != InputProfile::TeX8Bit))
|
&& (image.schema < 86 || image.state.input_profile() != InputProfile::TeX8Bit))
|
||||||
|| !image.state.validate_format_pdf_forms()
|
|| !image.state.validate_format_pdf_forms()
|
||||||
|
|||||||
@@ -794,6 +794,7 @@ impl Execution {
|
|||||||
page.pdf_resources = PageResources::from_page(
|
page.pdf_resources = PageResources::from_page(
|
||||||
page.pdf_resources.entries.clone(),
|
page.pdf_resources.entries.clone(),
|
||||||
page.pdf_resources.attributes.clone(),
|
page.pdf_resources.attributes.clone(),
|
||||||
|
page.pdf_resources.objects,
|
||||||
&states,
|
&states,
|
||||||
objects,
|
objects,
|
||||||
).map_err(|message| Error::at(
|
).map_err(|message| Error::at(
|
||||||
|
|||||||
@@ -2080,6 +2080,54 @@ fn write_pdf_outlines(
|
|||||||
root_id
|
root_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn pdf_pages_dictionary(kids: &[usize], pages: usize, parent: Option<usize>) -> Vec<u8> {
|
||||||
|
let refs = kids.iter().map(|kid| format!("{kid} 0 R")).collect::<Vec<_>>().join(" ");
|
||||||
|
let mut node = format!("<< /Type /Pages /Kids [{refs}] /Count {pages}").into_bytes();
|
||||||
|
if let Some(parent) = parent {
|
||||||
|
write!(&mut node, " /Parent {parent} 0 R >>").unwrap();
|
||||||
|
}
|
||||||
|
node
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_pdf_page_tree(
|
||||||
|
objects: &mut Vec<Vec<u8>>,
|
||||||
|
pages: &[usize],
|
||||||
|
groups: BTreeMap<usize, Vec<usize>>,
|
||||||
|
) -> Vec<usize> {
|
||||||
|
struct Node {
|
||||||
|
id: usize,
|
||||||
|
pages: usize,
|
||||||
|
kids: Vec<usize>,
|
||||||
|
}
|
||||||
|
let fanout = crate::pdf_device::page_resources::PAGE_TREE_FANOUT as usize;
|
||||||
|
let grouped: BTreeSet<_> = groups.values().flatten().copied().collect();
|
||||||
|
let mut level: Vec<_> = groups.into_iter().map(|(id, kids)| Node {
|
||||||
|
id, pages: kids.len(), kids,
|
||||||
|
}).collect();
|
||||||
|
while level.len() > fanout {
|
||||||
|
let mut upper = Vec::with_capacity(level.len().div_ceil(fanout));
|
||||||
|
for children in level.chunks(fanout) {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
let parent = objects.len();
|
||||||
|
for node in children {
|
||||||
|
objects[node.id - 1] = pdf_pages_dictionary(&node.kids, node.pages, Some(parent));
|
||||||
|
}
|
||||||
|
upper.push(Node {
|
||||||
|
id: parent,
|
||||||
|
pages: children.iter().map(|node| node.pages).sum(),
|
||||||
|
kids: children.iter().map(|node| node.id).collect(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
level = upper;
|
||||||
|
}
|
||||||
|
for node in &level {
|
||||||
|
objects[node.id - 1] = pdf_pages_dictionary(&node.kids, node.pages, Some(2));
|
||||||
|
}
|
||||||
|
level.into_iter().map(|node| node.id)
|
||||||
|
.chain(pages.iter().copied().filter(|id| !grouped.contains(id)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
fn write_pdf(
|
fn write_pdf(
|
||||||
pages: &[DisplayList],
|
pages: &[DisplayList],
|
||||||
page_width: i64,
|
page_width: i64,
|
||||||
@@ -2182,7 +2230,7 @@ fn write_pdf(
|
|||||||
// retains its measured source image and can precede that registration.
|
// retains its measured source image and can precede that registration.
|
||||||
let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| {
|
let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| {
|
||||||
if let DisplayItem::PdfImageObject(object) = item {
|
if let DisplayItem::PdfImageObject(object) = item {
|
||||||
Some((object.image.id, object.image.image.as_ref(), object.attributes.as_slice(), object.compression))
|
Some((object.image.as_ref(), object.attributes.as_slice(), object.compression))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -2191,7 +2239,7 @@ fn write_pdf(
|
|||||||
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
|
||||||
list.items.iter().filter_map(move |item| {
|
list.items.iter().filter_map(move |item| {
|
||||||
if let DisplayItem::PdfImage { image, .. } = item {
|
if let DisplayItem::PdfImage { image, .. } = item {
|
||||||
Some((image.id, image.image.as_ref(), &[][..], compression))
|
Some((image.as_ref(), &[][..], compression))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -2199,15 +2247,15 @@ fn write_pdf(
|
|||||||
});
|
});
|
||||||
let mut image_ids = HashSet::new();
|
let mut image_ids = HashSet::new();
|
||||||
let images: Vec<_> = declarations.chain(placements)
|
let images: Vec<_> = declarations.chain(placements)
|
||||||
.filter(|(id, ..)| image_ids.insert(*id))
|
.filter(|(image, ..)| image_ids.insert(image.id))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let compression = final_compression.unwrap_or(0).clamp(0, 9) as u8;
|
let compression = final_compression.unwrap_or(0).clamp(0, 9) as u8;
|
||||||
let mut type1_plans = type1_fonts::FontPlans::default();
|
let mut type1_plans = type1_fonts::FontPlans::default();
|
||||||
// pdfTeX collects included font descriptors as it writes forms. The
|
// pdfTeX collects included font descriptors as it writes forms. The
|
||||||
// TeX font dictionaries and their glyph marks are finalized afterward.
|
// TeX font dictionaries and their glyph marks are finalized afterward.
|
||||||
for (_, image, _, _) in &images {
|
for (image, _, _) in &images {
|
||||||
for font in image.mapped_type1_fonts() {
|
for font in image.image.mapped_type1_fonts() {
|
||||||
type1_plans.include(font);
|
type1_plans.include(font);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2422,6 +2470,29 @@ fn write_pdf(
|
|||||||
device_objects.insert(number, objects.len() as u32);
|
device_objects.insert(number, objects.len() as u32);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for number in images.iter().filter_map(|(image, ..)| image.pdf_object_number) {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
device_objects.insert(number, objects.len() as u32);
|
||||||
|
}
|
||||||
|
let parents: BTreeSet<_> = pages.iter().filter_map(|page| {
|
||||||
|
page.pdf_resources.objects.map(|allocation| allocation.parent)
|
||||||
|
}).collect();
|
||||||
|
let grouped_pages = parents.len() > 1;
|
||||||
|
for number in parents {
|
||||||
|
let id = if grouped_pages {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
objects.len() as u32
|
||||||
|
} else {
|
||||||
|
2
|
||||||
|
};
|
||||||
|
device_objects.insert(number, id);
|
||||||
|
}
|
||||||
|
for allocation in pages.iter().filter_map(|page| page.pdf_resources.objects) {
|
||||||
|
for number in [allocation.resources, allocation.contents] {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
device_objects.insert(number, objects.len() as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
let remapped = resources
|
let remapped = resources
|
||||||
.map(|resources| resources.append(&mut objects, diagnostics, device_objects.clone()))
|
.map(|resources| resources.append(&mut objects, diagnostics, device_objects.clone()))
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
@@ -2437,6 +2508,7 @@ fn write_pdf(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut kids = Vec::new();
|
let mut kids = Vec::new();
|
||||||
|
let mut page_groups = BTreeMap::<usize, Vec<usize>>::new();
|
||||||
let mut navigation = PdfNavigation::default();
|
let mut navigation = PdfNavigation::default();
|
||||||
let mut annotation_actions = Vec::new();
|
let mut annotation_actions = Vec::new();
|
||||||
let mut xdv_annotations = Vec::new();
|
let mut xdv_annotations = Vec::new();
|
||||||
@@ -2445,8 +2517,9 @@ fn write_pdf(
|
|||||||
.and_then(|page| page.pdf.as_ref())
|
.and_then(|page| page.pdf.as_ref())
|
||||||
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
|
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
|
||||||
let mut unwritten_color_spaces = BTreeMap::new();
|
let mut unwritten_color_spaces = BTreeMap::new();
|
||||||
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(id, image, attributes, compression)| {
|
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression)| {
|
||||||
let color_space = image.color_space.map(|number| {
|
let target = image.pdf_object_number.map(|number| device_objects[&number] as usize);
|
||||||
|
let color_space = image.image.color_space.map(|number| {
|
||||||
let Ok(reference) = u32::try_from(number) else {
|
let Ok(reference) = u32::try_from(number) else {
|
||||||
return i64::from(number);
|
return i64::from(number);
|
||||||
};
|
};
|
||||||
@@ -2460,10 +2533,10 @@ fn write_pdf(
|
|||||||
objects.len() as i64
|
objects.len() as i64
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
let object = image.append_to(
|
let object = image.image.append_to(
|
||||||
&mut objects, attributes, compression, pdf_version, &type1_references, color_space,
|
&mut objects, attributes, compression, pdf_version, &type1_references, color_space, target,
|
||||||
);
|
);
|
||||||
(id, object)
|
(image.id, object)
|
||||||
}).collect();
|
}).collect();
|
||||||
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
|
||||||
@@ -2607,9 +2680,13 @@ fn write_pdf(
|
|||||||
let reserved_page = remapped.as_ref()
|
let reserved_page = remapped.as_ref()
|
||||||
.and_then(|resources| resources.page_objects.get(&page_index))
|
.and_then(|resources| resources.page_objects.get(&page_index))
|
||||||
.copied();
|
.copied();
|
||||||
|
let allocation = list.pdf_resources.objects;
|
||||||
|
let content_slot = allocation.map(|page| device_objects[&page.contents] as usize);
|
||||||
|
let parent = allocation.map_or(2, |page| device_objects[&page.parent] as usize);
|
||||||
let page_id = reserved_page.unwrap_or(objects.len() + 1);
|
let page_id = reserved_page.unwrap_or(objects.len() + 1);
|
||||||
let content_id = objects.len() + 1 + usize::from(reserved_page.is_none());
|
let next_object = objects.len() + 1 + usize::from(reserved_page.is_none());
|
||||||
let image_base = content_id + 1;
|
let content_id = content_slot.unwrap_or(next_object);
|
||||||
|
let image_base = next_object + usize::from(content_slot.is_none());
|
||||||
let mut xobjects = used
|
let mut xobjects = used
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
|
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
|
||||||
@@ -2663,33 +2740,42 @@ fn write_pdf(
|
|||||||
format!(" /Annots [{annotation_refs}]")
|
format!(" /Annots [{annotation_refs}]")
|
||||||
};
|
};
|
||||||
navigation.pages.push(page_id);
|
navigation.pages.push(page_id);
|
||||||
kids.push(format!("{page_id} 0 R"));
|
kids.push(page_id);
|
||||||
|
if parent != 2 {
|
||||||
|
page_groups.entry(parent).or_default().push(page_id);
|
||||||
|
}
|
||||||
let decorated = !list.pdf_resources.attributes.is_empty();
|
let decorated = !list.pdf_resources.attributes.is_empty();
|
||||||
let mut page = b"<< /Type /Page".to_vec();
|
let mut page = b"<< /Type /Page".to_vec();
|
||||||
if !decorated {
|
if !decorated {
|
||||||
page.extend_from_slice(b" /Parent 2 0 R");
|
write!(&mut page, " /Parent {parent} 0 R").unwrap();
|
||||||
}
|
}
|
||||||
if !crate::pdf_device::page_attributes::supplies_media_box(&list.pdf_resources.attributes) {
|
if !crate::pdf_device::page_attributes::supplies_media_box(&list.pdf_resources.attributes) {
|
||||||
page.extend_from_slice(format!(" /MediaBox [0 0 {} {}]", physical(width), physical(height)).as_bytes());
|
page.extend_from_slice(format!(" /MediaBox [0 0 {} {}]", physical(width), physical(height)).as_bytes());
|
||||||
}
|
}
|
||||||
page.extend_from_slice(b" /Resources ");
|
let mut resources = resources.into_bytes();
|
||||||
let additional = remapped.as_ref().map(|resources| resources.pages[page_index].as_slice())
|
let additional = remapped.as_ref().map(|resources| resources.pages[page_index].as_slice())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let writes_procset = list.pdf.as_ref().is_some_and(|pdf| pdf.writes_procset());
|
let writes_procset = list.pdf.as_ref().is_some_and(|pdf| pdf.writes_procset());
|
||||||
if !additional.is_empty() || writes_procset {
|
if !additional.is_empty() || writes_procset {
|
||||||
page.extend_from_slice(&resources.as_bytes()[..resources.len() - 2]);
|
resources.truncate(resources.len() - 2);
|
||||||
page.extend_from_slice(additional);
|
resources.extend_from_slice(additional);
|
||||||
if writes_procset {
|
if writes_procset {
|
||||||
append_page_procset(&mut page, list, !used.is_empty());
|
append_page_procset(&mut resources, list, !used.is_empty());
|
||||||
}
|
}
|
||||||
page.extend_from_slice(b" >>");
|
resources.extend_from_slice(b" >>");
|
||||||
|
}
|
||||||
|
page.extend_from_slice(b" /Resources ");
|
||||||
|
if let Some(allocation) = allocation {
|
||||||
|
let id = device_objects[&allocation.resources];
|
||||||
|
objects[id as usize - 1] = resources;
|
||||||
|
write!(&mut page, "{id} 0 R").unwrap();
|
||||||
} else {
|
} else {
|
||||||
page.extend_from_slice(resources.as_bytes());
|
page.extend_from_slice(&resources);
|
||||||
}
|
}
|
||||||
if decorated {
|
if decorated {
|
||||||
page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes());
|
page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes());
|
||||||
page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]);
|
page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]);
|
||||||
page.extend_from_slice(format!(" /Parent 2 0 R{annots}{png_group_ref} >>").as_bytes());
|
page.extend_from_slice(format!(" /Parent {parent} 0 R{annots}{png_group_ref} >>").as_bytes());
|
||||||
} else {
|
} else {
|
||||||
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes());
|
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes());
|
||||||
}
|
}
|
||||||
@@ -2718,11 +2804,12 @@ fn write_pdf(
|
|||||||
&opentype,
|
&opentype,
|
||||||
font_opacities,
|
font_opacities,
|
||||||
);
|
);
|
||||||
objects.push(objects::stream(
|
let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression));
|
||||||
"",
|
if let Some(id) = content_slot {
|
||||||
&content,
|
objects[id - 1] = stream;
|
||||||
list.pdf.as_ref().map_or(0, |p| p.stream_compression),
|
} else {
|
||||||
));
|
objects.push(stream);
|
||||||
|
}
|
||||||
|
|
||||||
for (index, _) in &used {
|
for (index, _) in &used {
|
||||||
let image = &list.images[*index];
|
let image = &list.images[*index];
|
||||||
@@ -2854,12 +2941,12 @@ fn write_pdf(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
objects[1] = format!(
|
let root_children = if page_groups.is_empty() {
|
||||||
"<< /Type /Pages /Kids [{}] /Count {}",
|
kids
|
||||||
kids.join(" "),
|
} else {
|
||||||
pages.len()
|
write_pdf_page_tree(&mut objects, &kids, page_groups)
|
||||||
)
|
};
|
||||||
.into_bytes();
|
objects[1] = pdf_pages_dictionary(&root_children, pages.len(), None);
|
||||||
if let Some(resources) = &remapped && !resources.page_tree_attributes.is_empty() {
|
if let Some(resources) = &remapped && !resources.page_tree_attributes.is_empty() {
|
||||||
objects[1].push(b' ');
|
objects[1].push(b' ');
|
||||||
objects[1].extend_from_slice(&resources.page_tree_attributes);
|
objects[1].extend_from_slice(&resources.page_tree_attributes);
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ pub(crate) enum ObjectBody {
|
|||||||
FormatLink,
|
FormatLink,
|
||||||
Form,
|
Form,
|
||||||
FormResources,
|
FormResources,
|
||||||
|
Image(usize),
|
||||||
|
PageResources,
|
||||||
|
PageContents,
|
||||||
|
Pages,
|
||||||
DiscardedAtDump,
|
DiscardedAtDump,
|
||||||
Direct(Vec<u8>),
|
Direct(Vec<u8>),
|
||||||
Stream {
|
Stream {
|
||||||
@@ -34,7 +38,8 @@ impl ObjectBody {
|
|||||||
fn len(&self) -> usize {
|
fn len(&self) -> usize {
|
||||||
match self {
|
match self {
|
||||||
Self::Page | Self::Link | Self::FormatLink | Self::Form
|
Self::Page | Self::Link | Self::FormatLink | Self::Form
|
||||||
| Self::FormResources | Self::DiscardedAtDump => 0,
|
| Self::FormResources | Self::Image(_) | Self::PageResources | Self::PageContents
|
||||||
|
| Self::Pages | Self::DiscardedAtDump => 0,
|
||||||
Self::Direct(bytes) => bytes.len(),
|
Self::Direct(bytes) => bytes.len(),
|
||||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||||
Self::File {
|
Self::File {
|
||||||
@@ -51,7 +56,8 @@ impl ObjectBody {
|
|||||||
|
|
||||||
fn parse(&self) -> Result<Object, String> {
|
fn parse(&self) -> Result<Object, String> {
|
||||||
match self {
|
match self {
|
||||||
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources => {
|
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
|
||||||
|
| Self::Image(_) | Self::PageResources | Self::PageContents | Self::Pages => {
|
||||||
Err("expected a generic native PDF object".into())
|
Err("expected a generic native PDF object".into())
|
||||||
}
|
}
|
||||||
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
|
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
|
||||||
@@ -69,6 +75,15 @@ impl ObjectBody {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub(crate) struct PageObjects {
|
||||||
|
pub resources: u32,
|
||||||
|
pub contents: u32,
|
||||||
|
pub parent: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const PAGE_TREE_FANOUT: u32 = 6;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
pub struct PdfObjects {
|
pub struct PdfObjects {
|
||||||
values: Vec<Option<Arc<ObjectBody>>>,
|
values: Vec<Option<Arc<ObjectBody>>>,
|
||||||
@@ -79,6 +94,8 @@ pub struct PdfObjects {
|
|||||||
bytes: usize,
|
bytes: usize,
|
||||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
page_references: BTreeMap<u32, u32>,
|
page_references: BTreeMap<u32, u32>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
page_parent: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PdfObjects {
|
impl PdfObjects {
|
||||||
@@ -125,6 +142,42 @@ impl PdfObjects {
|
|||||||
self.allocate(Some(Arc::new(ObjectBody::FormResources)), limit)
|
self.allocate(Some(Arc::new(ObjectBody::FormResources)), limit)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn reserve_image(&mut self, image: usize, limit: usize) -> Result<u32, String> {
|
||||||
|
self.allocate(Some(Arc::new(ObjectBody::Image(image))), limit)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn image_slot(&self, number: u32) -> Option<usize> {
|
||||||
|
match self.entry(number)?.as_deref()? {
|
||||||
|
ObjectBody::Image(slot) => Some(*slot),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn image_count(&self) -> usize {
|
||||||
|
self.values.iter().filter(|entry| matches!(entry.as_deref(), Some(ObjectBody::Image(_)))).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn retain_legacy_image_numbers(&mut self, slots: usize) {
|
||||||
|
if slots > self.values.len() {
|
||||||
|
let reserved = Arc::new(ObjectBody::DiscardedAtDump);
|
||||||
|
self.values.resize(slots, Some(reserved));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn begin_page(&mut self, page: u32, limit: usize) -> Result<PageObjects, String> {
|
||||||
|
let resources = self.allocate(Some(Arc::new(ObjectBody::PageResources)), limit)?;
|
||||||
|
self.page_reference(page, limit)?;
|
||||||
|
let contents = self.allocate(Some(Arc::new(ObjectBody::PageContents)), limit)?;
|
||||||
|
Ok(PageObjects { resources, contents, parent: 0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn finish_page(&mut self, page: u32, limit: usize) -> Result<u32, String> {
|
||||||
|
if (page - 1) % PAGE_TREE_FANOUT == 0 {
|
||||||
|
self.page_parent = Some(self.allocate(Some(Arc::new(ObjectBody::Pages)), limit)?);
|
||||||
|
}
|
||||||
|
self.page_parent.ok_or_else(|| "missing native PDF page parent".into())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn form_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
pub(crate) fn form_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
||||||
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
||||||
matches!(entry.as_deref(), Some(ObjectBody::Form)).then_some(index as u32 + 1)
|
matches!(entry.as_deref(), Some(ObjectBody::Form)).then_some(index as u32 + 1)
|
||||||
@@ -149,7 +202,8 @@ impl PdfObjects {
|
|||||||
let replacement = match entry.as_deref() {
|
let replacement = match entry.as_deref() {
|
||||||
// A restored link whatsit gets its own annotation object when shipped.
|
// A restored link whatsit gets its own annotation object when shipped.
|
||||||
Some(ObjectBody::Link) => ObjectBody::FormatLink,
|
Some(ObjectBody::Link) => ObjectBody::FormatLink,
|
||||||
Some(ObjectBody::Page | ObjectBody::FormResources) => ObjectBody::DiscardedAtDump,
|
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
|
||||||
|
| ObjectBody::PageContents | ObjectBody::Pages) => ObjectBody::DiscardedAtDump,
|
||||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||||
_ => continue,
|
_ => continue,
|
||||||
};
|
};
|
||||||
@@ -159,6 +213,7 @@ impl PdfObjects {
|
|||||||
self.last_link = None;
|
self.last_link = None;
|
||||||
self.bytes = self.values.iter().flatten().map(|body| body.len()).sum();
|
self.bytes = self.values.iter().flatten().map(|body| body.len()).sum();
|
||||||
self.page_references.clear();
|
self.page_references.clear();
|
||||||
|
self.page_parent = None;
|
||||||
!self.values.is_empty()
|
!self.values.is_empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,6 +397,7 @@ pub(super) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
|||||||
/// Referenced names affect SVG painting only when they are used by the page.
|
/// Referenced names affect SVG painting only when they are used by the page.
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct PageResources {
|
pub struct PageResources {
|
||||||
|
pub(crate) objects: Option<PageObjects>,
|
||||||
pub(crate) entries: Arc<[u8]>,
|
pub(crate) entries: Arc<[u8]>,
|
||||||
pub(crate) attributes: Arc<[u8]>,
|
pub(crate) attributes: Arc<[u8]>,
|
||||||
pub(crate) viewport: Option<super::page_attributes::Viewport>,
|
pub(crate) viewport: Option<super::page_attributes::Viewport>,
|
||||||
@@ -397,11 +453,13 @@ impl PageResources {
|
|||||||
pub(crate) fn from_page(
|
pub(crate) fn from_page(
|
||||||
bytes: Arc<[u8]>,
|
bytes: Arc<[u8]>,
|
||||||
attributes: Arc<[u8]>,
|
attributes: Arc<[u8]>,
|
||||||
|
allocation: Option<PageObjects>,
|
||||||
names: &BTreeSet<Vec<u8>>,
|
names: &BTreeSet<Vec<u8>>,
|
||||||
objects: &PdfObjects,
|
objects: &PdfObjects,
|
||||||
) -> Result<Self, String> {
|
) -> Result<Self, String> {
|
||||||
if names.is_empty() {
|
if names.is_empty() {
|
||||||
return Ok(Self {
|
return Ok(Self {
|
||||||
|
objects: allocation,
|
||||||
entries: bytes,
|
entries: bytes,
|
||||||
attributes,
|
attributes,
|
||||||
..Self::default()
|
..Self::default()
|
||||||
@@ -413,6 +471,7 @@ impl PageResources {
|
|||||||
.map_err(|_| "PDF graphics state used without an ExtGState resource")?;
|
.map_err(|_| "PDF graphics state used without an ExtGState resource")?;
|
||||||
let definitions = resolve_dictionary(definitions.clone(), objects)?;
|
let definitions = resolve_dictionary(definitions.clone(), objects)?;
|
||||||
let mut resources = Self {
|
let mut resources = Self {
|
||||||
|
objects: allocation,
|
||||||
entries: bytes,
|
entries: bytes,
|
||||||
attributes,
|
attributes,
|
||||||
..Self::default()
|
..Self::default()
|
||||||
@@ -544,8 +603,17 @@ impl ResourceOutput {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect();
|
let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect();
|
||||||
let form_objects: BTreeSet<_> = pages.iter().flat_map(|page| {
|
let device_objects: BTreeSet<_> = pages.iter().flat_map(|page| {
|
||||||
|
use crate::render::DisplayItem;
|
||||||
page.forms.iter().flat_map(|form| [form.form.number, form.resource_number])
|
page.forms.iter().flat_map(|form| [form.form.number, form.resource_number])
|
||||||
|
.chain(page.pdf_resources.objects.into_iter().flat_map(|objects| {
|
||||||
|
[objects.resources, objects.contents, objects.parent]
|
||||||
|
}))
|
||||||
|
.chain(page.items.iter().filter_map(|item| match item {
|
||||||
|
DisplayItem::PdfImage { image, .. } => image.pdf_object_number,
|
||||||
|
DisplayItem::PdfImageObject(object) => object.image.pdf_object_number,
|
||||||
|
_ => None,
|
||||||
|
}))
|
||||||
}).collect();
|
}).collect();
|
||||||
let annotation_entries = pages
|
let annotation_entries = pages
|
||||||
.iter()
|
.iter()
|
||||||
@@ -600,7 +668,7 @@ impl ResourceOutput {
|
|||||||
link_references.entry(number).or_insert(None);
|
link_references.entry(number).or_insert(None);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if values.contains_key(&number) || page_objects.contains(&number) || form_objects.contains(&number) {
|
if values.contains_key(&number) || page_objects.contains(&number) || device_objects.contains(&number) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if objects.is_discarded_at_dump(number) {
|
if objects.is_discarded_at_dump(number) {
|
||||||
|
|||||||
@@ -59,6 +59,8 @@ pub struct PdfImage {
|
|||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct PdfImageUse {
|
pub struct PdfImageUse {
|
||||||
pub id: usize,
|
pub id: usize,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub(crate) pdf_object_number: Option<u32>,
|
||||||
pub image: Arc<PdfImage>,
|
pub image: Arc<PdfImage>,
|
||||||
pub width: i64,
|
pub width: i64,
|
||||||
pub height: i64,
|
pub height: i64,
|
||||||
@@ -136,6 +138,7 @@ impl PdfImageUse {
|
|||||||
}
|
}
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
id,
|
id,
|
||||||
|
pdf_object_number: None,
|
||||||
image: Arc::new(image),
|
image: Arc::new(image),
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
@@ -182,6 +185,7 @@ impl PdfImageUse {
|
|||||||
});
|
});
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
id,
|
id,
|
||||||
|
pdf_object_number: None,
|
||||||
image,
|
image,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
@@ -228,6 +232,7 @@ impl PdfImageUse {
|
|||||||
let matrix = matrix.0.map(|value| (value * 100_000.0).round() / 100_000.0);
|
let matrix = matrix.0.map(|value| (value * 100_000.0).round() / 100_000.0);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
id,
|
id,
|
||||||
|
pdf_object_number: None,
|
||||||
image,
|
image,
|
||||||
width: (right - left) as i64,
|
width: (right - left) as i64,
|
||||||
height: (top - bottom) as i64,
|
height: (top - bottom) as i64,
|
||||||
@@ -849,12 +854,16 @@ impl PdfImage {
|
|||||||
pdf_version: (i32, i32),
|
pdf_version: (i32, i32),
|
||||||
fonts: &crate::pdf::type1_fonts::References<'_>,
|
fonts: &crate::pdf::type1_fonts::References<'_>,
|
||||||
color_space: Option<i64>,
|
color_space: Option<i64>,
|
||||||
|
target: Option<usize>,
|
||||||
) -> usize {
|
) -> usize {
|
||||||
if let Some(samples) = self.sampled_image() {
|
if let Some(samples) = self.sampled_image() {
|
||||||
return samples.append(pdf, attributes, compression, pdf_version, color_space);
|
return samples.append(pdf, attributes, compression, pdf_version, color_space, target);
|
||||||
}
|
}
|
||||||
let base = pdf.len() + 1;
|
// A preallocated image slot owns the first object. Other imported objects
|
||||||
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
|
// still occupy a contiguous range, including references back to the image.
|
||||||
|
let base = pdf.len() + usize::from(target.is_none());
|
||||||
|
let root = target.unwrap_or(base);
|
||||||
|
for (index, parts) in self.objects.iter().enumerate() {
|
||||||
let mut body = Vec::new();
|
let mut body = Vec::new();
|
||||||
if index == 0 {
|
if index == 0 {
|
||||||
body.extend_from_slice(b"<< ");
|
body.extend_from_slice(b"<< ");
|
||||||
@@ -866,7 +875,10 @@ impl PdfImage {
|
|||||||
for part in parts {
|
for part in parts {
|
||||||
match part {
|
match part {
|
||||||
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
|
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
|
||||||
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
|
Part::Ref(id) => {
|
||||||
|
let object = if *id == 0 { root } else { base + id };
|
||||||
|
write!(body, "{object} 0 R").unwrap();
|
||||||
|
}
|
||||||
Part::ImageColorSpace => {
|
Part::ImageColorSpace => {
|
||||||
let id = color_space.expect("mapped image color space");
|
let id = color_space.expect("mapped image color space");
|
||||||
write!(body, "{id} 0 R").unwrap();
|
write!(body, "{id} 0 R").unwrap();
|
||||||
@@ -888,9 +900,13 @@ impl PdfImage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
body
|
if index == 0 && target.is_some() {
|
||||||
}));
|
pdf[root - 1] = body;
|
||||||
base
|
} else {
|
||||||
|
pdf.push(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -184,8 +184,9 @@ impl SampledImage {
|
|||||||
compression: u8,
|
compression: u8,
|
||||||
pdf_version: (i32, i32),
|
pdf_version: (i32, i32),
|
||||||
color_space: Option<i64>,
|
color_space: Option<i64>,
|
||||||
|
target: Option<usize>,
|
||||||
) -> usize {
|
) -> usize {
|
||||||
let id = pdf.len() + 1;
|
let id = target.unwrap_or(pdf.len() + 1);
|
||||||
let [width, height] = self.size;
|
let [width, height] = self.size;
|
||||||
let mut color = match (color_space, &self.color) {
|
let mut color = match (color_space, &self.color) {
|
||||||
(Some(id), _) => format!("{id} 0 R"),
|
(Some(id), _) => format!("{id} 0 R"),
|
||||||
@@ -202,7 +203,8 @@ impl SampledImage {
|
|||||||
};
|
};
|
||||||
let has_alpha = self.has_alpha(pdf_version);
|
let has_alpha = self.has_alpha(pdf_version);
|
||||||
if has_alpha {
|
if has_alpha {
|
||||||
write!(color, " /SMask {} 0 R", id + 1).expect("writing to a string");
|
let mask = pdf.len() + 1 + usize::from(target.is_none());
|
||||||
|
write!(color, " /SMask {mask} 0 R").expect("writing to a string");
|
||||||
}
|
}
|
||||||
let strip_16 = pdf_version < (1, 5) && self.depth == 16;
|
let strip_16 = pdf_version < (1, 5) && self.depth == 16;
|
||||||
let reduced;
|
let reduced;
|
||||||
@@ -221,7 +223,11 @@ impl SampledImage {
|
|||||||
// Image attributes are TeX printer bytes and may be non-UTF-8.
|
// Image attributes are TeX printer bytes and may be non-UTF-8.
|
||||||
stream.splice(3..3, attributes.iter().copied().chain([b'\n']));
|
stream.splice(3..3, attributes.iter().copied().chain([b'\n']));
|
||||||
}
|
}
|
||||||
|
if target.is_some() {
|
||||||
|
pdf[id - 1] = stream;
|
||||||
|
} else {
|
||||||
pdf.push(stream);
|
pdf.push(stream);
|
||||||
|
}
|
||||||
if has_alpha {
|
if has_alpha {
|
||||||
pdf.push(objects::stream(
|
pdf.push(objects::stream(
|
||||||
&format!(
|
&format!(
|
||||||
|
|||||||
+22
-1
@@ -801,12 +801,33 @@ PDF 对象的引用进入同一重编号过程。边界框、矩阵和资源引
|
|||||||
后,安全复用该文件首次读取前的检查点,只更新第二页。PDF、SVG
|
后,安全复用该文件首次读取前的检查点,只更新第二页。PDF、SVG
|
||||||
和来源映射与独立全量一致,实际辅助文件内容一致。
|
和来源映射与独立全量一致,实际辅助文件内容一致。
|
||||||
|
|
||||||
下一入口为图片与其它 PDF 对象共用编号。冻结用例的原版打印
|
当时冻结了图片与其他 PDF 对象的编号差异。原版用例打印
|
||||||
1/2/3/4,当前原生打印 1/1/2/3。首次发页后新原始对象的编号
|
1/2/3/4,当前原生打印 1/1/2/3。首次发页后新原始对象的编号
|
||||||
分别为 9 和 5。保留两端实际 PDF 与日志,并用真实页面资源和
|
分别为 9 和 5。保留两端实际 PDF 与日志,并用真实页面资源和
|
||||||
内容流补齐剩余的分配时机。回执 target/p3-pdf-form-format/receipt.json
|
内容流补齐剩余的分配时机。回执 target/p3-pdf-form-format/receipt.json
|
||||||
的 SHA-256 为 9f58bf51a894b698a90640c65c8fd7a3a6877b244aaebe1c676f169b0d1fb423。
|
的 SHA-256 为 9f58bf51a894b698a90640c65c8fd7a3a6877b244aaebe1c676f169b0d1fb423。
|
||||||
|
|
||||||
|
### pdfTeX 图像与实际页面对象共享编号
|
||||||
|
|
||||||
|
TeX 可见的图像号由通用 PDF 对象表分配。真实页开始时分配
|
||||||
|
资源、页面和内容流,在写页字典时分配每组六页的 Pages 叶节点。
|
||||||
|
输出 PDF 使用实际资源字典、内容流和页树。通用对象中的引用映射
|
||||||
|
到这批输出对象,重复引用使用同一个物理对象。旧格式的图像号仍可
|
||||||
|
使用,schema87 保存新的对象身份和图像颜色空间引用。
|
||||||
|
[TeX Live 的页面输出和编号分配](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L19165-L19187)
|
||||||
|
|
||||||
|
原差异用例的四个对象和首次发页后的新编号现与 pdfTeX 一致。
|
||||||
|
38 页对照覆盖未来页号、每组六页的叶节点和多层页树。五组参考
|
||||||
|
作业共 43 页 144 DPI 灰度逐像素一致,错误类型引用有明确诊断。
|
||||||
|
真实 schema86 旧格式两页光栅保持一致。十六项图像、链接和 PDF
|
||||||
|
配置回归通过。图像编辑会话复用读取图像前的检查点,只更新实际
|
||||||
|
引用的第二页。PDF、SVG 和来源映射与独立全量一致。
|
||||||
|
|
||||||
|
下一入口是字体、透明 PNG 和压缩对象流在发页时的实际分配。
|
||||||
|
现有三个用例首次发页后读取的新对象编号与原版仍分别差 1、2 和 1。
|
||||||
|
源码、原版和原生出页见 target/p3-pdf-shared-numbers/next-device-objects。
|
||||||
|
回执 target/p3-pdf-shared-numbers/receipt.json 的 SHA-256 为 e77e730569d6643bf5155c93cf1bb1e64070823d05094e962623fb736d88894e。
|
||||||
|
|
||||||
### PDF 预览按实际页面资源复用
|
### PDF 预览按实际页面资源复用
|
||||||
|
|
||||||
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
|
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
|
||||||
|
|||||||
@@ -375,9 +375,13 @@ fn png_project_edit_updates_only_the_page_using_the_image() {
|
|||||||
\pdfoutput=1 \pdfminorversion=7 \pdfcompresslevel=0 \pdfobjcompresslevel=0
|
\pdfoutput=1 \pdfminorversion=7 \pdfcompresslevel=0 \pdfobjcompresslevel=0
|
||||||
\pdfpagewidth=120bp \pdfpageheight=120bp \pdfhorigin=4bp \pdfvorigin=4bp
|
\pdfpagewidth=120bp \pdfpageheight=120bp \pdfhorigin=4bp \pdfvorigin=4bp
|
||||||
\shipout\vbox{\hrule width12pt height20pt depth0pt}
|
\shipout\vbox{\hrule width12pt height20pt depth0pt}
|
||||||
|
\def\space{ }
|
||||||
";
|
";
|
||||||
let continuation = r"\pdfximage width36bp {figure.data}
|
let continuation = r"\pdfximage width36bp {figure.data}
|
||||||
\shipout\hbox{\pdfrefximage\pdflastximage}\end
|
\edef\imageobject{\the\pdflastximage}
|
||||||
|
\ifnum\imageobject=5\else\errorstopmode\errmessage{wrong image object number}\fi
|
||||||
|
\pdfobj{<< /OriginalImage \imageobject\space 0 R >>}
|
||||||
|
\shipout\hbox{\pdfrefobj\pdflastobj\pdfrefximage\imageobject}\end
|
||||||
";
|
";
|
||||||
let complete_line = format!("{}\n", "\\relax ".repeat(26));
|
let complete_line = format!("{}\n", "\\relax ".repeat(26));
|
||||||
let source = format!("{prefix}{}{continuation}", complete_line.repeat(40));
|
let source = format!("{prefix}{}{continuation}", complete_line.repeat(40));
|
||||||
@@ -447,6 +451,13 @@ fn png_project_edit_updates_only_the_page_using_the_image() {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
assert_eq!(images.len(), 1);
|
assert_eq!(images.len(), 1);
|
||||||
|
let image_id = document.objects.values().find_map(|object| {
|
||||||
|
object.as_dict().ok()?.get(b"OriginalImage").ok()?.as_reference().ok()
|
||||||
|
}).unwrap();
|
||||||
|
assert!(std::ptr::eq(
|
||||||
|
document.get_object(image_id).unwrap().as_stream().unwrap(),
|
||||||
|
images[0].0,
|
||||||
|
));
|
||||||
assert_eq!(images[0].0.content, [0, 0, 255, 0, 255, 0]);
|
assert_eq!(images[0].0.content, [0, 0, 255, 0, 255, 0]);
|
||||||
assert_eq!(images[0].1.content, [255, 128]);
|
assert_eq!(images[0].1.content, [255, 128]);
|
||||||
fs::remove_dir_all(root).unwrap();
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
|||||||
Reference in new issue
Block a user