Share physical Type 1 fonts across PDF page resources

This commit is contained in:
gloamxun committed 2026-11-26 16:28:26 +08:00
1 parent 5edd4ae4ec
commit 38c567623a
11 files changed
+385 -140

No files matched your search

@@ -0,0 +1,177 @@
//! Document-wide physical Type 1 embeddings for TeX glyphs and included PDFs.
use super::{native_pdf_name, objects};
use crate::{
native_font::Type1ProgramKey,
pdf_image::ImportedType1Use,
type1::Type1Font,
type1_outline::{subset_tag, write_subset},
};
use std::{
collections::{BTreeSet, HashMap},
fmt::Write as _,
};
pub(crate) struct Reference {
pub object: usize,
pub name: String,
}
pub(crate) type References<'a> = HashMap<Type1ProgramKey<'a>, Reference>;
struct FontPlan<'a> {
font: &'a Type1Font,
parameters: String,
subset: bool,
all_glyphs: bool,
glyphs: BTreeSet<String>,
}
#[derive(Default)]
pub(super) struct FontPlans<'a>(HashMap<Type1ProgramKey<'a>, FontPlan<'a>>);
impl<'a> FontPlans<'a> {
pub(super) fn include(&mut self, use_: &'a ImportedType1Use) {
let plan = self.0.entry(use_.mapped.key()).or_insert_with(|| {
let font = &use_.mapped.font;
let [left, bottom, right, top] = font.bbox;
let angle = &font.italic_angle;
let flags = use_.mapped.flags;
let stem_v = use_.stem_v;
FontPlan {
font,
parameters: format!(
"/Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} \
/Ascent {top} /Descent {bottom} /CapHeight {top} /StemV {stem_v}"
),
subset: use_.mapped.subset,
all_glyphs: false,
glyphs: BTreeSet::new(),
}
});
if let Some(glyphs) = &use_.glyphs {
plan.glyphs.extend(glyphs.iter().cloned());
} else {
plan.all_glyphs = true;
}
}
pub(super) fn paint(
&mut self,
key: Type1ProgramKey<'a>,
font: &'a Type1Font,
subset: bool,
parameters: impl FnOnce() -> String,
glyphs: impl Iterator<Item = &'a str>,
) {
let plan = self.0.entry(key).or_insert_with(|| FontPlan {
font,
parameters: parameters(),
subset,
all_glyphs: false,
glyphs: BTreeSet::new(),
});
if plan.subset {
plan.glyphs.extend(
glyphs
.filter(|glyph| *glyph != ".notdef")
.map(str::to_owned),
);
}
}
pub(super) fn write(
self,
objects: &mut Vec<Vec<u8>>,
compression: u8,
) -> Result<References<'a>, String> {
let mut plans: Vec<_> = self.0.into_iter().collect();
plans.sort_unstable_by(|((a, at), _), ((b, bt), _)| {
(a.path.file_name(), at, &a.path, &a.sha256, a.bytes).cmp(&(
b.path.file_name(),
bt,
&b.path,
&b.sha256,
b.bytes,
))
});
let mut tags = BTreeSet::new();
let mut references = HashMap::new();
for (key, plan) in plans {
let reference = if plan.subset {
let tag = (0..100)
.map(|salt| subset_tag(&plan.font.name, &plan.glyphs, salt))
.find(|tag| tags.insert(tag.clone()))
.ok_or("Type1 subset name collision limit exceeded")?;
let subset = write_subset(plan.font, &plan.glyphs, plan.all_glyphs, &tag)?;
let lengths = [subset.length1, subset.program.len() - subset.length1, 0];
Reference {
object: write_embedding(
objects,
&subset.name,
&plan.parameters,
Some(&subset.glyphs),
&subset.program,
lengths,
compression,
),
name: subset.name,
}
} else {
Reference {
object: write_full(objects, plan.font, &plan.parameters, compression),
name: plan.font.name.clone(),
}
};
references.insert(key, reference);
}
Ok(references)
}
}
pub(super) fn write_full(
objects: &mut Vec<Vec<u8>>,
font: &Type1Font,
parameters: &str,
compression: u8,
) -> usize {
write_embedding(
objects,
&font.name,
parameters,
None,
&font.program,
[font.length1, font.length2, font.length3],
compression,
)
}
fn write_embedding(
objects: &mut Vec<Vec<u8>>,
name: &str,
parameters: &str,
glyphs: Option<&BTreeSet<String>>,
program: &[u8],
lengths: [usize; 3],
compression: u8,
) -> usize {
let descriptor = objects.len() + 1;
let file = descriptor + 1;
let name = native_pdf_name(name);
let mut body = format!("<< /Type /FontDescriptor /FontName /{name} {parameters}");
if let Some(glyphs) = glyphs {
body.push_str(" /CharSet <");
for glyph in glyphs {
body.push_str("2F");
for byte in glyph.bytes() {
write!(body, "{byte:02X}").unwrap();
}
}
body.push('>');
}
write!(body, " /FontFile {file} 0 R >>").unwrap();
objects.push(body.into_bytes());
let [clear, private, trailer] = lengths;
let keys = format!("/Length1 {clear} /Length2 {private} /Length3 {trailer}");
objects.push(objects::stream(&keys, program, compression));
descriptor
}