Write XeTeX PDF font descriptors from OS/2 and CFF data

This commit is contained in:
gloamxun committed 2026-11-25 22:15:06 +08:00
1 parent 2b82172bfb
commit fa27e0985f
5 files changed
+125 -16

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ libloading = "=0.8.9"
md5 = "0.8"
png = "0.18.1"
rusttype = "0.8.3"
read-fonts = { version = "=0.46.0", default-features = false }
rustybuzz = "=0.20.1"
subsetter = { version = "=0.2.3", default-features = false }
unicode-bidi = "=0.3.18"
+83 -16
View File
@@ -1,7 +1,11 @@
//! Embedding for glyphs selected by the native OpenType shaper.
use super::{PageContent, native_pdf_name, objects, to_unicode_map};
use crate::{execution::FontId, opentype::OpenTypeFont};
use rustybuzz::ttf_parser::{GlyphId, RawFace, Tag};
use read_fonts::{
FontData, FontRead,
ps::cff::{dict, v1::Cff},
};
use rustybuzz::ttf_parser::{Face, GlyphId, RawFace, Tag};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fmt::Write};
use subsetter::GlyphRemapper;
@@ -149,21 +153,7 @@ fn write_font(
objects.push(format!(
"<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /W [{widths}]{mapping} >>"
).into_bytes());
let rect = face.global_bounding_box();
let [left, bottom, right, top] =
[rect.x_min, rect.y_min, rect.x_max, rect.y_max].map(|v| width(i64::from(v)));
let ascent = width(i64::from(face.tables().hhea.ascender));
let descent = width(i64::from(face.tables().hhea.descender));
let cap = face
.capital_height()
.map_or(ascent, |n| width(i64::from(n)));
let flags = 4 | i32::from(face.is_monospaced()) | if face.is_italic() { 64 } else { 0 };
let angle = face.italic_angle();
let stem = f64::from(face.weight().to_number()) / 65.;
let stem = (50. + stem * stem).round() as i32;
objects.push(format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem} /{file_key} {font_file} 0 R >>"
).into_bytes());
objects.push(font_descriptor(&face, &name, file_key, font_file));
objects.push(objects::stream(&file_options, program, compression));
objects.push(objects::stream("", &to_unicode_map(&cmap, 4), compression));
Ok(EmbeddedFont {
@@ -173,6 +163,83 @@ fn write_font(
})
}
fn font_descriptor(face: &Face<'_>, name: &str, file_key: &str, font_file: usize) -> Vec<u8> {
// XDV uses the OS/2 typographic values for PDF metadata independently
// of the metrics selected by the layout engine.
let os2 = face
.raw_face()
.table(Tag::from_bytes(b"OS/2"))
.filter(|table| table.len() >= 68);
let field = |offset| {
let bytes = os2?.get(offset..offset + 2)?;
Some(u16::from_be_bytes([bytes[0], bytes[1]]))
};
let pdf_units = |value: i16| {
(1000. * f64::from(value) / f64::from(face.units_per_em()) + 0.5).floor() as i32
};
let rect = face.global_bounding_box();
let [left, bottom, right, top] =
[rect.x_min, rect.y_min, rect.x_max, rect.y_max].map(pdf_units);
let ascent = pdf_units(field(68).map_or(880, |number| number as i16));
let descent = pdf_units(field(70).map_or(-120, |number| number as i16));
let (cap, x_height) = if field(0) == Some(2) {
let cap = field(88).map_or(ascent, |number| pdf_units(number as i16));
let x_height = field(86).map(|number| pdf_units(number as i16));
(cap, x_height)
} else {
(ascent, None)
};
let average_width = field(2).unwrap_or(0) as i16;
let weight = f64::from(field(4).unwrap_or(400)) / 65.;
let stem = cff_stem_width(face).unwrap_or_else(|| (weight * weight + 50.).trunc());
let selection = field(62).unwrap_or(0);
let family = field(30).unwrap_or(0) >> 8;
let flags = 4
| i32::from(face.is_monospaced())
| (i32::from(family != 8) << 1)
| (i32::from(family == 10) << 3)
| (i32::from(selection & 1 != 0) << 6)
| (i32::from(selection & (1 << 5) != 0) << 18);
let angle = face.italic_angle();
let mut descriptor = format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem}"
);
if let Some(height) = x_height {
write!(descriptor, " /XHeight {height}").unwrap();
}
if average_width != 0 {
write!(descriptor, " /AvgWidth {}", pdf_units(average_width)).unwrap();
}
descriptor.push_str(" /Style << /Panose <");
for byte in os2.map_or(&[0; 12][..], |table| &table[30..42]) {
write!(descriptor, "{byte:02X}").unwrap();
}
write!(descriptor, "> >> /{file_key} {font_file} 0 R >>").unwrap();
descriptor.into_bytes()
}
fn cff_stem_width(face: &Face<'_>) -> Option<f64> {
let data = face.raw_face().table(Tag::from_bytes(b"CFF "))?;
let cff = Cff::read(FontData::new(data)).ok()?;
let top_dict = cff.top_dicts().get(0)?;
let mut private_dict = None;
for entry in dict::entries(top_dict, None).flatten() {
match entry {
dict::Entry::Ros { .. } => return None,
dict::Entry::PrivateDictRange(range) => private_dict = Some(range),
_ => {}
}
}
let private_dict = data.get(private_dict?)?;
dict::entries(private_dict, None).flatten().find_map(|entry| {
if let dict::Entry::StdVw(width) = entry {
Some(width.to_f64())
} else {
None
}
})
}
fn utf16_hex(value: &str) -> String {
value
.encode_utf16()