Render and embed TrueType fonts selected by pdfTeX maps

This commit is contained in:
gloamxun committed 2026-11-28 02:30:30 +08:00
1 parent aa780a800b
commit 46ef76f890
9 files changed
+570 -36

No files matched your search

@@ -0,0 +1,70 @@
use super::{native_font_units, native_pdf_font_size, native_pdf_name, objects};
use crate::{
native_font::{NativeFontPaint, TrueTypeProgram},
tfm::TfmMetrics,
type1_outline::subset_tag,
};
use rustybuzz::ttf_parser::Tag;
use std::collections::BTreeSet;
pub(super) fn write(
objects: &mut Vec<Vec<u8>>,
metrics: &TfmMetrics,
paint: &NativeFontPaint,
program: &TrueTypeProgram,
used: impl Iterator<Item = u8>,
compression: u8,
subset_tags: &mut BTreeSet<String>,
) -> Result<(usize, String), String> {
let mut slots: BTreeSet<_> = used.collect();
let name = if paint.subset {
let names = slots
.iter()
.map(|&slot| &paint.encoding[usize::from(slot)])
.filter(|name| *name != ".notdef")
.cloned()
.collect();
let tag = (0..100)
.map(|salt| subset_tag(&program.name, &names, salt))
.find(|tag| subset_tags.insert(tag.clone()))
.ok_or("TrueType subset name collision limit exceeded")?;
if paint.encoding[97] == "a" {
// Match pdfTeX's additional glyph for older PDF readers.
slots.insert(b'a');
}
format!("{tag}+{}", native_pdf_name(&program.name))
} else {
native_pdf_name(&program.name)
};
let data = program.embed(slots.into_iter(), paint.subset)?;
let face = program.face()?;
let in_pdf_units = |value: i16| 1000 * i32::from(value) / i32::from(face.units_per_em());
let ascent = in_pdf_units(face.tables().hhea.ascender);
let descent = in_pdf_units(face.tables().hhea.descender);
let pclt = face.raw_face().table(Tag::from_bytes(b"PCLT"));
let pclt_height = |offset| {
let bytes = pclt?.get(offset..offset + 2)?;
Some(in_pdf_units(i16::from_be_bytes(bytes.try_into().ok()?)))
};
let size = native_pdf_font_size(metrics.size_sp());
let cap = pclt_height(16)
.unwrap_or_else(|| native_font_units(metrics.height('H'), size, 1000) as i32);
let x_height =
pclt_height(10).unwrap_or_else(|| native_font_units(metrics.x_height(), size, 1000) as i32);
let stem = native_font_units(metrics.width('.') / 3, size, 1000);
let angle = face.italic_angle().floor() as i32;
let [left, bottom, right, top] = paint.bbox;
let flags = paint.descriptor_flags.unwrap_or(4);
let font_file = objects.len() + 1;
objects.push(objects::stream(
&format!("/Length1 {}", data.len()),
&data,
compression,
));
let descriptor = objects.len() + 1;
objects.push(format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /Ascent {ascent} /Descent {descent} /CapHeight {cap} /ItalicAngle {angle} /StemV {stem} /XHeight {x_height} /FontFile2 {font_file} 0 R >>"
).into_bytes());
Ok((descriptor, name))
}