Embed all route-D text faces with CID widths

This commit is contained in:
gloamxun committed 2026-10-20 20:59:01 +08:00
1 parent 5010e9ab10
commit 641fc1c14b
4 files changed
+145 -84

No files matched your search

+4 -3
View File
@@ -1820,7 +1820,7 @@ mod tests {
let list = layout.pages()[0].display_list();
let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /Times-Italic"));
assert!(text.contains("/BaseFont /LiberationSerif-Italic"));
assert!(text.contains("BT /F3"));
}
#[test]
@@ -1835,8 +1835,9 @@ mod tests {
});
let pdf = crate::pdf::display_list_to_pdf(&list, 400 * 65_536);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /Times-Bold"));
assert!(text.contains("/F2 4 0 R"));
assert!(text.contains("/BaseFont /LiberationSerif-Bold"));
assert!(text.contains("/F2 "));
assert!(text.contains("/W ["));
assert!(text.contains("BT /F2"));
}
+122 -76
View File
@@ -1,6 +1,6 @@
//! Minimal PDF writer for route-D display lists.
//!
//! Embedded true-type Roman text, Base-14 companion faces, filled rectangles,
//! Embedded true-type text faces, filled rectangles,
//! and raw-RGB image XObjects.
use std::collections::BTreeMap;
@@ -10,16 +10,57 @@ 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"))
struct PdfFace {
bytes: &'static [u8],
base: &'static str,
italic_angle: i32,
font: OnceLock<Font<'static>>,
}
fn glyph_hex(text: &str) -> String {
let font = serif();
static FACES: [PdfFace; 5] = [
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Bold.ttf"),
base: "LiberationSerif-Bold",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-BoldItalic.ttf"),
base: "LiberationSerif-BoldItalic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationMono-Regular.ttf"),
base: "LiberationMono",
italic_angle: 0,
font: OnceLock::new(),
},
];
fn face(font: FontFace) -> &'static PdfFace {
&FACES[font as usize]
}
fn face_font(face: &'static PdfFace) -> &'static Font<'static> {
face.font
.get_or_init(|| Font::from_bytes(face.bytes).expect("embedded face"))
}
fn glyph_hex(face: &'static PdfFace, text: &str) -> String {
let font = face_font(face);
let mut out = String::new();
for character in text.chars() {
let id = font.glyph(character).id().0;
@@ -28,8 +69,8 @@ fn glyph_hex(text: &str) -> String {
out
}
fn tounicode_cmap() -> Vec<u8> {
let font = serif();
fn tounicode_cmap(face: &'static PdfFace) -> 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",
);
@@ -43,6 +84,32 @@ fn tounicode_cmap() -> Vec<u8> {
map.into_bytes()
}
fn cid_widths(face: &'static PdfFace) -> String {
let font = face_font(face);
let units = font.units_per_em() as f32;
let scale = 1000.0 / units;
let mut entries = Vec::new();
for character in (0x20u8..=0x7e).map(char::from) {
let glyph = font.glyph(character);
let id = glyph.id().0;
let width = (glyph
.scaled(rusttype::Scale::uniform(units))
.h_metrics()
.advance_width
* scale)
.round() as i64;
entries.push((id, width));
}
entries.sort_unstable();
entries.dedup_by_key(|(id, _)| *id);
let mut out = String::from("[");
for (id, width) in entries {
out.push_str(&format!(" {id} [{width}]"));
}
out.push_str(" ]");
out
}
fn escape(text: &str) -> String {
let mut out = String::new();
for character in text.chars() {
@@ -62,19 +129,9 @@ fn pt(value: i64) -> String {
format!("{:.3}", value as f64 / 65_536.0)
}
fn font_base(font: FontFace) -> &'static str {
match font {
FontFace::Roman => "Times-Roman",
FontFace::Bold => "Times-Bold",
FontFace::Italic => "Times-Italic",
FontFace::BoldItalic => "Times-BoldItalic",
FontFace::Mono => "Courier",
}
}
fn font_resource(font: FontFace) -> &'static str {
match font {
FontFace::Roman => "F6",
FontFace::Roman => "F1",
FontFace::Bold => "F2",
FontFace::Italic => "F3",
FontFace::BoldItalic => "F4",
@@ -99,11 +156,7 @@ fn page_content(list: &DisplayList, height: i64, image_names: &BTreeMap<usize, S
pt(*size),
pt(*x),
pt(height - *y),
if *font == FontFace::Roman {
format!("<{}>", glyph_hex(text))
} else {
format!("({})", escape(text))
}
format!("<{}>", glyph_hex(face(*font), text))
));
}
DisplayItem::Rule {
@@ -177,61 +230,51 @@ pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8>
let mut objects: Vec<Vec<u8>> = Vec::new();
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
objects.push(Vec::new()); // pages object filled below
for font in [
FontFace::Roman,
FontFace::Bold,
FontFace::Italic,
FontFace::BoldItalic,
FontFace::Mono,
] {
let mut font_ids = [0usize; 5];
for (slot, face) in FACES.iter().enumerate() {
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;
font_ids[slot] = type0_id;
let base = face.base;
objects.push(
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} >>",
font_base(font)
"<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>"
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 1000 /W {} >>",
cid_widths(face)
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{base} /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle {} /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>",
face.italic_angle
)
.into_bytes(),
);
let mut font_stream = format!(
"<< /Length {} /Length1 {} >>\nstream\n",
face.bytes.len(),
face.bytes.len()
)
.into_bytes();
font_stream.extend_from_slice(face.bytes);
font_stream.extend_from_slice(b"\nendstream");
objects.push(font_stream);
let cmap = tounicode_cmap(face);
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);
}
// 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();
@@ -250,7 +293,10 @@ 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 = 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 fonts = format!(
"/F1 {} 0 R /F2 {} 0 R /F3 {} 0 R /F4 {} 0 R /F5 {} 0 R",
font_ids[0], font_ids[1], font_ids[2], font_ids[3], font_ids[4]
);
let resources = if used.is_empty() {
format!("<< /Font << {fonts} >> >>")
} else {