Embed a TrueType Roman font in route-D PDFs

This commit is contained in:
gloamxun committed 2026-10-20 20:49:21 +08:00
1 parent a703f2dcc0
commit a09398811f
5 files changed
+95 -12

No files matched your search

+4 -1
View File
@@ -1735,7 +1735,10 @@ mod tests {
let text = String::from_utf8_lossy(&pdf);
assert!(text.starts_with("%PDF-1.4"));
assert!(text.contains("/Type /Page "));
assert!(text.contains("/BaseFont /Times-Roman"));
assert!(text.contains("/BaseFont /LiberationSerif"));
assert!(text.contains("/Subtype /Type0"));
assert!(text.contains("/FontFile2"));
assert!(text.contains("/ToUnicode"));
assert!(text.contains("Tj"));
assert!(text.trim_end().ends_with("%%EOF"));
}
+85 -6
View File
@@ -1,12 +1,48 @@
//! Minimal PDF writer for route-D display lists.
//!
//! Base-14 Times-Roman text, filled rectangles, and raw-RGB image XObjects.
//! TFM/NFSS fonts and `\special` are later milestones.
//! Embedded true-type Roman text, Base-14 companion faces, filled rectangles,
//! and raw-RGB image XObjects.
use std::collections::BTreeMap;
use std::sync::OnceLock;
use rusttype::Font;
use crate::render::{DisplayItem, DisplayList, FontFace};
static SERIF_BYTES: &[u8] =
include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf");
static SERIF: OnceLock<Font<'static>> = OnceLock::new();
fn serif() -> &'static Font<'static> {
SERIF.get_or_init(|| Font::from_bytes(SERIF_BYTES).expect("embedded serif font"))
}
fn glyph_hex(text: &str) -> String {
let font = serif();
let mut out = String::new();
for character in text.chars() {
let id = font.glyph(character).id().0;
out.push_str(&format!("{id:04X}"));
}
out
}
fn tounicode_cmap() -> Vec<u8> {
let font = serif();
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;
map.push_str(&format!("<{id:04X}> <{:04X}>\n", character as u32));
}
map.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
map.into_bytes()
}
fn escape(text: &str) -> String {
let mut out = String::new();
for character in text.chars() {
@@ -38,7 +74,7 @@ fn font_base(font: FontFace) -> &'static str {
fn font_resource(font: FontFace) -> &'static str {
match font {
FontFace::Roman => "F1",
FontFace::Roman => "F6",
FontFace::Bold => "F2",
FontFace::Italic => "F3",
FontFace::BoldItalic => "F4",
@@ -58,12 +94,16 @@ fn page_content(list: &DisplayList, height: i64, image_names: &BTreeMap<usize, S
font,
} => {
content.push_str(&format!(
"BT /{} {} Tf 1 0 0 1 {} {} Tm ({}) Tj ET\n",
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
font_resource(*font),
pt(*size),
pt(*x),
pt(height - *y),
escape(text)
if *font == FontFace::Roman {
format!("<{}>", glyph_hex(text))
} else {
format!("({})", escape(text))
}
));
}
DisplayItem::Rule {
@@ -153,6 +193,45 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
);
}
// Embedded Type0 Roman font: Type0, CIDFont, descriptor, FontFile2.
let type0_id = objects.len() + 1;
let cid_id = type0_id + 1;
let descriptor_id = type0_id + 2;
let file_id = type0_id + 3;
let tounicode_id = type0_id + 4;
objects.push(
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /LiberationSerif /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>"
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /LiberationSerif /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 1000 >>"
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /LiberationSerif /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle 0 /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>"
)
.into_bytes(),
);
let mut font_stream = format!(
"<< /Length {} /Length1 {} >>\nstream\n",
SERIF_BYTES.len(),
SERIF_BYTES.len()
)
.into_bytes();
font_stream.extend_from_slice(SERIF_BYTES);
font_stream.extend_from_slice(b"\nendstream");
objects.push(font_stream);
let cmap = tounicode_cmap();
let mut cmap_object = format!("<< /Length {} >>\nstream\n", cmap.len()).into_bytes();
cmap_object.extend_from_slice(&cmap);
cmap_object.extend_from_slice(b"\nendstream");
objects.push(cmap_object);
let mut kids = Vec::new();
for list in pages {
let mut used = BTreeMap::new();
@@ -171,7 +250,7 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
.collect::<Vec<_>>()
.join(" ");
let fonts = "/F1 3 0 R /F2 4 0 R /F3 5 0 R /F4 6 0 R /F5 7 0 R";
let fonts = format!("/F1 3 0 R /F2 4 0 R /F3 5 0 R /F4 6 0 R /F5 7 0 R /F6 {type0_id} 0 R");
let resources = if used.is_empty() {
format!("<< /Font << {fonts} >> >>")
} else {