Allocate indirect PDF import objects during native writes

This commit is contained in:
gloamxun committed 2026-11-28 00:06:51 +08:00
1 parent 5a2df6781a
commit 861c9dbfc9
14 files changed
+588 -32

No files matched your search

@@ -312,6 +312,7 @@ impl PdfImage {
fn retain_reachable_objects(&mut self) {
let mut used = vec![false; self.objects.len()];
let mut visit = vec![0];
visit.extend(self.pdftex_source.iter().filter_map(|source| source.info()));
while let Some(index) = visit.pop() {
if std::mem::replace(&mut used[index], true) {
continue;
@@ -339,6 +340,9 @@ impl PdfImage {
}
}
}
if let Some(source) = &mut self.pdftex_source {
source.retain(&used, &reindex);
}
self.objects = keep;
}
}
@@ -0,0 +1,195 @@
//! Indirect source objects are allocated in the order pdfTeX writes them.
use super::{Graph, Part, PdfImage, resolved};
use crate::{pdf_device::page_resources::PdfObjects, resources::ResourceVersion};
use lopdf::{Dictionary, Object, ObjectId};
use serde::{Deserialize, Serialize};
use std::{collections::VecDeque, io::Write};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(super) struct SourceGraph {
// Slot zero belongs to the output Form, which has no source object number.
nodes: Vec<Option<SourceObject>>,
info: Option<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct SourceObject {
id: ObjectId,
stream: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct ImportWrite {
pub(crate) objects: Vec<Option<ImportedObject>>,
pub(super) form_entries: Vec<Part>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct ImportedObject {
pub(crate) number: u32,
pub(super) write: bool,
}
impl SourceGraph {
pub(super) fn capture(graph: &mut Graph<'_>) -> Result<Self, String> {
let mut info_ref = Vec::new();
if let Ok(info @ Object::Reference(_)) = graph.doc.trailer.get(b"Info") {
graph.render(info, &mut info_ref, 0)?;
}
let info = match info_ref.as_slice() {
[Part::Ref(index)] => Some(*index),
_ => None,
};
let mut nodes = vec![None; graph.bodies.len()];
for (&id, &index) in &graph.ids {
nodes[index] = Some(SourceObject {
id,
stream: matches!(graph.doc.objects.get(&id), Some(Object::Stream(_))),
});
}
Ok(Self { nodes, info })
}
pub(super) fn info(&self) -> Option<usize> {
self.info
}
pub(super) fn retain(&mut self, used: &[bool], reindex: &[usize]) {
self.nodes = std::mem::take(&mut self.nodes)
.into_iter()
.zip(used)
.filter_map(|(node, &keep)| keep.then_some(node))
.collect();
self.info = self.info.map(|index| reindex[index]);
}
}
impl Graph<'_> {
// pdfTeX inlines the selected page's resource dictionary and its top-level
// groups. References *inside* those groups are preserved and queued.
pub(super) fn pdftex_resources(
&mut self,
source: Option<&Object>,
form: &mut Vec<Part>,
) -> Result<(), String> {
let mut entries = Dictionary::new();
if let Some(source) = source {
let resources = resolved(self.doc, source)?
.as_dict()
.map_err(|error| error.to_string())?;
for (key, value) in resources.iter() {
let value = resolved(self.doc, value)?;
let valid = match key.as_slice() {
b"ProcSet" => matches!(value, Object::Array(_)),
b"Subtype" => matches!(value, Object::Name(_)),
_ => matches!(value, Object::Dictionary(_)),
};
if valid {
entries.set(key.clone(), value.clone());
}
}
}
self.render(&Object::Dictionary(entries), form, 0)
}
}
impl PdfImage {
pub(crate) fn has_source_graph(&self) -> bool {
self.pdftex_source.is_some()
}
pub(crate) fn write_import(
&self,
file_name: &str,
suppress: i32,
underscore: bool,
registry: &mut PdfObjects,
compression: u8,
limit: usize,
) -> Result<ImportWrite, String> {
let source = self.pdftex_source.as_ref().expect("pdfTeX source graph");
let separator = if underscore { '_' } else { '.' };
let mut form_entries = Vec::new();
let mut header = Vec::new();
if suppress & 2 == 0 {
write!(header, "/PTEX{separator}FileName <").unwrap();
for byte in file_name.bytes() {
write!(header, "{byte:02X}").unwrap();
}
header.extend_from_slice(b">\n");
}
if suppress & 4 == 0 {
writeln!(header, "/PTEX{separator}PageNumber {}", self.page).unwrap();
}
if suppress & 8 == 0
&& let Some(info) = source.info
{
write!(header, "/PTEX{separator}InfoDict ").unwrap();
form_entries.push(Part::Bytes(std::mem::take(&mut header)));
form_entries.push(Part::Ref(info));
header.push(b'\n');
}
if !header.is_empty() {
form_entries.push(Part::Bytes(header));
}
let mut queue = VecDeque::new();
let mut objects = vec![None; source.nodes.len()];
let mut numbering = ImportNumbering {
source,
version: &self.version,
registry,
limit,
};
numbering.references(
form_entries.iter().chain(&self.objects[0]),
&mut objects,
&mut queue,
)?;
while let Some(index) = queue.pop_front() {
let object = source.nodes[index].expect("indirect source object");
if compression >= 2 && !object.stream {
numbering
.registry
.pack_object(objects[index].unwrap().number, limit)?;
}
numbering.references(self.objects[index].iter(), &mut objects, &mut queue)?;
}
Ok(ImportWrite {
objects,
form_entries,
})
}
}
struct ImportNumbering<'a> {
source: &'a SourceGraph,
version: &'a ResourceVersion,
registry: &'a mut PdfObjects,
limit: usize,
}
impl ImportNumbering<'_> {
fn references<'a>(
&mut self,
parts: impl Iterator<Item = &'a Part>,
objects: &mut [Option<ImportedObject>],
queue: &mut VecDeque<usize>,
) -> Result<(), String> {
for part in parts {
let Part::Ref(index) = *part else { continue };
if objects[index].is_some() {
continue;
}
let source = self.source.nodes[index].expect("indirect source object");
let (number, write) =
self.registry
.import_image_object(self.version, source.id, self.limit)?;
objects[index] = Some(ImportedObject { number, write });
if write {
queue.push_back(index);
}
}
Ok(())
}
}
+2 -1
View File
@@ -147,6 +147,7 @@ pub(super) fn read(
objects: vec![vec![Part::Png(image)]],
color_space,
imported_fonts: Vec::new(),
pdftex_source: None,
restored_pdf_origin: None,
},
warning,
@@ -193,7 +194,7 @@ impl SampledImage {
compression: u8,
pdf_version: (i32, i32),
color_space: Option<i64>,
targets: PdfImageTargets,
targets: PdfImageTargets<'_>,
) -> usize {
let target = targets.image;
let id = target.unwrap_or(pdf.len() + 1);