Add a minimal PDF writer for route-D display lists

This commit is contained in:
gloamxun committed 2026-10-20 18:09:55 +08:00
1 parent 946f8b1b76
commit b6fab85f61
3 files changed
+113

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
//! Minimal single-page PDF writer for route-D display lists.
//!
//! This is intentionally small: Base-14 Times-Roman for text, filled
//! rectangles for rules. It proves the display-list -> PDF path before the
//! real NFSS/TFM font backend and XObject support arrive.
use crate::render::{DisplayItem, DisplayList};
fn escape(text: &str) -> String {
let mut out = String::new();
for character in text.chars() {
match character {
'(' => out.push_str("\\("),
')' => out.push_str("\\)"),
'\\' => out.push_str("\\\\"),
c if c.is_ascii() => out.push(c),
_ => out.push('?'),
}
}
out
}
fn pt(value: i64) -> String {
format!("{:.3}", value as f64 / 65_536.0)
}
/// Write one page. The media box is at least US Letter.
pub fn display_list_to_pdf(list: &DisplayList, page_height: i64) -> Vec<u8> {
let width = list.width.max(612 * 65_536);
let height = page_height.max(792 * 65_536);
let mut content = String::from("q\n0 0 0 rg\n");
for item in &list.items {
match item {
DisplayItem::Text { x, y, size, text } => {
content.push_str(&format!(
"BT /F1 {} Tf 1 0 0 1 {} {} Tm ({}) Tj ET\n",
pt(*size),
pt(*x),
pt(height - *y),
escape(text)
));
}
DisplayItem::Rule {
x,
y,
width,
height: rule_height,
} => {
content.push_str(&format!(
"{} {} {} {} re f\n",
pt(*x),
pt(height - *y - *rule_height),
pt(*width),
pt(*rule_height)
));
}
}
}
content.push_str("Q\n");
let objects = vec![
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>".to_string(),
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /Font << /F1 3 0 R >> >> /Contents 5 0 R >>",
pt(width),
pt(height)
),
format!(
"<< /Length {} >>\nstream\n{}endstream",
content.len(),
content
),
];
let mut pdf = String::from("%PDF-1.4\n");
let mut offsets = Vec::new();
for (index, object) in objects.iter().enumerate() {
offsets.push(pdf.len());
pdf.push_str(&format!("{} 0 obj\n{}\nendobj\n", index + 1, object));
}
let xref = pdf.len();
pdf.push_str(&format!(
"xref\n0 {}\n0000000000 65535 f \n",
objects.len() + 1
));
for offset in &offsets {
pdf.push_str(&format!("{:010} 00000 n \n", offset));
}
pdf.push_str(&format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
xref
));
pdf.into_bytes()
}