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

+15 -6
View File
@@ -13,7 +13,9 @@ use std::{
sync::{Arc, Mutex, OnceLock},
};
mod map;
mod truetype;
mod virtual_paint;
pub use truetype::TrueTypeProgram;
pub use map::PdfFontBindings;
use map::{dedicated_space_map, find_map_entry, load_map, selected_outline};
pub(crate) use virtual_paint::{JobVirtualFonts, VirtualGlyphs, VirtualPaintState};
@@ -64,7 +66,7 @@ impl NativeFontPaint {
match &self.program {
NativeFontProgram::Type1(font) => self.resources.get(self.program_index.unwrap_or(1))
.map(|version| (version, font.transform)),
NativeFontProgram::Pk(_) => None,
NativeFontProgram::Pk(_) | NativeFontProgram::TrueType(_) => None,
}
}
}
@@ -73,12 +75,14 @@ impl NativeFontPaint {
pub enum NativeFontProgram {
Type1(crate::type1::Type1Font),
Pk(crate::pk_font::PkFontProgram),
TrueType(TrueTypeProgram),
}
impl NativeFontProgram {
pub fn name(&self) -> &str {
match self {
Self::Type1(p) => &p.name,
Self::Pk(p) => &p.name,
Self::TrueType(p) => &p.name,
}
}
}
@@ -373,7 +377,7 @@ impl NativeFontCache {
/// Resolve only fonts used by actual output lists. TFM-only execution and
/// unshipped boxes do not require any font program. Errors leave lists intact.
/// SVG executes the requested glyph programs; PDF embeds the same actual PFB.
/// SVG draws the requested outlines; PDF embeds the same actual font programs.
pub fn resolve_native_fonts(
pages: &mut [crate::render::DisplayList],
files: &mut impl crate::execution::SourceProvider,
@@ -414,7 +418,7 @@ fn resolve_physical_fonts(
let default_version = captured.and_then(|bindings| bindings.default_map.as_ref())
.or_else(|| default_map.as_ref().map(|map| &map.version));
let mut resolved = BTreeMap::new();
let mut pk_resolved = BTreeMap::new();
let mut direct_resolved = BTreeMap::new();
let device = pages.iter().find_map(|page| page.pdf.as_ref());
let xdv = device.is_some_and(|pdf| pdf.driver == crate::pdf_device::PdfDriver::Xdv);
let device = device.map(|pdf| pdf.file.clone());
@@ -480,7 +484,7 @@ fn resolve_physical_fonts(
}));
glyph_paths.insert(slot, program.glyph_path(slot)?);
}
pk_resolved.insert(
direct_resolved.insert(
id,
Arc::new(NativeFontPaint {
program: NativeFontProgram::Pk(program),
@@ -499,6 +503,11 @@ fn resolve_physical_fonts(
);
continue;
};
if let Some(file) = outline.true_type_file() {
let paint = truetype::resolve(files, outline, file, &font, slots)?;
direct_resolved.insert(id, Arc::new(paint));
continue;
}
let file = outline.type1_file(&font.name)?;
let version = outline.version.as_ref();
let key = (
@@ -583,7 +592,7 @@ fn resolve_physical_fonts(
.into_iter()
.map(|(id, key)| (id, cache[&key].clone()))
.collect();
resolved.extend(pk_resolved);
resolved.extend(direct_resolved);
for page in pages {
for item in &mut page.items {
if let DisplayItem::NativeGlyph {
@@ -596,7 +605,7 @@ fn resolve_physical_fonts(
{
let p = resolved[&font.id].clone();
*character = match &p.program {
NativeFontProgram::Type1(_) => {
NativeFontProgram::Type1(_) | NativeFontProgram::TrueType(_) => {
crate::type1::glyph_unicode_text(&p.encoding[*slot as usize])
.and_then(|text| text.chars().next())
.unwrap_or('�')
@@ -38,6 +38,21 @@ impl MapEntry {
self.file.is_some() || self.postscript_name
}
pub(super) fn true_type_file(&self) -> Option<&str> {
self.file.as_deref().filter(|file| {
Path::new(file)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
extension.eq_ignore_ascii_case("ttf") || extension.eq_ignore_ascii_case("ttc")
})
})
}
pub(super) fn postscript_name(&self) -> Option<&str> {
self.ps_name.as_deref()
}
pub(super) fn type1_file(&self, name: &str) -> Result<&str, String> {
let file = self.file.as_deref().ok_or_else(|| {
format!("font map {name} has no embedded Type1 program; mapped device fonts require their actual support")
@@ -0,0 +1,320 @@
//! The PDF map binds TeX slots to a real TrueType face, independent of the TFM.
use super::{NativeFont, NativeFontPaint, NativeFontProgram, map::MapEntry};
use crate::{execution::SourceProvider, resources::ResourceKind};
use rustybuzz::ttf_parser::{Face, GlyphId, PlatformId, RawFace, Tag, name_id};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
use subsetter::GlyphRemapper;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct TrueTypeProgram {
pub(crate) name: String,
data: Arc<[u8]>,
glyphs: Vec<u16>,
pub(crate) reencoded: bool,
}
impl TrueTypeProgram {
pub(crate) fn face(&self) -> Result<Face<'_>, String> {
Face::parse(&self.data, 0)
.map_err(|error| format!("invalid TrueType font {}: {error}", self.name))
}
pub(crate) fn embed(
&self,
slots: impl Iterator<Item = u8>,
subset: bool,
) -> Result<Vec<u8>, String> {
if !subset {
// A collection stores offsets into the entire file. Rebuild its
// first face as a standalone font for the PDF stream.
if self.data.starts_with(b"ttcf") {
let face = self.face()?;
return build_sfnt(tables(face.raw_face())?);
}
return Ok(self.data.to_vec());
}
let mut remapper = GlyphRemapper::new();
remapper.remap(1);
let mut mapping = [0u16; 256];
for slot in slots {
let index = usize::from(slot);
mapping[index] = remapper.remap(self.glyphs[index]);
}
let data = subsetter::subset(&self.data, 0, &remapper)
.map_err(|error| format!("failed to subset TrueType font {}: {error}", self.name))?;
let face = RawFace::parse(&data, 0).map_err(|error| error.to_string())?;
let mut tables = tables(&face)?;
let original = self.face()?;
let glyph_count = Face::parse(&data, 0)
.map_err(|error| error.to_string())?
.number_of_glyphs();
tables.insert(tag(b"cmap"), slot_cmap(&mapping, glyph_count));
if let Some(os2) = original.raw_face().table(tag(b"OS/2")) {
tables.insert(tag(b"OS/2"), symbol_os2(os2)?);
}
if let Some(pclt) = original.raw_face().table(tag(b"PCLT")) {
tables.insert(tag(b"PCLT"), pclt.to_vec());
}
build_sfnt(tables)
}
}
pub(super) fn resolve(
files: &mut impl SourceProvider,
outline: &MapEntry,
file: &str,
font: &NativeFont,
slots: BTreeSet<u8>,
) -> Result<NativeFontPaint, String> {
let from = outline.from.to_string_lossy();
let resource = super::actual_resource(files, ResourceKind::TrueType, file, &from)?;
let face = Face::parse(&resource.data, 0)
.map_err(|error| format!("invalid TrueType font {file}: {error}"))?;
if face.tables().glyf.is_none() || face.number_of_glyphs() < 2 {
return Err(format!("invalid TrueType outline tables in {file}"));
}
let mut resources: Vec<_> = outline.version.iter().cloned().collect();
let program_index = Some(resources.len());
resources.push(resource.version);
let encoding = if let Some(name) = &outline.encoding {
let enc = super::actual_resource(files, ResourceKind::Encoding, name, &from)?;
let encoding = super::encoding_vector(&enc.data)?;
resources.push(enc.version);
Some(encoding)
} else {
None
};
if outline.subset && encoding.is_none() {
return Err(format!(
"subset TrueType font {} needs a reencoding",
font.name
));
}
let reencoded = encoding.is_some();
let glyphs = if outline.subset {
let encoding = encoding.as_ref().unwrap();
encoding
.iter()
.map(|name| face.glyph_index_by_name(name).unwrap_or(GlyphId(0)).0)
.collect()
} else {
(0..=255)
.map(|slot| builtin_glyph(&face, slot).0)
.collect::<Vec<_>>()
};
let encoding = encoding.unwrap_or_else(|| {
glyphs
.iter()
.enumerate()
.map(|(slot, &glyph)| {
if let Some(name) = face.glyph_name(GlyphId(glyph)) {
return name.to_owned();
}
let character = win_ansi(slot as u8);
if glyph != 0 && face.glyph_index(character) == Some(GlyphId(glyph)) {
format!("uni{:04X}", u32::from(character))
} else {
".notdef".to_owned()
}
})
.collect()
});
let units = f64::from(face.units_per_em());
let scale = 1000. / units;
let glyph_paths = slots
.into_iter()
.map(|slot| {
let path = crate::opentype::outline(
&face,
glyphs[usize::from(slot)],
Some([scale, 0., scale]),
);
(slot, path)
})
.collect();
let name = face
.names()
.into_iter()
.filter(|name| name.name_id == name_id::POST_SCRIPT_NAME)
.find_map(|name| name.to_string())
.unwrap_or_else(|| outline.postscript_name().unwrap_or(&font.name).to_owned());
let bbox = face.global_bounding_box();
let bbox = [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max]
.map(|value| 1000 * i32::from(value) / i32::from(face.units_per_em()));
let program = TrueTypeProgram {
name,
data: resource.data.into(),
glyphs,
reencoded,
};
Ok(NativeFontPaint {
program: NativeFontProgram::TrueType(program),
encoding,
glyph_paths,
bbox,
stem_v: 0,
subset: outline.subset,
descriptor_flags: outline.descriptor_flags,
xdv_descriptor: None,
resources,
program_index,
})
}
fn builtin_glyph(face: &Face<'_>, slot: u8) -> GlyphId {
let code = u32::from(slot);
if let Some(cmap) = face.tables().cmap {
for table in cmap.subtables {
if table.platform_id == PlatformId::Windows && table.encoding_id == 0 {
return table
.glyph_index(0xf000 | code)
.or_else(|| table.glyph_index(code))
.unwrap_or(GlyphId(0));
}
}
}
face.glyph_index(win_ansi(slot))
.or_else(|| {
face.tables()
.cmap?
.subtables
.into_iter()
.find(|table| table.platform_id == PlatformId::Macintosh && table.encoding_id == 0)?
.glyph_index(code)
})
.unwrap_or(GlyphId(0))
}
fn win_ansi(slot: u8) -> char {
// WinAnsi assigns the printable Windows characters and fills the
// unused 0x80–0x9f entries with bullet.
const HIGH: [char; 32] = [
'€', '•', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '•', 'Ž', '•', '•', '‘',
'’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '•', 'ž', 'Ÿ',
];
match slot {
0x80..=0x9f => HIGH[usize::from(slot - 0x80)],
0x7f => '•',
0xa0 => ' ',
0xad => '-',
_ => char::from(slot),
}
}
fn tag(bytes: &[u8; 4]) -> Tag {
Tag::from_bytes(bytes)
}
fn tables(face: &RawFace<'_>) -> Result<BTreeMap<Tag, Vec<u8>>, String> {
face.table_records
.into_iter()
.map(|entry| {
let bytes = face
.table(entry.tag)
.ok_or("invalid TrueType table range")?;
Ok((entry.tag, bytes.to_vec()))
})
.collect()
}
fn symbol_os2(original: &[u8]) -> Result<Vec<u8>, String> {
let mut data = original
.get(..78)
.ok_or("invalid TrueType OS/2 table")?
.to_vec();
data[0..2].copy_from_slice(&1u16.to_be_bytes());
data[42..58].fill(0);
data[45] = 3;
data[46] = 0x10;
data[64..68].copy_from_slice(&[0, 0, 0xf0, 0xff]);
data.extend_from_slice(&[0x80, 0, 0, 0, 0, 0, 0, 0]);
Ok(data)
}
fn slot_cmap(mapping: &[u16; 256], glyph_count: u16) -> Vec<u8> {
let mut mac = Vec::new();
if glyph_count < 256 {
push_words(&mut mac, &[0, 262, 0]);
mac.extend(mapping.iter().map(|&gid| gid as u8));
} else {
push_words(&mut mac, &[6, 522, 0, 0, 256]);
push_words(&mut mac, mapping);
}
let mut out = Vec::new();
// A Mac byte cmap and a Windows symbol cmap address the same TeX slots.
push_words(
&mut out,
&[0, 2, 1, 0, 0, 20, 3, 0, 0, 20 + mac.len() as u16],
);
out.extend(mac);
push_words(
&mut out,
&[
4, 544, 0, 4, 4, 1, 0, 0xf0ff, 0xffff, 0, 0xf000, 0xffff, 0, 1, 4, 0,
],
);
push_words(&mut out, mapping);
out
}
fn push_words(out: &mut Vec<u8>, words: &[u16]) {
for word in words {
out.extend_from_slice(&word.to_be_bytes());
}
}
fn checksum(bytes: &[u8]) -> u32 {
bytes.chunks(4).fold(0u32, |sum, chunk| {
let mut word = [0; 4];
word[..chunk.len()].copy_from_slice(chunk);
sum.wrapping_add(u32::from_be_bytes(word))
})
}
fn build_sfnt(mut tables: BTreeMap<Tag, Vec<u8>>) -> Result<Vec<u8>, String> {
let head = tables
.get_mut(&tag(b"head"))
.ok_or("missing TrueType head table")?;
head.get_mut(8..12)
.ok_or("invalid TrueType head table")?
.fill(0);
let count = u16::try_from(tables.len()).map_err(|_| "too many TrueType tables")?;
let search = count.ilog2() as u16;
let range = (1u16 << search)
.checked_mul(16)
.ok_or("too many TrueType tables")?;
let directory_bytes = count.checked_mul(16).ok_or("too many TrueType tables")?;
let mut out = Vec::new();
push_words(
&mut out,
&[1, 0, count, range, search, directory_bytes - range],
);
out.resize(12 + usize::from(directory_bytes), 0);
let mut adjustment = None;
for (index, (tag, bytes)) in tables.into_iter().enumerate() {
let offset = out.len();
let start = 12 + index * 16;
let length = u32::try_from(bytes.len()).map_err(|_| "TrueType table too large")?;
let address = u32::try_from(offset).map_err(|_| "TrueType font too large")?;
out[start..start + 4].copy_from_slice(&tag.to_bytes());
out[start + 4..start + 8].copy_from_slice(&checksum(&bytes).to_be_bytes());
out[start + 8..start + 12].copy_from_slice(&address.to_be_bytes());
out[start + 12..start + 16].copy_from_slice(&length.to_be_bytes());
if tag == Tag::from_bytes(b"head") {
adjustment = Some(offset + 8);
}
out.extend(bytes);
out.resize(out.len().next_multiple_of(4), 0);
}
let address = adjustment.ok_or("missing TrueType checksum adjustment")?;
let value = 0xb1b0_afbau32.wrapping_sub(checksum(&out));
out[address..address + 4].copy_from_slice(&value.to_be_bytes());
Ok(out)
}
+42 -23
View File
@@ -26,6 +26,7 @@ pub(crate) mod type1_fonts;
pub(crate) mod objects;
#[path = "pdf_pk.rs"]
mod pk_fonts;
mod truetype_fonts;
#[path = "pdf_opentype.rs"]
mod opentype_fonts;
#[path = "pdf_opentype_unicode.rs"]
@@ -1768,23 +1769,17 @@ fn write_native_font(
diagnostics: &mut Vec<String>,
reference: Option<&type1_fonts::Reference>,
target: Option<usize>,
) -> usize {
let font = match &paint.program {
crate::native_font::NativeFontProgram::Type1(font) => font,
crate::native_font::NativeFontProgram::Pk(pk) => {
return pk_fonts::write_font(objects, face.id, pk, used, compression, target);
}
};
subset_tags: &mut BTreeSet<String>,
) -> Result<usize, String> {
use crate::native_font::NativeFontProgram;
if let NativeFontProgram::Pk(pk) = &paint.program {
return Ok(pk_fonts::write_font(objects, face.id, pk, used, compression, target));
}
let id = target.unwrap_or_else(|| {
objects.push(Vec::new());
objects.len()
});
let m = face.metrics();
let descriptor = reference.map_or_else(
|| type1_fonts::write_full(objects, font, &native_type1_parameters(font, paint, m), compression),
|shared| shared.object,
);
let unicode = objects.len() + 1;
let first = *used.keys().next().unwrap();
let last = *used.keys().next_back().unwrap();
let widths = (first..=last)
@@ -1801,13 +1796,34 @@ fn write_native_font(
})
.collect::<Vec<_>>()
.join(" ");
let differences = paint
.encoding
.iter()
.map(|n| format!("/{}", native_pdf_name(n)))
.collect::<Vec<_>>()
.join(" ");
let cmap = if let Some(options) = options {
let (subtype, descriptor, name, widths, encoding, has_glyph_unicode) = match &paint.program {
NativeFontProgram::Type1(font) => {
let descriptor = reference.map_or_else(
|| type1_fonts::write_full(objects, font, &native_type1_parameters(font, paint, m), compression),
|shared| shared.object,
);
let name = native_pdf_name(reference.map_or(font.name.as_str(), |shared| shared.name.as_str()));
let differences = paint.encoding.iter()
.map(|n| format!("/{}", native_pdf_name(n)))
.collect::<Vec<_>>()
.join(" ");
let encoding = format!(" /Encoding << /Type /Encoding /Differences [0 {differences}] >>");
("Type1", descriptor, name, format!("[{widths}]"), encoding, true)
}
NativeFontProgram::TrueType(program) => {
let width_object = objects.len() + 1;
objects.push(format!("[{widths}]").into_bytes());
let (descriptor, name) = truetype_fonts::write(
objects, m, paint, program, used.keys().copied(), compression, subset_tags,
)?;
("TrueType", descriptor, name, format!("{width_object} 0 R"), String::new(), program.reencoded)
}
NativeFontProgram::Pk(_) => unreachable!(),
};
let unicode = objects.len() + 1;
let cmap = if !has_glyph_unicode {
None
} else if let Some(options) = options {
if options.fonts.pdf_settings(face.id).is_some_and(|settings| settings.omit_builtin_unicode) {
None
} else if options.generate_unicode > 0 && !options.glyph_unicode.is_empty() {
@@ -1844,12 +1860,11 @@ fn write_native_font(
} else {
String::new()
};
let name = native_pdf_name(reference.map_or(font.name.as_str(), |shared| shared.name.as_str()));
objects[id - 1] = format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name} /FirstChar {first} /LastChar {last} /Widths [{widths}] /Encoding << /Type /Encoding /Differences [0 {differences}] >> /FontDescriptor {descriptor} 0 R {unicode_ref} >>").into_bytes();
objects[id - 1] = format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /FirstChar {first} /LastChar {last} /Widths {widths}{encoding} /FontDescriptor {descriptor} 0 R {unicode_ref} >>").into_bytes();
if let Some(cmap) = cmap {
objects.push(objects::stream("", &cmap, compression));
}
id
Ok(id)
}
fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
@@ -2374,6 +2389,9 @@ fn write_pdf(
Some((physical(descriptor), name.map(physical)))
})?;
let mut subset_tags = type1_references.values()
.filter_map(|font| font.name.split_once('+').map(|(tag, _)| tag.to_owned()))
.collect();
let mut native_font_ids = BTreeMap::new();
for (&id, (face, paint, used)) in &native_used {
let target = registry.and_then(|objects| objects.font_number(id))
@@ -2390,7 +2408,8 @@ fn write_pdf(
diagnostics,
paint.type1_program_key().and_then(|key| type1_references.get(&key)),
target,
),
&mut subset_tags,
)?,
);
}
for (font, owner) in aliases {
@@ -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))
}
+3 -1
View File
@@ -157,7 +157,8 @@ impl NativeText {
let expansion = if self.xdv { font.expansion } else { self.expansion };
let advance = match &paint.program {
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
crate::native_font::NativeFontProgram::Type1(_) => {
crate::native_font::NativeFontProgram::Type1(_)
| crate::native_font::NativeFontProgram::TrueType(_) => {
let factor = i64::from(1000 + expansion);
let width = if !self.xdv || font.layout_metrics.is_some() {
Self::round_scale(font.advance(slot), 1000, factor)
@@ -268,6 +269,7 @@ impl FontHistory {
&& matches!(
paint.program,
crate::native_font::NativeFontProgram::Type1(_)
| crate::native_font::NativeFontProgram::TrueType(_)
)
&& !self.first_scalable.contains_key(&font.name)
{
+6 -6
View File
@@ -168,7 +168,7 @@ struct NativeSvgGlyph<'a> {
font: &'a str,
glyph: &'a str,
path: &'a str,
type1: bool,
scalable: bool,
}
impl DisplayItem {
@@ -195,7 +195,7 @@ impl DisplayItem {
.filter(|_| paint.encoding.len() == 256)
.ok_or_else(|| {
format!(
"native Type1 SVG outline is not resolved for {} slot {slot}",
"native SVG outline is not resolved for {} slot {slot}",
font.name
)
})?;
@@ -207,9 +207,9 @@ impl DisplayItem {
font: paint.program.name(),
glyph: &paint.encoding[usize::from(*slot)],
path,
type1: matches!(
scalable: !matches!(
paint.program,
crate::native_font::NativeFontProgram::Type1(_)
crate::native_font::NativeFontProgram::Pk(_)
),
})
})())
@@ -552,7 +552,7 @@ impl DisplayList {
font,
glyph,
path,
type1,
scalable,
} = item
.native_svg_glyph()
.unwrap()
@@ -565,7 +565,7 @@ impl DisplayList {
} else {
scale * f64::from(1000 + expansion) / 1000.0
};
let label = if type1 {
let label = if scalable {
crate::type1::glyph_unicode_text(glyph).unwrap_or_default()
} else {
String::new()
+28
View File
@@ -819,6 +819,34 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
### pdfTeX 映射的 TrueType 字体
pdfTeX 的字体映射可读取实际 TrueType 程序和编码文件。
TeX 列表继续用实际 TFM 度量,PDF 以同一字体生成 TrueType 字典和
FontFile2,预览由真实字形轮廓绘制。子集使用原字体的字形名称选择
字形,复用字体子集库处理复合字形,并写 TeX 槽位对应的 Mac 字节及
Windows 符号 cmap。整嵌保留原程序,预览解析 WinAnsi 字符。
[原版 TrueType 写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writettf.c#L1226-L1325)
[原版 PDF 字典和 Unicode 映射](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writefont.c#L504-L553)
以实际 Liberation Serif 正体和斜体、Times TFM 和 TeXBase1 编码,
五组各一页的 144 DPI 灰度、原始文字、词框、字符宽度和字体描述符
字段均与 pdfTeX 1.40.29 一致。样例含带重音的复合字形、Unicode
映射及整嵌 WinAnsi 槽位 130 和 139 的实际预览。子集缺编码时
两端都报错。PDF 中字体对象号为原版 4、原生 3。定向验证覆盖新
整嵌回归及既有 Type 1 字距重载。本阶段使用开发构建。
三页项目依次改编码、改第二页子文件、让真实字体缺失并恢复。
失败保留上一版预览和 aux。三次成功编辑各复用 104 步,仅更新
第 2 页,实际字体和编码读入均有版本记录。逐次 PDF、测量页面、
完整 SVG、来源映射和 aux 与独立全量一致。
证据在 target/p3-mapped-truetype。receipt.json 的 SHA-256 为
8739d705bce538b81cbe7f60c2d7480dfa5e8e09f6ab0a47b9052f1154794610。
SFD 子字体待实现,TTC 的独立对照待补。下一入口为传统映射中的
OpenType CFF 整嵌。next-pdftex-cff 保存实际 rm-lmr10.tfm、
lmroman10-regular.otf、原版 Type 1C PDF 及当前候选报错。
### pdfTeX 字距字体的格式重载
schema95 保存派生字体名、字号和加宽后的 TFM 度量,并清除定义作业
+71
View File
@@ -1888,6 +1888,77 @@ fn relocated_format_binds_packed_and_new_glyphs_to_the_current_tfm() {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn mapped_truetype_paints_and_embeds_the_actual_font() {
use texrra_tex_core::{native_font::NativeFontProgram, render::DisplayItem};
let root = directory("mapped-truetype").canonicalize().unwrap();
let outline = root.join("face.ttf");
let map = root.join("pdftex.map");
let program = include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf");
fs::write(&outline, program).unwrap();
fs::write(&map, b"cmr10 LiberationSerif <<face.ttf\n").unwrap();
fs::write(
root.join("main.tex"),
br"\catcode123=1 \catcode125=2 \pdfoutput=1 \pdfcompresslevel=0
\font\mapped=cmr10 \shipout\hbox{\mapped AV}
\end",
)
.unwrap();
let mut job = request(&root);
for kind in [ResourceKind::Map, ResourceKind::TrueType] {
job.world
.paths
.insert(kind, vec![SearchPath::directory(&root, false)]);
}
let compiler = NativeCompiler::default();
let first = compiler.compile(job.clone()).unwrap();
let mut glyphs = String::new();
for item in &first.pages[0].items {
if let DisplayItem::NativeGlyph {
slot,
character,
paint: Some(paint),
..
} = item
{
assert!(matches!(paint.program, NativeFontProgram::TrueType(_)));
assert!(!paint.glyph_paths[slot].is_empty());
glyphs.push(*character);
}
}
assert_eq!(glyphs, "AV");
for path in [&map, &outline] {
assert!(
first
.resources
.trace
.reads
.contains(&file_version(path).unwrap().unwrap())
);
}
let pdf = lopdf::Document::load_mem(first.pdf.as_deref().unwrap()).unwrap();
let font = pdf
.objects
.values()
.find_map(|object| {
let dict = object.as_dict().ok()?;
(dict.get(b"Subtype").ok()?.as_name().ok()? == b"TrueType").then_some(dict)
})
.unwrap();
let descriptor = font.get(b"FontDescriptor").unwrap().as_reference().unwrap();
let descriptor = pdf.get_dictionary(descriptor).unwrap();
let font_file = descriptor.get(b"FontFile2").unwrap().as_reference().unwrap();
let embedded = pdf.get_object(font_file).unwrap().as_stream().unwrap();
assert_eq!(embedded.content, program);
fs::remove_file(&outline).unwrap();
let error = compiler.compile_detailed(job).err().unwrap().error.to_string();
assert!(error.contains("face.ttf"), "{error}");
assert!(Arc::ptr_eq(&first, &compiler.latest().unwrap()));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn loaded_format_uses_current_letterspace_font_programs() {
use texrra_tex_core::render::DisplayItem;