Allocate mapped Type 1 import objects in PDF write order

This commit is contained in:
gloamxun committed 2026-11-28 00:30:57 +08:00
1 parent 861c9dbfc9
commit c1c3c25b3f
9 files changed
+466 -95

No files matched your search

@@ -1,7 +1,7 @@
//! Replacement of fonts in the root resources of an included pdfTeX page.
use super::{Graph, Part, PdfImage, number, resolved};
use super::{Graph, ImportWrite, Part, PdfImage, number, resolved};
use crate::{native_font::MappedType1, type1::{builtin_encoding, standard_encoding}};
use lopdf::{Dictionary, Document, Object, Stream};
use lopdf::{Dictionary, Document, Object, ObjectId, Stream};
use read_fonts::ps::cff::CffFontRef;
use std::{borrow::Cow, collections::BTreeSet, sync::Arc};
@@ -12,7 +12,8 @@ pub(super) struct ImportedType1 {
stem_v: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
charset: Option<Vec<u8>>,
dictionary: Result<Vec<Part>, String>,
descriptor: ObjectId,
dictionary: Result<(Vec<Part>, Vec<u8>), String>,
}
pub(super) fn capture(
@@ -68,9 +69,9 @@ pub(super) fn capture(
let Ok(descriptor) = dict.get(b"FontDescriptor") else {
continue;
};
if descriptor.as_reference().is_err() {
let Ok(descriptor_id) = descriptor.as_reference() else {
continue;
}
};
let Ok(descriptor) = resolved(doc, descriptor)?.as_dict() else {
continue;
};
@@ -96,6 +97,7 @@ pub(super) fn capture(
postscript_name: postscript_name.to_owned(),
stem_v,
charset,
descriptor: descriptor_id,
dictionary,
});
}
@@ -172,88 +174,90 @@ fn font_template(
graph: &mut Graph<'_>,
dict: &Dictionary,
file: EmbeddedType1<'_>,
) -> Result<Vec<Part>, String> {
) -> Result<(Vec<Part>, Vec<u8>), String> {
let doc = graph.doc;
let mut replacement = dict.clone();
replacement.remove(b"BaseFont");
replacement.remove(b"FontDescriptor");
if let Some(encoding) = replace_implicit_encoding(doc, dict, file)? {
replacement.set("Encoding", encoding);
}
replacement.remove(b"Encoding");
let encoding = imported_encoding(doc, dict, file)?;
let encoding = crate::pdf_device::page_resources::encode_value(Object::Dictionary(encoding))?;
let mut parts = Vec::new();
graph.render(&Object::Dictionary(replacement), &mut parts, 0)?;
let Some(Part::Bytes(end)) = parts.last_mut() else {
return Err("missing imported font dictionary end".into());
};
end.truncate(end.len() - 2);
Ok(parts)
Ok((parts, encoding))
}
fn replace_implicit_encoding(
fn imported_encoding(
doc: &Document,
font: &Dictionary,
program: EmbeddedType1<'_>,
) -> Result<Option<Dictionary>, String> {
let encoding = font
.get(b"Encoding")
.ok()
.map(|object| resolved(doc, object))
.transpose()?;
let differences = match encoding {
Some(Object::Name(_)) => return Ok(None),
Some(Object::Dictionary(dict)) if dict.has(b"BaseEncoding") => return Ok(None),
Some(Object::Dictionary(dict)) => dict.get(b"Differences").ok(),
None | Some(Object::Null) => None,
) -> Result<Dictionary, String> {
let source = font.get(b"Encoding").ok().map(|value| resolved(doc, value)).transpose()?;
let (base, differences) = match source {
Some(Object::Name(name)) => (Some(name.as_slice()), None),
Some(Object::Dictionary(dict)) => (
dict.get(b"BaseEncoding").ok()
.map(|value| resolved(doc, value)?.as_name().map_err(|error| error.to_string()))
.transpose()?,
dict.get(b"Differences").ok(),
),
None | Some(Object::Null) => (None, None),
_ => return Err("invalid Type1 encoding in included PDF".into()),
};
let mut names = program.glyph_names(doc)?;
if let Some(differences) = differences {
let differences = resolved(doc, differences)?
.as_array()
.map_err(|error| error.to_string())?;
let mut slot = 0usize;
for value in differences {
match resolved(doc, value)? {
Object::Integer(code) => {
slot = usize::try_from(*code)
.ok()
.filter(|&slot| slot < names.len())
.ok_or("invalid Type1 encoding difference index")?;
}
Object::Name(glyph) => {
*names
.get_mut(slot)
.ok_or("Type1 encoding difference exceeds 256 slots")? = glyph.clone();
slot += 1;
}
_ => return Err("invalid Type1 encoding difference".into()),
let differences = differences.map(|value| {
let values = resolved(doc, value)?.as_array().map_err(|error| error.to_string())?;
values.iter().map(|value| match resolved(doc, value)? {
value @ (Object::Integer(_) | Object::Name(_)) => Ok(value.clone()),
_ => Err("invalid Type1 encoding difference".to_owned()),
}).collect::<Result<Vec<_>, String>>()
}).transpose()?.unwrap_or_default();
let mut encoding = Dictionary::new();
encoding.set("Type", Object::Name(b"Encoding".to_vec()));
if let Some(base) = base.filter(|base| *base != b"StandardEncoding") {
encoding.set("BaseEncoding", Object::Name(base.to_vec()));
if !differences.is_empty() {
encoding.set("Differences", Object::Array(differences));
}
return Ok(encoding);
}
let mut names = if base.is_some() {
(0..=255u8).map(|slot| standard_encoding(slot).unwrap_or(".notdef").as_bytes().to_vec()).collect()
} else {
program.glyph_names(doc)?
};
let mut slot = 0usize;
for value in differences {
match value {
Object::Integer(code) => {
slot = usize::try_from(code).ok().filter(|&slot| slot < names.len())
.ok_or("invalid Type1 encoding difference index")?;
}
Object::Name(glyph) => {
*names.get_mut(slot).ok_or("Type1 encoding difference exceeds 256 slots")? = glyph;
slot += 1;
}
_ => unreachable!(),
}
}
let mut generated = Dictionary::new();
generated.set("Type", Object::Name(b"Encoding".to_vec()));
let first = font
.get(b"FirstChar")
.ok()
.and_then(|object| resolved(doc, object).ok())
.and_then(|object| object.as_i64().ok())
.unwrap_or(0)
.clamp(0, 255);
let last = font
.get(b"LastChar")
.ok()
.and_then(|object| resolved(doc, object).ok())
.and_then(|object| object.as_i64().ok())
.unwrap_or(255)
.clamp(first, 255);
let mut differences = vec![Object::Integer(first)];
differences.extend(
names
.drain(first as usize..=last as usize)
.map(Object::Name),
);
generated.set("Differences", Object::Array(differences));
Ok(Some(generated))
let mut differences = Vec::new();
let mut next = None;
for (slot, name) in names.into_iter().enumerate() {
if name == b".notdef" {
continue;
}
if next != Some(slot) {
differences.push(Object::Integer(slot as i64));
}
differences.push(Object::Name(name));
next = Some(slot + 1);
}
encoding.set("Differences", Object::Array(differences));
Ok(encoding)
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -261,11 +265,18 @@ pub(crate) struct ImportedType1Use {
pub mapped: MappedType1,
pub stem_v: i32,
pub glyphs: Option<BTreeSet<String>>,
pub(super) descriptor: ObjectId,
pub(super) encoding: Vec<u8>,
}
impl PdfImage {
pub(crate) fn mapped_type1_fonts(&self) -> impl Iterator<Item = &ImportedType1Use> {
self.objects.iter().flatten().filter_map(|part| {
pub(crate) fn mapped_type1_fonts<'a>(
&'a self,
imports: Option<&'a ImportWrite>,
) -> impl Iterator<Item = &'a ImportedType1Use> {
self.objects.iter().enumerate().filter(move |(index, _)| {
imports.is_none_or(|import| import.font_encodings.contains_key(index))
}).flat_map(|(_, parts)| parts).filter_map(|part| {
if let Part::MappedType1(font) = part {
Some(font.as_ref())
} else {
@@ -297,8 +308,10 @@ impl PdfImage {
})
.transpose()?;
let stem_v = crate::type1_outline::pdftex_stem_v(&mapped.font)?.unwrap_or(entry.stem_v);
let mut dictionary = entry.dictionary.clone()?;
dictionary.push(Part::MappedType1(Arc::new(ImportedType1Use { mapped, stem_v, glyphs })));
let (mut dictionary, encoding) = entry.dictionary.clone()?;
dictionary.push(Part::MappedType1(Arc::new(ImportedType1Use {
mapped, stem_v, glyphs, descriptor: entry.descriptor, encoding,
})));
dictionary.push(Part::Bytes(b">>".to_vec()));
result.get_or_insert_with(|| self.clone()).objects[entry.index] = dictionary;
}
@@ -3,7 +3,10 @@ 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};
use std::{
collections::{BTreeMap, VecDeque},
io::Write,
};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(super) struct SourceGraph {
@@ -22,6 +25,8 @@ struct SourceObject {
pub(crate) struct ImportWrite {
pub(crate) objects: Vec<Option<ImportedObject>>,
pub(super) form_entries: Vec<Part>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) font_encodings: BTreeMap<usize, u32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -138,6 +143,8 @@ impl PdfImage {
let mut numbering = ImportNumbering {
source,
version: &self.version,
bodies: &self.objects,
font_encodings: BTreeMap::new(),
registry,
limit,
};
@@ -146,6 +153,15 @@ impl PdfImage {
&mut objects,
&mut queue,
)?;
// Encodings are emitted in reverse registration order before source
// dictionaries, including when they start a new object stream.
if compression > 0 {
let mut encodings: Vec<_> = numbering.font_encodings.values().copied().collect();
encodings.sort_unstable_by(|left, right| right.cmp(left));
for number in encodings {
numbering.registry.pack_object(number, limit)?;
}
}
while let Some(index) = queue.pop_front() {
let object = source.nodes[index].expect("indirect source object");
if compression >= 2 && !object.stream {
@@ -154,10 +170,21 @@ impl PdfImage {
.pack_object(objects[index].unwrap().number, limit)?;
}
numbering.references(self.objects[index].iter(), &mut objects, &mut queue)?;
// A mapped font's /BaseFont name is requested after the other
// font dictionary entries, including indirect widths.
if let Some(Part::MappedType1(font)) = self.objects[index]
.iter()
.find(|part| matches!(part, Part::MappedType1(_)))
{
numbering
.registry
.reserve_imported_type1_name(font.mapped.key(), limit)?;
}
}
Ok(ImportWrite {
objects,
form_entries,
font_encodings: numbering.font_encodings,
})
}
}
@@ -165,6 +192,8 @@ impl PdfImage {
struct ImportNumbering<'a> {
source: &'a SourceGraph,
version: &'a ResourceVersion,
bodies: &'a [Vec<Part>],
font_encodings: BTreeMap<usize, u32>,
registry: &'a mut PdfObjects,
limit: usize,
}
@@ -182,6 +211,28 @@ impl ImportNumbering<'_> {
continue;
}
let source = self.source.nodes[index].expect("indirect source object");
if self
.registry
.imported_image_number(self.version, source.id)
.is_none()
&& let Some(Part::MappedType1(font)) = self.bodies[index]
.iter()
.find(|part| matches!(part, Part::MappedType1(_)))
{
if self
.registry
.imported_image_number(self.version, font.descriptor)
.is_none()
{
let descriptor = self
.registry
.reserve_imported_type1_descriptor(font.mapped.key(), self.limit)?;
self.registry
.bind_imported_image(self.version, font.descriptor, descriptor);
}
let encoding = self.registry.reserve_imported_font_part(self.limit)?;
self.font_encodings.insert(index, encoding);
}
let (number, write) =
self.registry
.import_image_object(self.version, source.id, self.limit)?;