Add per-face PDF font resources

This commit is contained in:
gloamxun committed 2026-10-20 18:27:14 +08:00
1 parent 03025de783
commit d40595c7e5
5 files changed
+91 -9

No files matched your search

+48 -6
View File
@@ -5,7 +5,7 @@
use std::collections::BTreeMap;
use crate::render::{DisplayItem, DisplayList};
use crate::render::{DisplayItem, DisplayList, FontFace};
fn escape(text: &str) -> String {
let mut out = String::new();
@@ -25,13 +25,40 @@ 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 => "F1",
FontFace::Bold => "F2",
FontFace::Italic => "F3",
FontFace::BoldItalic => "F4",
FontFace::Mono => "F5",
}
}
fn page_content(list: &DisplayList, height: i64, image_names: &BTreeMap<usize, String>) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
for item in &list.items {
match item {
DisplayItem::Text { x, y, size, text } => {
DisplayItem::Text {
x,
y,
size,
text,
font,
} => {
content.push_str(&format!(
"BT /F1 {} 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),
@@ -93,7 +120,21 @@ 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
objects.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>".to_vec());
for font in [
FontFace::Roman,
FontFace::Bold,
FontFace::Italic,
FontFace::BoldItalic,
FontFace::Mono,
] {
objects.push(
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} >>",
font_base(font)
)
.into_bytes(),
);
}
let mut kids = Vec::new();
for list in pages {
@@ -113,10 +154,11 @@ 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 resources = if used.is_empty() {
"<< /Font << /F1 3 0 R >> >>".to_string()
format!("<< /Font << {fonts} >> >>")
} else {
format!("<< /Font << /F1 3 0 R >> /XObject << {xobjects} >> >>")
format!("<< /Font << {fonts} >> /XObject << {xobjects} >> >>")
};
let links = list
.items