Parse Computer Modern Type1 programs for PDF embedding

This commit is contained in:
gloamxun committed 2026-10-24 03:24:32 +08:00
1 parent 36f2aa12d7
commit 5b5fdab8a6
3 files changed
+215

No files matched your search

Binary file not shown.
+1
View File
@@ -7,6 +7,7 @@ pub mod pdf;
pub mod render;
mod subset;
pub mod tfm;
pub mod type1;
pub use cmr10::Cmr10Metrics;
use std::collections::BTreeMap;
+214
View File
@@ -0,0 +1,214 @@
//! Type1 (PFB) loading for TeX's Computer Modern outlines.
//!
//! Route-D used to embed Liberation TrueType outlines while taking widths from
//! the Computer Modern TFMs, so the PDF glyph shapes never matched the metrics.
//! This module parses Knuth's Type1 programs directly: PFB segment lengths for
//! the PDF `/FontFile` entry and the font's built-in encoding so callers can map
//! characters to the codes the program expects.
use std::collections::BTreeMap;
/// A Type1 font program ready to be written as a PDF `/FontFile` stream.
#[derive(Clone, Debug)]
pub struct Type1Font {
/// PostScript name, for example `CMR10`.
pub name: String,
/// Clear-text header, `eexec` payload and trailing zeros concatenated.
pub program: Vec<u8>,
/// Length of the clear-text portion (`/Length1`).
pub length1: usize,
/// Length of the encrypted portion (`/Length2`).
pub length2: usize,
/// Length of the trailing clear-text portion (`/Length3`).
pub length3: usize,
codes: BTreeMap<String, u8>,
}
impl Type1Font {
/// Parse a PFB container into a PDF-ready program plus its encoding.
pub fn from_pfb(bytes: &[u8]) -> Option<Self> {
let mut header = Vec::new();
let mut encrypted = Vec::new();
let mut trailer = Vec::new();
let mut index = 0usize;
while index + 6 <= bytes.len() {
if bytes[index] != 0x80 {
return None;
}
let kind = bytes[index + 1];
let length = u32::from_le_bytes([
bytes[index + 2],
bytes[index + 3],
bytes[index + 4],
bytes[index + 5],
]) as usize;
let start = index + 6;
let end = start.checked_add(length)?;
if end > bytes.len() {
return None;
}
match kind {
1 if encrypted.is_empty() => header.extend_from_slice(&bytes[start..end]),
1 => trailer.extend_from_slice(&bytes[start..end]),
2 => encrypted.extend_from_slice(&bytes[start..end]),
3 => {
index = end;
break;
}
_ => return None,
}
index = end;
}
if header.is_empty() || encrypted.is_empty() {
return None;
}
let text = String::from_utf8_lossy(&header);
let name = text.lines().find_map(|line| {
line.trim()
.strip_prefix("/FontName /")
.map(|rest| rest.split_whitespace().next().unwrap_or(rest).to_string())
})?;
let mut codes = BTreeMap::new();
for line in text.lines() {
let line = line.trim();
if !line.starts_with("dup ") || !line.ends_with(" put") {
continue;
}
let mut parts = line.split_whitespace();
if parts.next() != Some("dup") {
continue;
}
let Some(code) = parts.next().and_then(|value| value.parse::<u8>().ok()) else {
continue;
};
let Some(name) = parts.next().and_then(|value| value.strip_prefix('/')) else {
continue;
};
if name == ".notdef" || codes.contains_key(name) {
continue;
}
codes.insert(name.to_string(), code);
}
let length1 = header.len();
let length2 = encrypted.len();
let length3 = trailer.len();
let mut program = header;
program.extend_from_slice(&encrypted);
program.extend_from_slice(&trailer);
Some(Self {
name,
program,
length1,
length2,
length3,
codes,
})
}
/// PDF character code for `ch`, using the font's own encoding.
pub fn code_for(&self, ch: char) -> Option<u8> {
glyph_names(ch)
.iter()
.find_map(|name| self.codes.get(*name).copied())
}
/// Whether the program has a glyph for every character in `chars`.
pub fn covers(&self, chars: impl IntoIterator<Item = char>) -> bool {
chars.into_iter().all(|ch| self.code_for(ch).is_some())
}
/// Number of encoded glyphs parsed from the program.
pub fn glyph_count(&self) -> usize {
self.codes.len()
}
}
/// PostScript glyph names that can represent `ch`, most specific first.
fn glyph_names(ch: char) -> &'static [&'static str] {
const DIGITS: [&str; 10] = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
];
const UPPER: [&str; 26] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z",
];
const LOWER: [&str; 26] = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z",
];
match ch {
'0'..='9' => &DIGITS[(ch as u8 - b'0') as usize..][..1],
'A'..='Z' => &UPPER[(ch as u8 - b'A') as usize..][..1],
'a'..='z' => &LOWER[(ch as u8 - b'a') as usize..][..1],
'\'' => &["quotesingle", "quoteright"],
'"' => &["quotedbl", "quotedblleft", "quotedblbase"],
'`' => &["grave", "quoteleft"],
'-' => &["hyphen", "minus"],
' ' => &["space"],
'!' => &["exclam"],
'#' => &["numbersign"],
'$' => &["dollar"],
'%' => &["percent"],
'&' => &["ampersand"],
'(' => &["parenleft"],
')' => &["parenright"],
'*' => &["asterisk"],
'+' => &["plus"],
',' => &["comma"],
'.' => &["period"],
'/' => &["slash"],
':' => &["colon"],
';' => &["semicolon"],
'<' => &["less"],
'=' => &["equal"],
'>' => &["greater"],
'?' => &["question"],
'@' => &["at"],
'[' => &["bracketleft"],
'\\' => &["backslash"],
']' => &["bracketright"],
'^' => &["asciicircum"],
'_' => &["underscore"],
'{' => &["braceleft"],
'|' => &["bar"],
'}' => &["braceright"],
'~' => &["asciitilde"],
_ => &[],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cmr10() -> Type1Font {
Type1Font::from_pfb(include_bytes!("../../../assets/fonts/cmr10.pfb"))
.expect("parse cmr10.pfb")
}
#[test]
fn pfb_segments_become_a_pdf_font_program() {
let font = cmr10();
assert_eq!(font.name, "CMR10");
assert_eq!(font.length1, 4_287);
assert_eq!(font.length2, 30_900);
assert_eq!(font.length3, 545);
assert_eq!(
font.program.len(),
font.length1 + font.length2 + font.length3
);
assert!(font.glyph_count() > 100);
}
#[test]
fn built_in_encoding_maps_printable_ascii() {
let font = cmr10();
assert_eq!(font.code_for('A'), Some(65));
assert_eq!(font.code_for('a'), Some(97));
assert_eq!(font.code_for('-'), Some(45));
assert_eq!(font.code_for('\''), Some(39));
assert_eq!(font.code_for(' '), Some(160));
assert!(font.covers("Hello, world!".chars()));
assert!(font.code_for('é').is_none());
}
}