Allocate mapped Type 1 import objects in PDF write order
This commit is contained in:
1 parent
861c9dbfc9
commit
c1c3c25b3f
9 files changed
+466
-95
No files matched your search
@@ -2270,7 +2270,7 @@ fn write_pdf(
|
||||
let registry = unicode.and_then(|options| options.objects);
|
||||
let mut device_objects = BTreeMap::new();
|
||||
if let Some(registry) = registry {
|
||||
for number in registry.font_object_numbers() {
|
||||
for number in registry.font_object_numbers().chain(registry.imported_font_numbers()) {
|
||||
// An unused queried font leaves its reservation free.
|
||||
objects.push(Vec::new());
|
||||
device_objects.insert(number, objects.len() as u32);
|
||||
@@ -2346,8 +2346,8 @@ fn write_pdf(
|
||||
let mut type1_plans = type1_fonts::FontPlans::default();
|
||||
// pdfTeX collects included font descriptors as it writes forms. The
|
||||
// TeX font dictionaries and their glyph marks are finalized afterward.
|
||||
for (image, ..) in &images {
|
||||
for font in image.image.mapped_type1_fonts() {
|
||||
for (image, _, _, _, imports) in &images {
|
||||
for font in image.image.mapped_type1_fonts(*imports) {
|
||||
type1_plans.include(font);
|
||||
}
|
||||
}
|
||||
@@ -2368,7 +2368,11 @@ fn write_pdf(
|
||||
|| native_type1_parameters(program, owner_paint, owner.metrics()), glyphs);
|
||||
}
|
||||
let omit_charset = unicode.is_some_and(|options| options.omit_charset);
|
||||
let type1_references = type1_plans.write(&mut objects, compression, omit_charset)?;
|
||||
let type1_references = type1_plans.write(&mut objects, compression, omit_charset, |key| {
|
||||
let (descriptor, name) = registry?.imported_type1_slots(key)?;
|
||||
let physical = |number| device_objects[&number] as usize;
|
||||
Some((physical(descriptor), name.map(physical)))
|
||||
})?;
|
||||
|
||||
let mut native_font_ids = BTreeMap::new();
|
||||
for (&id, (face, paint, used)) in &native_used {
|
||||
|
||||
@@ -14,6 +14,7 @@ use std::{
|
||||
pub(crate) struct Reference {
|
||||
pub object: usize,
|
||||
pub name: String,
|
||||
pub name_object: Option<usize>,
|
||||
}
|
||||
|
||||
pub(crate) type References<'a> = HashMap<Type1ProgramKey<'a>, Reference>;
|
||||
@@ -84,6 +85,7 @@ impl<'a> FontPlans<'a> {
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
compression: u8,
|
||||
omit_charset: bool,
|
||||
reserved: impl Fn(Type1ProgramKey<'a>) -> Option<(usize, Option<usize>)>,
|
||||
) -> Result<References<'a>, String> {
|
||||
let mut plans: Vec<_> = self.0.into_iter().collect();
|
||||
plans.sort_unstable_by(|((a, at), _), ((b, bt), _)| {
|
||||
@@ -98,6 +100,8 @@ impl<'a> FontPlans<'a> {
|
||||
let mut tags = BTreeSet::new();
|
||||
let mut references = HashMap::new();
|
||||
for (key, plan) in plans {
|
||||
let slots = reserved(key);
|
||||
let name_object = slots.and_then(|(_, name)| name);
|
||||
let reference = if plan.subset {
|
||||
let tag = (0..100)
|
||||
.map(|salt| subset_tag(&plan.font.name, &plan.glyphs, salt))
|
||||
@@ -114,13 +118,25 @@ impl<'a> FontPlans<'a> {
|
||||
&subset.program,
|
||||
lengths,
|
||||
compression,
|
||||
slots,
|
||||
),
|
||||
name: subset.name,
|
||||
name_object,
|
||||
}
|
||||
} else {
|
||||
Reference {
|
||||
object: write_full(objects, plan.font, &plan.parameters, compression),
|
||||
object: write_embedding(
|
||||
objects,
|
||||
&plan.font.name,
|
||||
&plan.parameters,
|
||||
None,
|
||||
&plan.font.program,
|
||||
[plan.font.length1, plan.font.length2, plan.font.length3],
|
||||
compression,
|
||||
slots,
|
||||
),
|
||||
name: plan.font.name.clone(),
|
||||
name_object,
|
||||
}
|
||||
};
|
||||
references.insert(key, reference);
|
||||
@@ -143,6 +159,7 @@ pub(super) fn write_full(
|
||||
&font.program,
|
||||
[font.length1, font.length2, font.length3],
|
||||
compression,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -154,11 +171,24 @@ fn write_embedding(
|
||||
program: &[u8],
|
||||
lengths: [usize; 3],
|
||||
compression: u8,
|
||||
slots: Option<(usize, Option<usize>)>,
|
||||
) -> usize {
|
||||
let descriptor = objects.len() + 1;
|
||||
let file = descriptor + 1;
|
||||
let descriptor = slots.map_or_else(
|
||||
|| {
|
||||
objects.push(Vec::new());
|
||||
objects.len()
|
||||
},
|
||||
|(descriptor, _)| descriptor,
|
||||
);
|
||||
let file = objects.len() + 1;
|
||||
let name = native_pdf_name(name);
|
||||
let mut body = format!("<< /Type /FontDescriptor /FontName /{name} {parameters}");
|
||||
let font_name = if let Some((_, Some(name_id))) = slots {
|
||||
objects[name_id - 1] = format!("/{name}").into_bytes();
|
||||
format!("{name_id} 0 R")
|
||||
} else {
|
||||
format!("/{name}")
|
||||
};
|
||||
let mut body = format!("<< /Type /FontDescriptor /FontName {font_name} {parameters}");
|
||||
if let Some(glyphs) = glyphs {
|
||||
body.push_str(" /CharSet <");
|
||||
for glyph in glyphs {
|
||||
@@ -170,7 +200,7 @@ fn write_embedding(
|
||||
body.push('>');
|
||||
}
|
||||
write!(body, " /FontFile {file} 0 R >>").unwrap();
|
||||
objects.push(body.into_bytes());
|
||||
objects[descriptor - 1] = body.into_bytes();
|
||||
let [clear, private, trailer] = lengths;
|
||||
let keys = format!("/Length1 {clear} /Length2 {private} /Length3 {trailer}");
|
||||
objects.push(objects::stream(&keys, program, compression));
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! Native PDF objects and extra resources captured at page shipout.
|
||||
use crate::{execution::FontId, resources::ResourceVersion};
|
||||
use crate::{
|
||||
execution::FontId, native_font::Type1ProgramKey, resources::ResourceVersion,
|
||||
type1::Type1Transform,
|
||||
};
|
||||
use super::links::DestinationId;
|
||||
use lopdf::{
|
||||
Dictionary, Object, ObjectId, Stream,
|
||||
@@ -40,6 +43,7 @@ pub(crate) enum ObjectBody {
|
||||
ObjectStream,
|
||||
Destination,
|
||||
ImportedImage,
|
||||
ImportedFont,
|
||||
}
|
||||
|
||||
impl ObjectBody {
|
||||
@@ -48,7 +52,7 @@ impl ObjectBody {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form
|
||||
| Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::Destination | Self::ImportedImage | Self::DiscardedAtDump => 0,
|
||||
| Self::Destination | Self::ImportedImage | Self::ImportedFont | Self::DiscardedAtDump => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
@@ -68,7 +72,7 @@ impl ObjectBody {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
|
||||
| Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::Destination | Self::ImportedImage => {
|
||||
| Self::Destination | Self::ImportedImage | Self::ImportedFont => {
|
||||
Err("expected a generic native PDF object".into())
|
||||
}
|
||||
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
|
||||
@@ -135,6 +139,8 @@ pub struct PdfObjects {
|
||||
// Source object numbers belong to one particular version of one file.
|
||||
#[serde(skip)]
|
||||
imported_images: BTreeMap<PathBuf, BTreeMap<String, BTreeMap<ObjectId, u32>>>,
|
||||
#[serde(skip)]
|
||||
imported_type1: BTreeMap<(PathBuf, String, Type1Transform), (u32, Option<u32>)>,
|
||||
}
|
||||
|
||||
impl PdfObjects {
|
||||
@@ -268,21 +274,67 @@ impl PdfObjects {
|
||||
self.written_png_group
|
||||
}
|
||||
|
||||
pub(crate) fn imported_image_number(&self, version: &ResourceVersion, source: ObjectId) -> Option<u32> {
|
||||
self.imported_images.get(&version.path)?.get(&version.sha256)?.get(&source).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn bind_imported_image(&mut self, version: &ResourceVersion, source: ObjectId, number: u32) {
|
||||
self.imported_images.entry(version.path.clone()).or_default()
|
||||
.entry(version.sha256.clone()).or_default().entry(source).or_insert(number);
|
||||
}
|
||||
|
||||
pub(crate) fn import_image_object(
|
||||
&mut self, version: &ResourceVersion, source: ObjectId, limit: usize,
|
||||
) -> Result<(u32, bool), String> {
|
||||
if let Some(&number) = self.imported_images.get(&version.path)
|
||||
.and_then(|versions| versions.get(&version.sha256))
|
||||
.and_then(|objects| objects.get(&source))
|
||||
{
|
||||
if let Some(number) = self.imported_image_number(version, source) {
|
||||
return Ok((number, false));
|
||||
}
|
||||
let number = self.allocate(Some(Arc::new(ObjectBody::ImportedImage)), limit)?;
|
||||
self.imported_images.entry(version.path.clone()).or_default()
|
||||
.entry(version.sha256.clone()).or_default().insert(source, number);
|
||||
self.bind_imported_image(version, source, number);
|
||||
Ok((number, true))
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_imported_font_part(&mut self, limit: usize) -> Result<u32, String> {
|
||||
self.allocate(Some(Arc::new(ObjectBody::ImportedFont)), limit)
|
||||
}
|
||||
|
||||
pub(crate) fn imported_font_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
||||
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
||||
matches!(entry.as_deref(), Some(ObjectBody::ImportedFont)).then_some(index as u32 + 1)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn imported_type1_slots(&self, key: Type1ProgramKey<'_>) -> Option<(u32, Option<u32>)> {
|
||||
let (version, transform) = key;
|
||||
self.imported_type1.get(&(version.path.clone(), version.sha256.clone(), transform)).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_imported_type1_descriptor(
|
||||
&mut self, key: Type1ProgramKey<'_>, limit: usize,
|
||||
) -> Result<u32, String> {
|
||||
if let Some((descriptor, _)) = self.imported_type1_slots(key) {
|
||||
return Ok(descriptor);
|
||||
}
|
||||
let number = self.reserve_imported_font_part(limit)?;
|
||||
let (version, transform) = key;
|
||||
self.imported_type1.insert((version.path.clone(), version.sha256.clone(), transform), (number, None));
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_imported_type1_name(
|
||||
&mut self, key: Type1ProgramKey<'_>, limit: usize,
|
||||
) -> Result<(), String> {
|
||||
let descriptor = self.reserve_imported_type1_descriptor(key, limit)?;
|
||||
if self.imported_type1_slots(key).is_some_and(|(_, name)| name.is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
let number = self.reserve_imported_font_part(limit)?;
|
||||
let (version, transform) = key;
|
||||
self.imported_type1.insert((version.path.clone(), version.sha256.clone(), transform),
|
||||
(descriptor, Some(number)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn imported_image_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
||||
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
||||
matches!(entry.as_deref(), Some(ObjectBody::ImportedImage)).then_some(index as u32 + 1)
|
||||
@@ -388,7 +440,7 @@ impl PdfObjects {
|
||||
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
|
||||
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
|
||||
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination
|
||||
| ObjectBody::ImportedImage) => {
|
||||
| ObjectBody::ImportedImage | ObjectBody::ImportedFont) => {
|
||||
ObjectBody::DiscardedAtDump
|
||||
}
|
||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||
@@ -409,6 +461,7 @@ impl PdfObjects {
|
||||
self.destination_numbers.clear();
|
||||
self.shipped_links.clear();
|
||||
self.imported_images.clear();
|
||||
self.imported_type1.clear();
|
||||
!self.values.is_empty()
|
||||
}
|
||||
|
||||
@@ -574,7 +627,7 @@ pub(crate) fn font_attributes_affect_paint(bytes: &[u8]) -> Result<bool, String>
|
||||
Ok(attributes.iter().any(|(name, _)| name != b"ToUnicode"))
|
||||
}
|
||||
|
||||
pub(super) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
pub(crate) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
if let Object::Stream(stream) = object {
|
||||
let mut output = encode_value(Object::Dictionary(stream.dict))?;
|
||||
output.extend_from_slice(b"\nstream\n");
|
||||
@@ -869,7 +922,7 @@ impl ResourceOutput {
|
||||
|| device_objects.contains(&number) || objects.font_owner(number).is_some()
|
||||
|| matches!(objects.entry(number).and_then(Option::as_deref),
|
||||
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream
|
||||
| ObjectBody::Destination | ObjectBody::ImportedImage))
|
||||
| ObjectBody::Destination | ObjectBody::ImportedImage | ObjectBody::ImportedFont))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -963,8 +963,19 @@ impl PdfImage {
|
||||
Part::MappedType1(font) => {
|
||||
let reference = &fonts[&font.mapped.key()];
|
||||
body.extend_from_slice(b" /BaseFont ");
|
||||
body.extend(pdf_name(reference.name.as_bytes()));
|
||||
write!(body, " /FontDescriptor {} 0 R", reference.object).unwrap();
|
||||
if let Some(name) = reference.name_object {
|
||||
write!(body, "{name} 0 R").unwrap();
|
||||
} else {
|
||||
body.extend(pdf_name(reference.name.as_bytes()));
|
||||
}
|
||||
write!(body, " /FontDescriptor {} 0 R /Encoding ", reference.object).unwrap();
|
||||
if let Some((allocation, numbers)) = targets.imports {
|
||||
let encoding = numbers[&allocation.font_encodings[&index]];
|
||||
pdf[encoding as usize - 1].clone_from(&font.encoding);
|
||||
write!(body, "{encoding} 0 R").unwrap();
|
||||
} else {
|
||||
body.extend_from_slice(&font.encoding);
|
||||
}
|
||||
}
|
||||
Part::Png(_) | Part::Bmp(_) => unreachable!("sampled image owns its objects"),
|
||||
Part::XdvCmykDecode => {
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
Reference in new issue
Block a user