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

Generated
+1
View File
@@ -966,6 +966,7 @@ name = "texrra-tex-core"
version = "0.1.0"
dependencies = [
"hyphenate",
"rusttype",
"serde",
"serde_json",
]
+1
View File
@@ -6,6 +6,7 @@ license = "MIT OR Apache-2.0"
description = "Experimental incremental TeX-compatible typesetting core (route D)"
[dependencies]
rusttype = "0.8.3"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
hyphenate = { path = "../../vendor/hyphenate" }
+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 {
+4 -5
View File
@@ -229,7 +229,7 @@ for a later overlaid slash.
| M2 vertical/page builder | partial | vsize, topskip, insertions, marks, output hook, top/bottom floats, rules, vskip, penalties; interpreted `\output` and float pages absent |
| M3 halign | partial | natural columns, spans, omit, hline rows, templates, noalign skip, rules; no PDF painter |
| M4 math | partial | atoms, scripts, fractions, roots, delimiters, accents, operators, classes, braces, boxed, negated; no math painter/shrink wrapping |
| M5 NFSS/TFM | partial | CMR10 widths, per-face Base-14 PDF resources, and SVG font-family/weight/style for Roman/Bold/Italic/Mono; paragraph units carry a ParagraphFont face; embedded `cmr10.tfm` is parsed at runtime for widths/height/depth, but PDF font embedding and real NFSS families are absent |
| M5 NFSS/TFM | partial | runtime `cmr10.tfm` widths/heights/depths; Roman text embeds Liberation Serif as a Type0 CID font with Identity-H and ToUnicode; Bold/Italic/Mono still use Base-14 faces; SVG carries family/weight/style |
| M6 specials/XObject | partial | raw specials, RGB image XObjects, URI link annotations; class/package execution absent |
| M7 incremental integration | partial | edit replay + page hashes, not wired into v1 preview |
@@ -249,9 +249,9 @@ v1 remains the production renderer; the route-D core is additive and tested inde
M3 painter: `Page::display_list()` and `Halign::display_list()` produce absolute text, rule and line primitives. `DisplayList::to_svg()` writes a standalone SVG; paragraph glyphs and math atoms are painted at their measured positions.
PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with Base-14 Times/Courier resources, filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. TFM/NFSS embedded fonts remain open.
PDF writer: `crates/texrra-tex-core/src/pdf.rs` writes multi-page PDF 1.4 with an embedded Liberation Serif Type0/CID font (Identity-H + ToUnicode) for Roman text, Base-14 faces for the other styles, filled rectangles, diagonal rules, raw-RGB `/XObject` images, `/Annots` URI links and arbitrary `/special` operators. Real NFSS faces and subsets for bold/italic remain open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`; PDF resources map them to Times and Courier faces, and SVG emits matching family/weight/style. The embedded `cmr10.tfm` is parsed at runtime; PDF font embedding, ligature/kern tables and real NFSS families are still open.
M5 (partial): display-list text carries `FontFace::{Roman,Bold,Italic,BoldItalic,Mono}`. Roman text is painted with an embedded Liberation Serif Type0/CID font and a ToUnicode CMap; the other faces still map to Base-14 Times/Courier. `cmr10.tfm` is parsed at runtime for widths and heights/depths; ligature/kern tables and true NFSS family switching remain open.
M6 (partial): `DisplayItem::Image` becomes a PDF XObject; `DisplayItem::Link` becomes `/Annots /Subtype /Link /URI`; `DisplayItem::Special` injects raw content-stream operators. SVG previews show images as grey rectangles and specials as comments.
@@ -288,8 +288,7 @@ deliberately open rather than approximated:
- **M1**: TeX tolerance/demerits are still fitted to a few fixtures; multi-width
pdfTeX line breaks and full hyphenation demerits are not reproduced generally.
- **M5**: `cmr10.tfm` is parsed at runtime with widths and glyph heights/depths, but embedded NFSS fonts are not implemented. Display-list text
uses Base-14 Times/Courier faces; Unicode coverage beyond Latin-1 is limited.
- **M5**: `cmr10.tfm` is parsed at runtime with widths and glyph heights/depths. Roman text embeds Liberation Serif as Type0/Identity-H, but bold/italic/mono still use Base-14 faces; ligature/kern tables and full NFSS family switching are not implemented.
- **M6**: `\output`, `\insert`, mark/float output policies, class-file execution and
math limit policies are only partially modeled.
- **M7**: the route-D engine is not yet wired into the v1 live preview. The server