//! 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::collections::BTreeSet; use std::io::Write as _; use std::sync::OnceLock; use flate2::Compression; use flate2::write::ZlibEncoder; use rusttype::Font; use crate::cmr10::Cmr10Metrics; use crate::render::{DisplayItem, DisplayList, FontFace}; fn deflate(bytes: &[u8]) -> Vec { let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); encoder.write_all(bytes).expect("deflate font stream"); encoder.finish().expect("finish font stream") } struct PdfFace { bytes: &'static [u8], base: &'static str, italic_angle: i32, font: OnceLock>, } static FULL_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(), }, ]; static MIN_FACES: [PdfFace; 6] = [ PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Bold.ttf"), base: "LiberationSerif-Bold", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"), base: "LiberationSerif-Italic", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-BoldItalic.ttf"), base: "LiberationSerif-BoldItalic", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationMono-Regular.ttf"), base: "LiberationMono", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSans-Regular.ttf"), base: "LiberationSans", italic_angle: 0, font: OnceLock::new(), }, ]; fn minimal_text_char(ch: char) -> bool { ch.is_ascii() || matches!( ch, '\u{00A0}' | '\u{00A9}' | '\u{00AE}' | '\u{00B0}' | '\u{00B1}' | '\u{00B5}' | '\u{00B7}' | '\u{00D7}' | '\u{2013}' | '\u{2014}' | '\u{2018}' | '\u{2019}' | '\u{201C}' | '\u{201D}' | '\u{2022}' | '\u{2026}' | '\u{00B9}' | '\u{00B2}' | '\u{00B3}' | '\u{2070}'..='\u{2079}' | '\u{2248}' | '\u{223C}' | '\u{03BC}' ) } fn face(font: FontFace, faces: &'static [PdfFace; 6]) -> &'static PdfFace { &faces[font as usize] } #[allow(dead_code)] pub(crate) fn full_face_size(font: FontFace) -> usize { FULL_FACES[font as usize].bytes.len() } 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, characters: &BTreeSet) -> Vec { 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> \nendcodespacerange\n", ); let mut entries = std::collections::BTreeMap::new(); for character in characters { if (*character as u32) <= 0xffff { entries.insert(font.glyph(*character).id().0, *character); } } map.push_str(&format!("{} beginbfchar\n", entries.len())); for (id, character) in entries { 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, slot: usize, used: &std::collections::BTreeSet, ) -> String { let font = face_font(face); let metrics = Cmr10Metrics::for_pdf_slot(slot); let mut entries = Vec::new(); let mut characters = used.clone(); characters.extend((0x20u8..=0x7e).map(char::from)); for character in characters { if character.is_control() { continue; } let glyph = font.glyph(character); let id = glyph.id().0; let width = metrics.width(character) * 1000 / (10 * 65_536); 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, faces: &'static [PdfFace; 6], ) -> 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, faces), 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 { 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::new(); objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()); objects.push(Vec::new()); // pages object filled below let mut used_faces = [false; 6]; let mut used_chars: [BTreeSet; 6] = Default::default(); for page in pages { for item in &page.items { if let DisplayItem::Text { font, text, .. } = item { used_faces[*font as usize] = true; used_chars[*font as usize].extend(text.chars()); } } } let minimal = pages.iter().all(|page| { page.items.iter().all(|item| match item { DisplayItem::Text { text, .. } => text.chars().all(minimal_text_char), _ => true, }) }); let faces: &'static [PdfFace; 6] = if minimal { &MIN_FACES } else { &FULL_FACES }; let mut font_ids = [0usize; 6]; for (slot, face) in faces.iter().enumerate() { if !used_faces[slot] { continue; } 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 500 /W {} >>", cid_widths(face, slot, &used_chars[slot]) ) .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 font_bytes = crate::subset::subset_font(face.bytes, face_font(face), &used_chars[slot]); let compressed = deflate(&font_bytes); let mut font_stream = format!( "<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n", compressed.len(), font_bytes.len() ) .into_bytes(); font_stream.extend_from_slice(&compressed); font_stream.extend_from_slice(b"\nendstream"); objects.push(font_stream); let cmap = tounicode_cmap(face, &used_chars[slot]); let compressed_cmap = deflate(&cmap); let mut cmap_object = format!( "<< /Length {} /Filter /FlateDecode >>\nstream\n", compressed_cmap.len() ) .into_bytes(); cmap_object.extend_from_slice(&compressed_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::>() .join(" "); let fonts = (0..6) .filter(|slot| used_faces[*slot]) .map(|slot| format!("/F{} {} 0 R", slot + 1, font_ids[slot])) .collect::>() .join(" "); 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::>(); 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::>() .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, faces); 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 = 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 { display_lists_to_pdf(std::slice::from_ref(list), page_height) } #[cfg(test)] mod tests { use super::{FULL_FACES, cid_widths, escape, face_font}; use std::collections::BTreeSet; #[test] fn widths_cover_used_latin1_characters() { let face = &FULL_FACES[0]; let accent = char::from_u32(0xe9).unwrap(); let id = face_font(face).glyph(accent).id().0; let mut used = BTreeSet::new(); used.insert(accent); let widths = cid_widths(face, 0, &used); assert!(widths.contains(&format!("{id} [500]")), "{widths}"); } #[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("中文"), "??"); } }