442 lines
14 KiB
Rust
Executable File
442 lines
14 KiB
Rust
Executable File
//! Minimal PDF writer for route-D display lists.
|
|
//!
|
|
//! Embedded true-type text 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};
|
|
|
|
struct PdfFace {
|
|
bytes: &'static [u8],
|
|
base: &'static str,
|
|
italic_angle: i32,
|
|
font: OnceLock<Font<'static>>,
|
|
}
|
|
|
|
static FACES: [PdfFace; 6] = [
|
|
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(),
|
|
},
|
|
PdfFace {
|
|
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSans-Regular.ttf"),
|
|
base: "LiberationSans",
|
|
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;
|
|
out.push_str(&format!("{id:04X}"));
|
|
}
|
|
out
|
|
}
|
|
|
|
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",
|
|
);
|
|
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 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() {
|
|
match character {
|
|
'(' => out.push_str("\\("),
|
|
')' => out.push_str("\\)"),
|
|
'\\' => out.push_str("\\\\"),
|
|
c if c.is_ascii() => out.push(c),
|
|
c if (c as u32) <= 0xFF => out.push_str(&format!("\\{:03o}", c as u32)),
|
|
_ => out.push('?'),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
fn pt(value: i64) -> String {
|
|
format!("{:.3}", value as f64 / 65_536.0)
|
|
}
|
|
|
|
fn font_resource(font: FontFace) -> &'static str {
|
|
match font {
|
|
FontFace::Roman => "F1",
|
|
FontFace::Bold => "F2",
|
|
FontFace::Italic => "F3",
|
|
FontFace::BoldItalic => "F4",
|
|
FontFace::Mono => "F5",
|
|
FontFace::Sans => "F6",
|
|
}
|
|
}
|
|
|
|
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,
|
|
font,
|
|
} => {
|
|
content.push_str(&format!(
|
|
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
|
|
font_resource(*font),
|
|
pt(*size),
|
|
pt(*x),
|
|
pt(height - *y),
|
|
format!("<{}>", glyph_hex(face(*font), 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)
|
|
));
|
|
}
|
|
DisplayItem::Line {
|
|
x1,
|
|
y1,
|
|
x2,
|
|
y2,
|
|
width: line_width,
|
|
} => {
|
|
content.push_str(&format!(
|
|
"{} w {} {} m {} {} l S\n",
|
|
pt(*line_width),
|
|
pt(*x1),
|
|
pt(height - *y1),
|
|
pt(*x2),
|
|
pt(height - *y2)
|
|
));
|
|
}
|
|
DisplayItem::Image {
|
|
x,
|
|
y,
|
|
width,
|
|
height: image_height,
|
|
index,
|
|
} => {
|
|
if let Some(name) = image_names.get(index) {
|
|
content.push_str(&format!(
|
|
"q {} 0 0 {} {} {} cm /{name} Do Q\n",
|
|
pt(*width),
|
|
pt(*image_height),
|
|
pt(*x),
|
|
pt(height - *y - *image_height)
|
|
));
|
|
}
|
|
}
|
|
DisplayItem::Link { .. } => {}
|
|
DisplayItem::Special(special) => {
|
|
content.push_str(special);
|
|
content.push('\n');
|
|
}
|
|
}
|
|
}
|
|
content.push_str("Q\n");
|
|
content
|
|
}
|
|
|
|
/// Write several display lists as a multi-page PDF.
|
|
pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8> {
|
|
let height = page_height.max(792 * 65_536);
|
|
let width = pages
|
|
.iter()
|
|
.map(|page| page.width)
|
|
.max()
|
|
.unwrap_or(612 * 65_536)
|
|
.max(612 * 65_536);
|
|
|
|
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
|
|
let mut font_ids = [0usize; 6];
|
|
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 /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);
|
|
}
|
|
|
|
let mut kids = Vec::new();
|
|
for list in pages {
|
|
let mut used = BTreeMap::new();
|
|
for item in &list.items {
|
|
if let DisplayItem::Image { index, .. } = item {
|
|
let next = used.len();
|
|
used.entry(*index).or_insert(next);
|
|
}
|
|
}
|
|
|
|
let page_id = objects.len() + 1;
|
|
let content_id = page_id + 1;
|
|
let image_base = content_id + 1;
|
|
let xobjects = used
|
|
.iter()
|
|
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
|
|
.collect::<Vec<_>>()
|
|
.join(" ");
|
|
let fonts = format!(
|
|
"/F1 {} 0 R /F2 {} 0 R /F3 {} 0 R /F4 {} 0 R /F5 {} 0 R /F6 {} 0 R",
|
|
font_ids[0], font_ids[1], font_ids[2], font_ids[3], font_ids[4], font_ids[5]
|
|
);
|
|
let resources = if used.is_empty() {
|
|
format!("<< /Font << {fonts} >> >>")
|
|
} else {
|
|
format!("<< /Font << {fonts} >> /XObject << {xobjects} >> >>")
|
|
};
|
|
let links = list
|
|
.items
|
|
.iter()
|
|
.filter_map(|item| match item {
|
|
DisplayItem::Link {
|
|
x,
|
|
y,
|
|
width,
|
|
height,
|
|
url,
|
|
} => Some((*x, *y, *width, *height, url.clone())),
|
|
_ => None,
|
|
})
|
|
.collect::<Vec<_>>();
|
|
let annotation_base = image_base + used.len();
|
|
let annots = if links.is_empty() {
|
|
String::new()
|
|
} else {
|
|
let refs = (0..links.len())
|
|
.map(|index| {
|
|
format!("/Annots [{}]", (annotation_base + index))
|
|
.replace("/Annots [", "")
|
|
.replacen("]", "", 1)
|
|
})
|
|
.collect::<Vec<_>>()
|
|
.join(" ");
|
|
format!(" /Annots [{refs}]")
|
|
};
|
|
kids.push(format!("{page_id} 0 R"));
|
|
objects.push(
|
|
format!(
|
|
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources}{annots} /Contents {content_id} 0 R >>",
|
|
pt(width),
|
|
pt(height)
|
|
)
|
|
.into_bytes(),
|
|
);
|
|
|
|
let mut names = BTreeMap::new();
|
|
for (index, slot) in &used {
|
|
names.insert(*index, format!("Im{slot}"));
|
|
}
|
|
let content = page_content(list, height, &names);
|
|
objects.push(
|
|
format!(
|
|
"<< /Length {} >>\nstream\n{}endstream",
|
|
content.len(),
|
|
content
|
|
)
|
|
.into_bytes(),
|
|
);
|
|
|
|
for (index, _) in &used {
|
|
let image = &list.images[*index];
|
|
let mut object = format!(
|
|
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Length {} >>\nstream\n",
|
|
image.width,
|
|
image.height,
|
|
image.rgb.len()
|
|
)
|
|
.into_bytes();
|
|
object.extend_from_slice(&image.rgb);
|
|
object.extend_from_slice(b"\nendstream");
|
|
objects.push(object);
|
|
}
|
|
|
|
for (index, (x, y, width, link_height, url)) in links.iter().enumerate() {
|
|
let _ = index;
|
|
objects.push(
|
|
format!(
|
|
"<< /Type /Annot /Subtype /Link /Rect [{:.3} {:.3} {:.3} {:.3}] /Border [0 0 0] /A << /S /URI /URI ({}) >> >>",
|
|
*x as f64 / 65_536.0,
|
|
(height as f64 - *y as f64 - *link_height as f64) / 65_536.0,
|
|
(*x + *width) as f64 / 65_536.0,
|
|
(height as f64 - *y as f64) / 65_536.0,
|
|
escape(url)
|
|
)
|
|
.into_bytes(),
|
|
);
|
|
}
|
|
}
|
|
objects[1] = format!(
|
|
"<< /Type /Pages /Kids [{}] /Count {} >>",
|
|
kids.join(" "),
|
|
pages.len()
|
|
)
|
|
.into_bytes();
|
|
|
|
let mut pdf: Vec<u8> = b"%PDF-1.4\n".to_vec();
|
|
let mut offsets = Vec::new();
|
|
for (index, object) in objects.iter().enumerate() {
|
|
offsets.push(pdf.len());
|
|
pdf.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes());
|
|
pdf.extend_from_slice(object);
|
|
pdf.extend_from_slice(b"\nendobj\n");
|
|
}
|
|
let xref = pdf.len();
|
|
pdf.extend_from_slice(
|
|
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
|
|
);
|
|
for offset in &offsets {
|
|
pdf.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
|
|
}
|
|
pdf.extend_from_slice(
|
|
format!(
|
|
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
|
|
objects.len() + 1,
|
|
xref
|
|
)
|
|
.as_bytes(),
|
|
);
|
|
pdf
|
|
}
|
|
|
|
/// Write one page; kept for the single-page spike and tests.
|
|
pub fn display_list_to_pdf(list: &DisplayList, page_height: i64) -> Vec<u8> {
|
|
display_lists_to_pdf(std::slice::from_ref(list), page_height)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::escape;
|
|
|
|
#[test]
|
|
fn latin1_text_is_octal_escaped_in_the_content_stream() {
|
|
assert_eq!(escape("café"), "caf\\351");
|
|
assert_eq!(escape("über"), "\\374ber");
|
|
assert_eq!(escape("中文"), "??");
|
|
}
|
|
}
|