Embed Computer Modern Type1 outlines in route-D PDFs

This commit is contained in:
gloamxun committed 2026-10-24 03:28:10 +08:00
1 parent 6eef2f7a54
commit 5f5fc393a4
6 files changed
+295 -10

No files matched your search

+230 -2
View File
@@ -14,6 +14,7 @@ use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font;
fn deflate(bytes: &[u8]) -> Vec<u8> {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
@@ -235,6 +236,21 @@ fn font_resource(font: FontFace) -> &'static str {
}
}
/// Which outline format the PDF writer embeds for text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FontBackend {
/// Embedded Liberation TrueType subsets (the default).
TrueType,
/// Knuth's Computer Modern Type1 programs when they cover the text.
ComputerModern,
}
fn cmr10_type1() -> Option<&'static Type1Font> {
static FONT: OnceLock<Option<Type1Font>> = OnceLock::new();
FONT.get_or_init(|| Type1Font::from_pfb(include_bytes!("../../../assets/fonts/cmr10.pfb")))
.as_ref()
}
/// TeX page origin offsets (`\hoffset`, `\voffset`) in scaled points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageOrigin {
@@ -247,6 +263,7 @@ fn page_content(
height: i64,
image_names: &BTreeMap<usize, String>,
faces: &'static [PdfFace; 6],
cm_codes: Option<&BTreeMap<char, u8>>,
origin: PageOrigin,
) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
@@ -266,13 +283,26 @@ fn page_content(
text,
font,
} => {
let operand = match cm_codes {
Some(codes) if matches!(*font, FontFace::Roman) => {
let mut literal = String::from("(");
for character in text.chars() {
if let Some(code) = codes.get(&character) {
literal.push_str(&format!("\\{:03o}", code));
}
}
literal.push(')');
literal
}
_ => format!("<{}>", glyph_hex(face(*font, faces), text)),
};
content.push_str(&format!(
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
font_resource(*font),
pt(*size),
pt(*x),
pt(height - *y),
format!("<{}>", glyph_hex(face(*font, faces), text))
operand
));
}
DisplayItem::Rule {
@@ -365,6 +395,39 @@ pub fn display_lists_to_pdf_with_paper(
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::TrueType,
)
}
/// Write PDFs with Knuth's Computer Modern Type1 outlines whenever the programs
/// cover the text, falling back to Liberation TrueType for other characters.
pub fn display_lists_to_pdf_with_cm_type1(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::ComputerModern,
)
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
backend: FontBackend,
) -> Vec<u8> {
let width = page_width;
let height = page_height;
@@ -382,6 +445,23 @@ pub fn display_lists_to_pdf_with_paper(
}
}
}
let cm_codes: Option<(&Type1Font, BTreeMap<char, u8>)> = if backend
== FontBackend::ComputerModern
&& used_faces[0]
{
cmr10_type1().and_then(|font| {
if !font.covers(used_chars[0].iter().copied()) {
return None;
}
let codes = used_chars[0]
.iter()
.filter_map(|character| font.code_for(*character).map(|code| (*character, code)))
.collect();
Some((font, codes))
})
} else {
None
};
let minimal = pages.iter().all(|page| {
page.items.iter().all(|item| match item {
DisplayItem::Text { text, .. } => text.chars().all(minimal_text_char),
@@ -394,6 +474,68 @@ pub fn display_lists_to_pdf_with_paper(
if !used_faces[slot] {
continue;
}
if slot == 0
&& let Some((font, codes)) = &cm_codes
{
let font_id = objects.len() + 1;
let descriptor_id = font_id + 1;
let file_id = font_id + 2;
font_ids[slot] = font_id;
let metrics = Cmr10Metrics::for_pdf_slot(slot);
let mut by_code = BTreeMap::new();
for (character, code) in codes {
by_code.insert(*code, *character);
}
let first = *by_code.keys().next().unwrap_or(&32);
let last = *by_code.keys().next_back().unwrap_or(&32);
let mut widths = Vec::new();
let mut differences = Vec::new();
let mut next_code = first;
for code in first..=last {
let width = by_code.get(&code).map_or(0, |character| {
(metrics.width(*character) * 100 / 65_536) as i64
});
widths.push(width.to_string());
if let Some((code, name)) = by_code
.get(&code)
.and_then(|character| font.code_and_name_for(*character))
{
if code != next_code {
differences.push(code.to_string());
}
differences.push(format!("/{name}"));
next_code = code + 1;
}
}
objects.push(
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} /FirstChar {first} /LastChar {last} /Widths [{}] /Encoding << /Type /Encoding /Differences [{}] >> /FontDescriptor {descriptor_id} 0 R >>",
font.name,
widths.join(" "),
differences.join(" ")
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{} /Flags 34 /FontBBox [-40 -250 1009 750] /ItalicAngle 0 /Ascent 694 /Descent -194 /CapHeight 683 /StemV 69 /FontFile {file_id} 0 R >>",
font.name
)
.into_bytes(),
);
let mut stream = format!(
"<< /Length {} /Length1 {} /Length2 {} /Length3 {} >>\nstream\n",
font.program.len(),
font.length1,
font.length2,
font.length3
)
.into_bytes();
stream.extend_from_slice(&font.program);
stream.extend_from_slice(b"\nendstream");
objects.push(stream);
continue;
}
let type0_id = objects.len() + 1;
let cid_id = type0_id + 1;
let descriptor_id = type0_id + 2;
@@ -514,7 +656,14 @@ pub fn display_lists_to_pdf_with_paper(
for (index, slot) in &used {
names.insert(*index, format!("Im{slot}"));
}
let content = page_content(list, height, &names, faces, origin);
let content = page_content(
list,
height,
&names,
faces,
cm_codes.as_ref().map(|(_, codes)| codes),
origin,
);
objects.push(
format!(
"<< /Length {} >>\nstream\n{}endstream",
@@ -614,3 +763,82 @@ mod tests {
assert_eq!(escape("中文"), "??");
}
}
#[cfg(test)]
mod type1_pdf_tests {
use super::*;
fn hello_list() -> DisplayList {
let mut list = DisplayList {
width: 200 * 65_536,
height: 100 * 65_536,
items: Vec::new(),
images: Vec::new(),
};
list.push(DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Hi".to_string(),
font: FontFace::Roman,
});
list
}
fn write(list: &[DisplayList]) -> Vec<u8> {
display_lists_to_pdf_with_cm_type1(list, 200 * 65_536, 800 * 65_536, PageOrigin::default())
}
#[test]
fn type1_backend_embeds_computer_modern_outlines() {
let pdf = write(&[hello_list()]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/Subtype /Type1"), "{text}");
assert!(text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/FontFile"), "{text}");
assert!(text.contains("(\\110\\151)"), "{text}");
assert!(!text.contains("/Subtype /Type0"), "{text}");
}
#[test]
fn type1_backend_falls_back_for_uncovered_characters() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "café".to_string(),
font: FontFace::Roman,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(!text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/Subtype /Type0"), "{text}");
}
#[test]
fn pdffonts_accepts_the_embedded_type1_font() {
let probe = std::process::Command::new("pdffonts").arg("-v").output();
if probe.is_err() {
return;
}
let pdf = write(&[hello_list()]);
let path = std::env::temp_dir().join(format!(
"texrra-type1-{}-{}.pdf",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|value| value.subsec_nanos())
.unwrap_or(0)
));
std::fs::write(&path, &pdf).expect("write pdf");
let output = std::process::Command::new("pdffonts")
.arg(&path)
.output()
.expect("run pdffonts");
let _ = std::fs::remove_file(&path);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Type 1"), "{stdout}");
assert!(stdout.contains("CMR10"), "{stdout}");
}
}
+7
View File
@@ -112,6 +112,13 @@ impl Type1Font {
.find_map(|name| self.codes.get(*name).copied())
}
/// PDF character code plus the PostScript glyph name it selects.
pub fn code_and_name_for(&self, ch: char) -> Option<(u8, &'static str)> {
glyph_names(ch)
.iter()
.find_map(|name| self.codes.get(*name).map(|code| (*code, *name)))
}
/// 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())