Subset embedded fonts to the glyphs a document uses

This commit is contained in:
gloamxun committed 2026-10-21 09:14:46 +08:00
1 parent 06779fb8dd
commit 8731ec2b9e
5 files changed
+335 -13

No files matched your search

+22
View File
@@ -3,6 +3,7 @@ pub mod math;
pub mod paragraph;
pub mod pdf;
pub mod render;
mod subset;
pub mod tfm;
pub use cmr10::Cmr10Metrics;
@@ -2852,6 +2853,27 @@ mod tests {
assert!(text.trim_end().ends_with("%%EOF"));
}
#[test]
fn pdf_subset_keeps_only_used_glyphs() {
let document = Document::new(400, vec![Unit::paragraph(1, "caf\u{e9}")]);
let engine = Engine::layout(&document);
let list = engine.pages()[0].display_list();
let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536);
let text = String::from_utf8_lossy(&pdf);
let length1 = text
.split("/Length1 ")
.nth(1)
.and_then(|rest| rest.split_whitespace().next())
.and_then(|value| value.parse::<usize>().ok())
.expect("FontFile2 /Length1");
assert!(
length1 < crate::pdf::full_face_size(crate::render::FontFace::Roman),
"subset {length1} should be smaller than the full face {}",
crate::pdf::full_face_size(crate::render::FontFace::Roman)
);
assert!(text.contains("/Filter /FlateDecode"));
}
#[test]
fn pdf_embeds_only_the_used_faces() {
let document = Document::new(400, vec![Unit::paragraph(1, "roman only")]);
+22 -9
View File
@@ -4,6 +4,7 @@
//! and raw-RGB image XObjects.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::io::Write as _;
use std::sync::OnceLock;
@@ -136,6 +137,11 @@ fn face(font: FontFace, faces: &'static [PdfFace; 6]) -> &'static PdfFace {
&faces[font as usize]
}
#[allow(dead_code)]
pub(crate) fn full_face_size(font: FontFace) -> usize {
FULL_FACES[font as usize].bytes.len()
}
fn face_font(face: &'static PdfFace) -> &'static Font<'static> {
face.font
.get_or_init(|| Font::from_bytes(face.bytes).expect("embedded face"))
@@ -151,15 +157,19 @@ fn glyph_hex(face: &'static PdfFace, text: &str) -> String {
out
}
fn tounicode_cmap(face: &'static PdfFace) -> Vec<u8> {
fn tounicode_cmap(face: &'static PdfFace, characters: &BTreeSet<char>) -> Vec<u8> {
let font = face_font(face);
let mut map = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n /CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n 1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
let chars: Vec<char> = (0x20u8..=0x7e).map(char::from).collect();
map.push_str(&format!("{} beginbfchar\n", chars.len()));
for character in chars {
let id = font.glyph(character).id().0;
let mut entries = std::collections::BTreeMap::new();
for character in characters {
if (*character as u32) <= 0xffff {
entries.insert(font.glyph(*character).id().0, *character);
}
}
map.push_str(&format!("{} beginbfchar\n", entries.len()));
for (id, character) in entries {
map.push_str(&format!("<{id:04X}> <{:04X}>\n", character as u32));
}
map.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
@@ -327,10 +337,12 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
objects.push(Vec::new()); // pages object filled below
let mut used_faces = [false; 6];
let mut used_chars: [BTreeSet<char>; 6] = Default::default();
for page in pages {
for item in &page.items {
if let DisplayItem::Text { font, .. } = item {
if let DisplayItem::Text { font, text, .. } = item {
used_faces[*font as usize] = true;
used_chars[*font as usize].extend(text.chars());
}
}
}
@@ -373,17 +385,18 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
)
.into_bytes(),
);
let compressed = deflate(face.bytes);
let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), &used_chars[slot]);
let compressed = deflate(&font_bytes);
let mut font_stream = format!(
"<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n",
compressed.len(),
face.bytes.len()
font_bytes.len()
)
.into_bytes();
font_stream.extend_from_slice(&compressed);
font_stream.extend_from_slice(b"\nendstream");
objects.push(font_stream);
let cmap = tounicode_cmap(face);
let cmap = tounicode_cmap(face, &used_chars[slot]);
let compressed_cmap = deflate(&cmap);
let mut cmap_object = format!(
"<< /Length {} /Filter /FlateDecode >>\nstream\n",
+287
View File
@@ -0,0 +1,287 @@
//! Minimal TrueType `glyf` subsetting for embedded PDF fonts.
//!
//! Glyph IDs deliberately stay unchanged: the PDF Type0 font uses Identity-H
//! with CID = glyph ID, and `CIDToGIDMap /Identity`, so a subset may only
//! replace unused glyph outlines with empty ones. Other tables are copied
//! verbatim and only the SFNT offsets/checksums are rebuilt.
use std::collections::BTreeSet;
use rusttype::Font;
fn be_u16(bytes: &[u8], offset: usize) -> u16 {
u16::from_be_bytes([bytes[offset], bytes[offset + 1]])
}
fn be_u32(bytes: &[u8], offset: usize) -> u32 {
u32::from_be_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
])
}
fn be_i16(bytes: &[u8], offset: usize) -> i16 {
i16::from_be_bytes([bytes[offset], bytes[offset + 1]])
}
fn table_checksum(data: &[u8]) -> u32 {
let mut sum = 0_u32;
for chunk in data.chunks(4) {
let mut word = [0_u8; 4];
word[..chunk.len()].copy_from_slice(chunk);
sum = sum.wrapping_add(u32::from_be_bytes(word));
}
sum
}
struct Table {
tag: [u8; 4],
data: Vec<u8>,
}
/// Component glyph IDs referenced by a composite glyph.
fn components(glyph: &[u8]) -> Vec<u16> {
if glyph.len() < 10 || be_i16(glyph, 0) >= 0 {
return Vec::new();
}
let mut result = Vec::new();
let mut offset = 10;
loop {
if offset + 4 > glyph.len() {
break;
}
let flags = be_u16(glyph, offset);
let index = be_u16(glyph, offset + 2);
result.push(index);
offset += 4;
offset += if flags & 0x0001 != 0 { 4 } else { 2 };
if flags & 0x0008 != 0 {
offset += 2;
} else if flags & 0x0040 != 0 {
offset += 4;
} else if flags & 0x0080 != 0 {
offset += 8;
}
if flags & 0x0020 == 0 {
break;
}
}
result
}
/// Subset a TrueType font to `characters`, preserving glyph IDs.
///
/// The returned font is still a valid SFNT file. Unused glyphs have empty
/// outlines, which is enough for PDF viewers because the page only references
/// used CIDs.
pub fn subset_font(bytes: &[u8], font: &Font, characters: &BTreeSet<char>) -> Vec<u8> {
if bytes.len() < 12 {
return bytes.to_vec();
}
let num_tables = usize::from(be_u16(bytes, 4));
let mut tables = Vec::with_capacity(num_tables);
for index in 0..num_tables {
let record = 12 + index * 16;
if record + 16 > bytes.len() {
return bytes.to_vec();
}
let mut tag = [0_u8; 4];
tag.copy_from_slice(&bytes[record..record + 4]);
let offset = be_u32(bytes, record + 8) as usize;
let length = be_u32(bytes, record + 12) as usize;
if offset + length > bytes.len() {
return bytes.to_vec();
}
tables.push(Table {
tag,
data: bytes[offset..offset + length].to_vec(),
});
}
let Some(head_index) = tables.iter().position(|table| &table.tag == b"head") else {
return bytes.to_vec();
};
let Some(loca_index) = tables.iter().position(|table| &table.tag == b"loca") else {
return bytes.to_vec();
};
let Some(glyf_index) = tables.iter().position(|table| &table.tag == b"glyf") else {
return bytes.to_vec();
};
let Some(maxp_index) = tables.iter().position(|table| &table.tag == b"maxp") else {
return bytes.to_vec();
};
if tables[head_index].data.len() < 54 || tables[maxp_index].data.len() < 6 {
return bytes.to_vec();
}
let num_glyphs = usize::from(be_u16(&tables[maxp_index].data, 4));
let long_loca = be_i16(&tables[head_index].data, 50) != 0;
let loca_len = if long_loca {
(num_glyphs + 1) * 4
} else {
(num_glyphs + 1) * 2
};
if tables[loca_index].data.len() < loca_len {
return bytes.to_vec();
}
let mut offsets = Vec::with_capacity(num_glyphs + 1);
for index in 0..=num_glyphs {
let value = if long_loca {
be_u32(&tables[loca_index].data, index * 4) as usize
} else {
usize::from(be_u16(&tables[loca_index].data, index * 2)) * 2
};
offsets.push(value);
}
let glyf = &tables[glyf_index].data;
let mut used = BTreeSet::new();
used.insert(0_u16);
for character in characters {
used.insert(font.glyph(*character).id().0 as u16);
}
// Composite glyphs reference component glyphs by ID. Keep those too, or
// the subsetted outline points at empty glyphs.
loop {
let mut added = false;
for glyph in used.clone() {
let index = usize::from(glyph);
if index >= num_glyphs {
continue;
}
let start = offsets[index];
let end = offsets[index + 1];
if end <= start || end > glyf.len() {
continue;
}
for component in components(&glyf[start..end]) {
if used.insert(component) {
added = true;
}
}
}
if !added {
break;
}
}
let mut new_glyf = Vec::new();
let mut new_loca = Vec::with_capacity(num_glyphs + 1);
for glyph in 0..num_glyphs {
let start = offsets[glyph];
let end = offsets[glyph + 1];
new_loca.push(new_glyf.len());
if used.contains(&(glyph as u16)) && end > start && end <= glyf.len() {
new_glyf.extend_from_slice(&glyf[start..end]);
}
while new_glyf.len() % 2 != 0 {
new_glyf.push(0);
}
}
new_loca.push(new_glyf.len());
if long_loca {
let mut bytes = Vec::with_capacity(new_loca.len() * 4);
for offset in &new_loca {
bytes.extend_from_slice(&(*offset as u32).to_be_bytes());
}
tables[loca_index].data = bytes;
} else {
if new_glyf.len() / 2 > usize::from(u16::MAX) {
return bytes.to_vec();
}
let mut bytes = Vec::with_capacity(new_loca.len() * 2);
for offset in &new_loca {
bytes.extend_from_slice(&((*offset / 2) as u16).to_be_bytes());
}
tables[loca_index].data = bytes;
}
tables[glyf_index].data = new_glyf;
// The head checksum adjustment must be zero while table checksums are
// computed.
tables[head_index].data[8..12].fill(0);
let mut output = Vec::new();
output.extend_from_slice(&bytes[..12]);
let directory_len = 12 + tables.len() * 16;
let mut data_offset = directory_len;
let mut records = Vec::with_capacity(tables.len());
for table in &tables {
let checksum = table_checksum(&table.data);
records.push((table.tag, checksum, data_offset, table.data.len()));
data_offset += table.data.len();
data_offset = data_offset.div_ceil(4) * 4;
}
for (tag, checksum, offset, length) in &records {
output.extend_from_slice(tag);
output.extend_from_slice(&checksum.to_be_bytes());
output.extend_from_slice(&(*offset as u32).to_be_bytes());
output.extend_from_slice(&(*length as u32).to_be_bytes());
}
for table in &tables {
output.extend_from_slice(&table.data);
while output.len() % 4 != 0 {
output.push(0);
}
}
let adjustment = 0xB1B0_AFBA_u32.wrapping_sub(table_checksum(&output));
if let Some((_, _, offset, _)) = records.iter().find(|(tag, _, _, _)| tag == b"head") {
output[offset + 8..offset + 12].copy_from_slice(&adjustment.to_be_bytes());
}
output
}
#[cfg(test)]
mod tests {
use super::*;
fn table<'a>(font: &'a [u8], tag: &[u8; 4]) -> &'a [u8] {
let count = usize::from(be_u16(font, 4));
for index in 0..count {
let record = 12 + index * 16;
if &font[record..record + 4] == tag {
let offset = be_u32(font, record + 8) as usize;
let length = be_u32(font, record + 12) as usize;
return &font[offset..offset + length];
}
}
panic!("missing table");
}
#[test]
fn composite_components_survive_subsetting() {
let bytes = include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf");
let font = Font::from_bytes(&bytes[..]).expect("font");
let mut characters = BTreeSet::new();
characters.insert('\u{e9}');
let subset = subset_font(bytes, &font, &characters);
let maxp = table(&subset, b"maxp");
let num_glyphs = usize::from(be_u16(maxp, 4));
let head = table(&subset, b"head");
let long_loca = be_i16(head, 50) != 0;
let loca = table(&subset, b"loca");
let glyf = table(&subset, b"glyf");
let offset = |glyph: usize| {
if long_loca {
be_u32(loca, glyph * 4) as usize
} else {
usize::from(be_u16(loca, glyph * 2)) * 2
}
};
let glyph_len = |glyph: usize| {
assert!(glyph < num_glyphs);
offset(glyph + 1) - offset(glyph)
};
let composite = font.glyph('\u{e9}').id().0 as usize;
let component = font.glyph('e').id().0 as usize;
assert!(glyph_len(composite) > 0, "accented glyph has no outline");
assert!(glyph_len(component) > 0, "component glyph was dropped");
assert!(glyf.len() < 4096, "subset kept too much glyph data");
}
}