//! Minimal PDF writer for route-D display lists. //! //! Embedded true-type text faces, filled rectangles, //! and raw-RGB image XObjects. use std::collections::BTreeSet; use std::collections::{BTreeMap, HashMap, HashSet}; 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}; use crate::type1::Type1Font; #[path = "pdf_text.rs"] mod native_text; #[path = "pdf_objects.rs"] mod objects; #[path = "pdf_pk.rs"] mod pk_fonts; const FACE_COUNT: usize = 17; 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; FACE_COUNT] = [ 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(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"), base: "LiberationSerif-MathItalic", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathSymbol", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathExtension", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathBlackboard", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathFraktur", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSans-Bold.ttf"), base: "LiberationSans-Bold", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSans-Italic.ttf"), base: "LiberationSans-Italic", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"), base: "LiberationSerif-SmallCaps", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"), base: "LiberationSerif-Slanted", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-BoldItalic.ttf"), base: "LiberationSerif-BoldSlanted", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset/LiberationMono-Italic.ttf"), base: "LiberationMono-Italic", italic_angle: -12, font: OnceLock::new(), }, ]; static MIN_FACES: [PdfFace; FACE_COUNT] = [ 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(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"), base: "LiberationSerif-MathItalic", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathSymbol", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathExtension", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathBlackboard", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif-MathFraktur", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSans-Bold.ttf"), base: "LiberationSans-Bold", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSans-Italic.ttf"), base: "LiberationSans-Italic", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"), base: "LiberationSerif-SmallCaps", italic_angle: 0, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"), base: "LiberationSerif-Slanted", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-BoldItalic.ttf"), base: "LiberationSerif-BoldSlanted", italic_angle: -12, font: OnceLock::new(), }, PdfFace { bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationMono-Italic.ttf"), base: "LiberationMono-Italic", italic_angle: -12, 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; FACE_COUNT]) -> &'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() } /// ToUnicode CMap for a single-byte Type1 font. Glyph names are ambiguous /// (`Omega` in the Adobe Glyph List is the ohm sign), so the requested /// characters are mapped explicitly. fn expanded_ligature_text(text: &str) -> String { text.chars() .map(|c| match c { 'ff' => "ff".into(), 'fi' => "fi".into(), 'fl' => "fl".into(), 'ffi' => "ffi".into(), 'ffl' => "ffl".into(), c => c.to_string(), }) .collect() } fn type1_tounicode(by_code: &BTreeMap) -> Vec { let texts = by_code .iter() .map(|(slot, c)| (*slot, expanded_ligature_text(&c.to_string()))) .collect(); type1_tounicode_texts(&texts) } fn type1_tounicode_texts(by_code: &BTreeMap) -> Vec { let hex = by_code .iter() .map(|(slot, text)| { ( *slot, text.encode_utf16().map(|n| format!("{n:04X}")).collect(), ) }) .collect(); type1_tounicode_hex(&hex) } fn type1_tounicode_hex(by_code: &BTreeMap) -> Vec { 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\n1 begincodespacerange\n<00> \nendcodespacerange\n", ); let entries: Vec<_> = by_code.iter().collect(); for chunk in entries.chunks(100) { map.push_str(&format!("{} beginbfchar\n", chunk.len())); for (slot, text) in chunk { map.push_str(&format!("<{slot:02X}> <{text}>\n")); } map.push_str("endbfchar\n"); } map.push_str("endcmap\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) } /// Signed rounding for actual TFM dimensions in PDF font units. fn native_font_units(value: i64, size: i64, factor: i64) -> i64 { let n = value * factor; if n < 0 { -((-n + size / 2) / size) } else { (n + size / 2) / size } } fn native_pdf_font_size(size: i64) -> i64 { // pdf_use_font quantizes to 0.0001bp, then keeps divide_scaled's // scaled_out remainder. The declared widths use this effective TeX size. let denominator = 6_578_176; // 100bp in TeX sp, without a rounded 1bp. let mut remainder = (size * 1_000_000) % denominator; if remainder * 2 >= denominator { remainder -= denominator; } size - remainder / 1_000_000 } struct NativeTextRun { font: crate::execution::FontId, size: i64, y: i64, cursor: f64, point_size: f64, text: String, } impl NativeTextRun { fn flush(run: &mut Option, content: &mut String) { if let Some(run) = run.take() { content.push_str(&run.text); content.push_str("] TJ ET\n"); } } fn push(&mut self, x: f64, slot: u8, face: &crate::native_font::NativeFont) { // Advance by the declared rounded width, then consume the remaining // position difference through a real TJ adjustment. Per-glyph Tm // resets lose the pdfTeX profile's text-position quantization. let kern = if self.point_size == 0.0 { 0.0 } else { ((self.cursor - x) * 1000.0 / self.point_size).round() }; if kern != 0.0 { self.text.push_str(&format!(" {kern:.0} ")); } self.text.push_str(&format!("<{slot:02X}>")); let m = face.metrics(); let width = native_font_units( m.width(char::from(slot)), native_pdf_font_size(m.size_sp()), 10_000, ) as f64 / 10.0; self.cursor += (width - kern) * self.point_size / 1000.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", FontFace::MathItalic => "F7", FontFace::MathSymbol => "F8", FontFace::MathExtension => "F9", FontFace::MathBlackboard => "F10", FontFace::MathFraktur => "F11", FontFace::SansBold => "F12", FontFace::SansItalic => "F13", FontFace::SmallCaps => "F14", FontFace::Slanted => "F15", FontFace::BoldSlanted => "F16", FontFace::MonoItalic => "F17", } } /// Which outline format the PDF writer embeds for text. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum FontBackend { /// Embedded Liberation TrueType subsets (the default). TrueType, /// Knuth's Computer Modern Type1 programs when they cover the text. ComputerModern, } /// Knuth's Computer Modern Type1 programs, in `FontFace` order. fn type1_bytes(slot: usize) -> Option<&'static [u8]> { static PFBS: [Option<&'static [u8]>; FACE_COUNT] = [ Some(include_bytes!("../../../assets/fonts/cmr10.pfb")), Some(include_bytes!("../../../assets/fonts/cmbx10.pfb")), Some(include_bytes!("../../../assets/fonts/cmti10.pfb")), Some(include_bytes!("../../../assets/fonts/cmbxti10.pfb")), Some(include_bytes!("../../../assets/fonts/cmtt10.pfb")), Some(include_bytes!("../../../assets/fonts/cmss10.pfb")), Some(include_bytes!("../../../assets/fonts/cmmi10.pfb")), Some(include_bytes!("../../../assets/fonts/cmsy10.pfb")), Some(include_bytes!("../../../assets/fonts/cmex10.pfb")), Some(include_bytes!("../../../assets/fonts/msbm10.pfb")), Some(include_bytes!("../../../assets/fonts/eufm10.pfb")), Some(include_bytes!("../../../assets/fonts/cmssbx10.pfb")), Some(include_bytes!("../../../assets/fonts/cmssi10.pfb")), Some(include_bytes!("../../../assets/fonts/cmcsc10.pfb")), Some(include_bytes!("../../../assets/fonts/cmsl10.pfb")), Some(include_bytes!("../../../assets/fonts/cmbxsl10.pfb")), Some(include_bytes!("../../../assets/fonts/cmitt10.pfb")), ]; PFBS[slot] } fn type1_fonts() -> &'static [Option; FACE_COUNT] { static FONTS: OnceLock<[Option; FACE_COUNT]> = OnceLock::new(); FONTS .get_or_init(|| std::array::from_fn(|slot| type1_bytes(slot).and_then(Type1Font::from_pfb))) } /// TeX page origin offsets (`\hoffset`, `\voffset`) in scaled points. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct PageOrigin { pub h_offset: i64, pub v_offset: i64, } fn write_type0_font( objects: &mut Vec>, face: &'static PdfFace, slot: usize, used: &BTreeSet, ) -> usize { 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; 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) ) .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); 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); 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); type0_id } fn page_content( list: &DisplayList, height: i64, image_names: &BTreeMap, faces: &'static [PdfFace; FACE_COUNT], cm_codes: &[Option<&BTreeMap>], fallback_ids: &[usize; FACE_COUNT], origin: PageOrigin, ) -> String { let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits); let pt = |n: i64| { if list.units == crate::render::DisplayUnits::TeX { crate::pdf_device::print_sp(n, digits) } else { pt(n) } }; let mut content = String::from("q\n0 0 0 rg\n"); if list.magnification != 1000 { let ratio = f64::from(list.magnification) / 1000.0; content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n")); } if let Some(DisplayItem::Background(color)) = list.items.first() { content.push_str(&format!( "{:.3} {:.3} {:.3} rg\n0 0 {} {} re f\n0 0 0 rg\n", color[0] as f64 / 255.0, color[1] as f64 / 255.0, color[2] as f64 / 255.0, pt(list.width), pt(height) )); } if origin != PageOrigin::default() { content.push_str(&format!( "1 0 0 1 {} {} cm\n", pt(origin.h_offset), pt(-origin.v_offset) )); } let mut native_text: Option = None; let mut tex_text: Option = None; for item in &list.items { if list.units == crate::render::DisplayUnits::TeX { if let DisplayItem::NativeGlyph { x, y, font, slot, paint, .. } = item { assert!(paint.is_some(), "native glyph program must be resolved"); native_text::NativeText::glyph( &mut tex_text, &mut content, *x, *y, font, paint.as_ref().unwrap(), *slot, height, digits, ); continue; } native_text::NativeText::finish(&mut tex_text, &mut content); if let DisplayItem::Rule { x, y, width, height: rule_height, } = item { native_text::rule(&mut content, *x, *y, *width, *rule_height, height, digits); continue; } } if let Some(run) = &native_text { if run.point_size == 0.0 || !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && *size==run.size && *y==run.y) { NativeTextRun::flush(&mut native_text, &mut content); } } match item { DisplayItem::NativeGlyph { x, y, size, font, slot, paint, .. } => { assert!( paint.is_some(), "native font resources must be resolved before PDF output" ); let run = native_text.get_or_insert_with(|| { let point_size = native_font_units(font.size_sp(), 6_578_176, 1_000_000) as f64 / 10_000.0; NativeTextRun { font: font.id, size: *size, y: *y, cursor: pt(*x).parse().unwrap(), point_size, text: format!( "BT /N{} {point_size:.4} Tf 1 0 0 1 {} {} Tm [", font.id.index(), pt(*x), pt(height - *y) ), } }); run.push(list.units.bp(*x), *slot, font); } DisplayItem::MathGlyph { x, y, size, face, slot, .. } => { content.push_str(&format!( "BT /M{} {} Tf 1 0 0 1 {} {} Tm <{slot:02X}> Tj ET\n", face.0, pt(*size), pt(*x), pt(height - *y) )); } DisplayItem::Text { x, y, size, text, font, } => { let slot = *font as usize; let covered = cm_codes .get(slot) .and_then(|entry| entry.as_ref()) .filter(|codes| text.chars().all(|character| codes.contains_key(&character))); let (operand, resource) = match covered { Some(codes) => { let mut literal = String::from("("); for character in text.chars() { if let Some(code) = codes.get(&character) { literal.push_str(&format!("\\{:03o}", code)); } } literal.push(')'); (literal, font_resource(*font).to_string()) } None if fallback_ids[slot] != 0 => ( format!("<{}>", glyph_hex(face(*font, faces), text)), format!("T{}", slot + 1), ), None => ( format!("<{}>", glyph_hex(face(*font, faces), text)), font_resource(*font).to_string(), ), }; content.push_str(&format!( "BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n", resource, pt(*size), pt(*x), pt(height - *y), operand )); } DisplayItem::Background(_) => {} DisplayItem::Rect { x, y, width, height, color, } => { content.push_str(&format!( "{:.3} {:.3} {:.3} rg\n{} {} {} {} re f\n", color[0] as f64 / 255.0, color[1] as f64 / 255.0, color[2] as f64 / 255.0, pt(*x), pt(height - *y - *height), pt(*width), pt(*height) )); } 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::PdfImage { x, y, width, height: image_height, image, } => { let [sx, sy] = if list.units == crate::render::DisplayUnits::TeX { let [natural_width, natural_height] = image.image.natural; // pdfTeX out_image prints a six-decimal ratio of scaled // dimensions, while translation follows pdfdecimaldigits. let scale = |placed, natural| { let (coefficient, _) = crate::pdf_device::divide_scaled(placed, i64::from(natural), 6); crate::pdf_device::print_decimal(coefficient, 6) }; [ scale(*width, natural_width), scale(*image_height, natural_height), ] } else { let [natural_width, natural_height] = image.image.extent(); [ crate::pdf_image::real(list.units.bp(*width) / natural_width), crate::pdf_image::real(list.units.bp(*image_height) / natural_height), ] }; let name = image.id; content.push_str(&format!( "q {sx} 0 0 {sy} {} {} cm /PI{name} Do Q\n", pt(*x), pt(height - *y - *image_height) )); } DisplayItem::Frame { x, y, width, height, color, thickness, } => { content.push_str(&format!( "{:.3} {:.3} {:.3} RG\n{:.3} w\n{} {} {} {} re S\n0 0 0 RG\n1 w\n", color[0] as f64 / 255.0, color[1] as f64 / 255.0, color[2] as f64 / 255.0, *thickness as f64 / 65_536.0, pt(*x), pt(list.height - *y - *height), pt(*width), pt(*height) )); } DisplayItem::Link { .. } => {} DisplayItem::PdfImageObject(_) => {} DisplayItem::Fill([r, g, b]) => { content.push_str(&format!( "{:.3} {:.3} {:.3} rg\n", *r as f64 / 255.0, *g as f64 / 255.0, *b as f64 / 255.0 )); } DisplayItem::Special(special) => { content.push_str(special); content.push('\n'); } DisplayItem::PdfColor(program) => { content.push_str(program.literal()); content.push('\n'); } DisplayItem::PdfGraphics { x, y, operation } => { use crate::pdf_device::PdfGraphics; match operation { PdfGraphics::Save => content.push_str("q\n"), PdfGraphics::Restore { shift: [dx, dy] } => { content.push_str("Q\n"); if *dx != 0 || *dy != 0 { content.push_str(&format!("1 0 0 1 {} {} cm\n", pt(*dx), pt(-*dy))); } } PdfGraphics::Matrix(matrix) => { let point = |coordinate| { let displayed = pt(coordinate); displayed.parse::().expect("formatted PDF dimension") }; let [a, b, c, d, e, f] = matrix .about(point(*x), point(height - *y), false) .0 .map(crate::pdf_image::real); content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n")); } } } } } NativeTextRun::flush(&mut native_text, &mut content); native_text::NativeText::finish(&mut tex_text, &mut content); content.push_str("Q\n"); content } /// Document information written into the PDF Info dictionary. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct PdfMetadata { pub title: Option, pub author: Option, pub subject: Option, pub keywords: Option, pub outline: Vec, /// Border and colour for URI link annotations, when set. pub link_border: Option<[u8; 3]>, } /// One flat bookmark pointing at a page of the exported document. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PdfOutlineEntry { pub title: String, pub page: usize, /// Heading depth, with 1 as the top level. pub level: u8, } fn pdf_text(value: &str) -> String { if value.chars().all(|character| { (' '..='~').contains(&character) && character != '(' && character != ')' && character != '\\' }) { format!("({value})") } else { let mut text = String::from("'); text } } fn metadata_object(metadata: &PdfMetadata) -> Option { let mut fields = Vec::new(); if let Some(title) = &metadata.title { fields.push(format!("/Title {}", pdf_text(title))); } if let Some(author) = &metadata.author { fields.push(format!("/Author {}", pdf_text(author))); } if let Some(subject) = &metadata.subject { fields.push(format!("/Subject {}", pdf_text(subject))); } if let Some(keywords) = &metadata.keywords { fields.push(format!("/Keywords {}", pdf_text(keywords))); } if fields.is_empty() { return None; } fields.push("/Producer (texrra route-D)".to_string()); fields.push("/Creator (texrra route-D)".to_string()); Some(format!("<< {} >>", fields.join(" "))) } /// Write several display lists as a multi-page PDF at the default page origin. pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec { display_lists_to_pdf_with_origin(pages, page_height, PageOrigin::default()) } /// Write several display lists as a multi-page PDF, translating the page body /// by TeX page origin offsets. pub fn display_lists_to_pdf_with_origin( pages: &[DisplayList], page_height: i64, origin: PageOrigin, ) -> Vec { display_lists_to_pdf_with_paper( pages, pages .iter() .map(|page| page.width) .max() .unwrap_or(612 * 65_536) .max(612 * 65_536), page_height.max(792 * 65_536), origin, ) } /// Write several display lists as a multi-page PDF with an explicit paper /// size (TeX `\paperwidth`/`\paperheight`) and page origin offsets. pub fn display_lists_to_pdf_with_paper( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, ) -> Vec { write_pdf( pages, page_width, page_height, origin, FontBackend::TrueType, &PdfMetadata::default(), None, None, &mut Vec::new(), ) } fn descendant_count(children: &HashMap>, node: usize) -> usize { children .get(&node) .map(|kids| { kids.iter() .map(|kid| 1 + descendant_count(children, *kid)) .sum() }) .unwrap_or(0) } /// Write PDFs with Knuth's Computer Modern Type1 outlines whenever the programs /// cover the text, falling back to Liberation TrueType for other characters. pub fn display_lists_to_pdf_with_cm_type1( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, ) -> Vec { write_pdf( pages, page_width, page_height, origin, FontBackend::ComputerModern, &PdfMetadata::default(), None, None, &mut Vec::new(), ) } /// Strict token-kernel output: every glyph has its measured native resource /// and an actual resolved program. A legacy text/family node is an error; /// it cannot enter the AST painter's font selection or replacement path. pub fn display_lists_to_native_pdf( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, ) -> Result, String> { native_pdf(pages, page_width, page_height, origin, None, None).map(|document| document.bytes) } /// A complete native export, including diagnostics produced by font writing. #[derive(Debug)] pub struct NativePdfDocument { pub bytes: Vec, pub diagnostics: Vec, } /// Native job output uses each actual shipout's captured canvas and scale. /// Use the document form when the caller owns a diagnostic sink. pub fn shipout_lists_to_native_pdf( pages: &[DisplayList], options: crate::pdf_unicode::PdfFinalOptions<'_>, ) -> Result, String> { shipout_lists_to_native_pdf_document(pages, options).map(|document| document.bytes) } pub fn shipout_lists_to_native_pdf_document( pages: &[DisplayList], options: crate::pdf_unicode::PdfFinalOptions<'_>, ) -> Result { native_pdf( pages, 0, 0, PageOrigin::default(), Some(options.compression), Some(options), ) } fn native_pdf( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, final_compression: Option, unicode: Option>, ) -> Result { let mut fonts = BTreeMap::new(); if final_compression.is_some() && pages.is_empty() { return Err("no native PDF shipouts".into()); } for page in pages { if final_compression.is_some() { let p = page .pdf .as_ref() .ok_or("native DVI output cannot be exported by the PDF driver")?; if p.file.major < 1 || p.file.minor > 9 || p.file.object_compression > 3 || p.file.decimal_digits > 4 || p.stream_compression > 9 || !(72..=8000).contains(&p.file.pk_resolution) || (p.file.major == 1 && p.file.minor < 5 && p.file.object_compression > 0) { return Err("invalid captured native PDF file options".into()); } if page.units != crate::render::DisplayUnits::TeX { return Err("native PDF requires original TeX sp coordinates".into()); } if let Some(first) = pages.first().and_then(|p| p.pdf.as_ref()) { if first.file != p.file { return Err("inconsistent native PDF file options".into()); } } } if !(1..=32768).contains(&page.magnification) { return Err("invalid native page magnification".into()); } for item in &page.items { match item { DisplayItem::Text {..} | DisplayItem::MathGlyph {..} => return Err("native PDF requires actual native font snapshots, not legacy text or master glyphs".into()), DisplayItem::NativeGlyph {font,slot,paint,..} => { if native_pdf_font_size(font.metrics().size_sp()) <= 0 { return Err("native PDF font size rounds to zero in the pdfTeX profile".into()); } let paint=paint.as_ref().ok_or_else(||format!("native font {} has no resolved output program",font.name))?; if page.units != crate::render::DisplayUnits::TeX && matches!(paint.program,crate::native_font::NativeFontProgram::Pk(_)) { return Err("native PK PDF requires actual shipout device coordinates".into()); } if paint.encoding.len()!=256 || paint.encoding[*slot as usize]==".notdef" || !paint.glyph_paths.contains_key(slot) || !font.has_slot(*slot) { return Err(format!("native font {} has no output encoding for slot {slot}",font.name)); } if let Some((old_font,old_paint))=fonts.insert(font.id,(font,paint)) { if old_font != font || old_paint != paint { return Err("inconsistent native font snapshots or programs in PDF output".into()); } } } _=>{}, } } } if final_compression.is_some_and(|level| level > 9) && (!fonts.is_empty() || pages .first() .and_then(|p| p.pdf.as_ref()) .is_some_and(|p| p.file.object_compression > 0)) { return Err("invalid native PDF final stream compression level".into()); } let mut diagnostics = Vec::new(); let bytes = write_pdf( pages, page_width, page_height, origin, FontBackend::ComputerModern, &PdfMetadata::default(), final_compression, unicode, &mut diagnostics, ); Ok(NativePdfDocument { bytes, diagnostics }) } /// Write PDFs with Liberation TrueType outlines and a document Info dictionary. pub fn display_lists_to_pdf_with_truetype_and_metadata( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, metadata: &PdfMetadata, ) -> Vec { write_pdf( pages, page_width, page_height, origin, FontBackend::TrueType, metadata, None, None, &mut Vec::new(), ) } /// Write PDFs with Computer Modern Type1 outlines and a document Info dictionary. pub fn display_lists_to_pdf_with_cm_type1_and_metadata( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, metadata: &PdfMetadata, ) -> Vec { write_pdf( pages, page_width, page_height, origin, FontBackend::ComputerModern, metadata, None, None, &mut Vec::new(), ) } fn write_math_font( objects: &mut Vec>, face: crate::math_font::MathFontId, used: &BTreeMap, ) -> usize { let font = face.type1(); let id = objects.len() + 1; let descriptor = id + 1; let program = id + 2; let unicode = id + 3; let first = *used.keys().next().expect("used math font"); let last = *used.keys().next_back().unwrap(); let widths = (first..=last) .map(|slot| { format!( "{:.3}", face.metrics().width(char::from(slot)) as f64 * 1000.0 / face.design_size() as f64 ) }) .collect::>() .join(" "); objects.push(format!( "<< /Type /Font /Subtype /Type1 /BaseFont /{} /FirstChar {first} /LastChar {last} /Widths [{widths}] /FontDescriptor {descriptor} 0 R /ToUnicode {unicode} 0 R >>", font.name ).into_bytes()); let [left, bottom, right, top] = font.bbox; // FontBBox is an outline bound, not the Latin ascender/descender used by // text selection. Derive these from the actual optical master's TFM. let (ascent, descent, cap_height) = if matches!( face.family(), crate::math_engine_tex::MathFont::Roman | crate::math_engine_tex::MathFont::Italic ) { let m = face.metrics(); let em = face.design_size(); let units = |n: i64| (n * 1000 + em / 2) / em; ( units(m.height('d')), -units(m.depth('p')), units(m.height('H')), ) } else { (top as i64, bottom as i64, top as i64) }; objects.push(format!( "<< /Type /FontDescriptor /FontName /{} /Flags 4 /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle 0 /Ascent {ascent} /Descent {descent} /CapHeight {cap_height} /StemV 69 /FontFile {program} 0 R >>", font.name ).into_bytes()); let mut stream = format!( "<< /Length {} /Length1 {} /Length2 {} /Length3 {} >>\nstream\n", font.program.len(), font.length1, font.length2, font.length3 ) .into_bytes(); stream.extend_from_slice(&font.program); stream.extend_from_slice(b"\nendstream"); objects.push(stream); let cmap = type1_tounicode(used); let mut stream = format!("<< /Length {} >>\nstream\n", cmap.len()).into_bytes(); stream.extend_from_slice(&cmap); stream.extend_from_slice(b"\nendstream"); objects.push(stream); id } fn native_pdf_name(name: &str) -> String { name.bytes() .map(|b| { if (33..=126).contains(&b) && !b"#%()/<>[]{}".contains(&b) { char::from(b).to_string() } else { format!("#{b:02X}") } }) .collect() } struct NativeType1Descriptor<'a> { metrics: &'a crate::tfm::TfmMetrics, object: Option, } fn write_native_type1_descriptor( objects: &mut Vec>, font: &Type1Font, paint: &crate::native_font::NativeFontPaint, metrics: &crate::tfm::TfmMetrics, compression: u8, ) -> usize { let descriptor = objects.len() + 1; let program = descriptor + 1; let name = native_pdf_name(&font.name); let [left, bottom, right, top] = paint.bbox; let units = |n: i64| native_font_units(n, native_pdf_font_size(metrics.size_sp()), 1000); // TFM slot conventions of the profile, independent of glyph names in // mathematical or externally reencoded fonts. let ascent = units(metrics.height('h')); let descent = (-units(metrics.depth('y'))).min(0); let cap = units(metrics.height('H')); let x_height = units(metrics.x_height()); let flags = 4 | if font.is_fixed_pitch { 1 } else { 0 } | if font.italic_angle != "0" { 64 } else { 0 }; let angle = &font.italic_angle; let stem_v = paint.stem_v; objects.push(format!("<< /Type /FontDescriptor /FontName /{name} /Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v} /FontFile {program} 0 R >>").into_bytes()); objects.push(objects::stream( &format!( "/Length1 {} /Length2 {} /Length3 {}", font.length1, font.length2, font.length3 ), &font.program, compression, )); descriptor } fn write_native_font( objects: &mut Vec>, face: &crate::native_font::NativeFont, paint: &crate::native_font::NativeFontPaint, used: &BTreeMap, compression: u8, options: Option>, diagnostics: &mut Vec, descriptors: &mut HashMap<&crate::resources::ResourceVersion, NativeType1Descriptor<'_>>, ) -> usize { let font = match &paint.program { crate::native_font::NativeFontProgram::Type1(font) => font, crate::native_font::NativeFontProgram::Pk(pk) => { return pk_fonts::write_font(objects, face.id, pk, used, compression); } }; let id = objects.len() + 1; objects.push(Vec::new()); let m = face.metrics(); let descriptor = match paint.type1_resource().and_then(|key| descriptors.get_mut(key)) { Some(shared) => *shared.object.get_or_insert_with(|| { write_native_type1_descriptor(objects, font, paint, shared.metrics, compression) }), None => write_native_type1_descriptor(objects, font, paint, m, compression), }; let unicode = objects.len() + 1; let first = *used.keys().next().unwrap(); let last = *used.keys().next_back().unwrap(); let widths = (first..=last) .map(|slot| { format!( "{:.1}", native_font_units( m.width(char::from(slot)), native_pdf_font_size(m.size_sp()), 10_000 ) as f64 / 10.0 ) }) .collect::>() .join(" "); let differences = paint .encoding .iter() .map(|n| format!("/{}", native_pdf_name(n))) .collect::>() .join(" "); let cmap = if let Some(options) = options { if options.generate_unicode > 0 && !options.glyph_unicode.is_empty() { let texts = paint .encoding .iter() .enumerate() .filter_map(|(slot, name)| { options .glyph_unicode .lookup(&face.name, name) .map(|hex| (slot as u8, hex)) }) .collect(); Some(type1_tounicode_hex(&texts)) } else { if options.generate_unicode > 0 && diagnostics.is_empty() { diagnostics.push("no GlyphToUnicode entry has been inserted yet!".into()); } None } } else { let texts = used .keys() .filter_map(|slot| { crate::type1::glyph_unicode_text(&paint.encoding[*slot as usize]) .map(|s| (*slot, expanded_ligature_text(&s))) }) .collect(); Some(type1_tounicode_texts(&texts)) }; let unicode_ref = if cmap.is_some() { format!(" /ToUnicode {unicode} 0 R") } else { String::new() }; let name = native_pdf_name(&font.name); objects[id - 1] = format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name} /FirstChar {first} /LastChar {last} /Widths [{widths}] /Encoding << /Type /Encoding /Differences [0 {differences}] >> /FontDescriptor {descriptor} 0 R {unicode_ref} >>").into_bytes(); if let Some(cmap) = cmap { objects.push(objects::stream("", &cmap, compression)); } id } fn write_pdf( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, backend: FontBackend, metadata: &PdfMetadata, final_compression: Option, unicode: Option>, diagnostics: &mut Vec, ) -> Vec { let width = page_width; let height = page_height; 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 // Native math uses exact slots and optical masters, independent of the // document's Times/Liberation text backend and Unicode face remapping. let mut math_used: BTreeMap> = BTreeMap::new(); for page in pages { for item in &page.items { if let DisplayItem::MathGlyph { face, slot, character, .. } = item { math_used .entry(*face) .or_default() .insert(*slot, *character); } } } let mut math_font_ids = BTreeMap::new(); for (face, used) in &math_used { math_font_ids.insert(*face, write_math_font(&mut objects, *face, used)); } let mut native_used = BTreeMap::new(); let mut type1_names = HashSet::new(); let mut type1_descriptors = HashMap::new(); for page in pages { for item in &page.items { if let DisplayItem::NativeGlyph { font, paint, slot, character, .. } = item { let paint = paint .as_ref() .expect("resolve native font resources before PDF output"); let entry = native_used.entry(font.id).or_insert_with(|| { // pdfTeX registers one font object per scalable TFM name // when used and writes those objects in reverse order. // The last newly used TFM for a PFB supplies its shared // descriptor, while each font keeps its own encoding. if let Some(program) = paint.type1_resource() { if type1_names.insert((program, font.name.as_str())) { type1_descriptors.insert( program, NativeType1Descriptor { metrics: font.metrics(), object: None }, ); } } (font.clone(), paint.clone(), BTreeMap::new()) }); assert_eq!( entry.0.as_ref(), font.as_ref(), "native font ids from different jobs cannot share a PDF" ); entry.2.insert(*slot, *character); } } } let mut native_font_ids = BTreeMap::new(); for (id, (face, paint, used)) in native_used { native_font_ids.insert( id, write_native_font( &mut objects, &face, &paint, &used, final_compression.unwrap_or(0).max(0).min(9) as u8, unicode, diagnostics, &mut type1_descriptors, ), ); } let mut used_faces = [false; FACE_COUNT]; let mut used_chars: [BTreeSet; FACE_COUNT] = 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 cm_faces: Vec)>> = (0..FACE_COUNT) .map(|slot| { // A Times/TrueType document still wants the real Computer Modern // math faces: the Liberation fallback has different glyph sizes, // so formulas would be narrower and shorter than TeX. let type1_math = backend == FontBackend::TrueType && (6..=10).contains(&slot); if (backend != FontBackend::ComputerModern && !type1_math) || !used_faces[slot] { return None; } let font = type1_fonts()[slot].as_ref()?; if slot == FontFace::MathSymbol as usize || slot == FontFace::MathExtension as usize { let codes = used_chars[slot] .iter() .filter_map(|character| { let code = if slot == FontFace::MathSymbol as usize { crate::cmr10::math_symbol_slot(*character).or_else(|| { character.is_ascii_uppercase().then_some(*character as u8) }) } else { crate::cmr10::math_extension_slot(*character) }; code.map(|code| (*character, code)) }) .collect(); return Some((font, codes)); } let codes = used_chars[slot] .iter() .filter_map(|character| font.code_for(*character).map(|code| (*character, code))) .collect(); Some((font, codes)) }) .collect(); let cm_views: Vec>> = cm_faces .iter() .map(|entry| entry.as_ref().map(|(_, codes)| codes)) .collect(); let mut fallback_chars: [BTreeSet; FACE_COUNT] = Default::default(); for slot in 0..FACE_COUNT { if let Some((_, codes)) = &cm_faces[slot] { for character in &used_chars[slot] { if !codes.contains_key(character) { fallback_chars[slot].insert(*character); } } } } 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; FACE_COUNT] = if minimal { &MIN_FACES } else { &FULL_FACES }; let mut font_ids = [0usize; FACE_COUNT]; let mut fallback_font_ids = [0usize; FACE_COUNT]; for (slot, face) in faces.iter().enumerate() { if !used_faces[slot] { continue; } if let Some((font, codes)) = &cm_faces[slot] { let font_id = objects.len() + 1; let descriptor_id = font_id + 1; let file_id = font_id + 2; let tounicode_id = font_id + 3; font_ids[slot] = font_id; let metrics = Cmr10Metrics::for_pdf_slot(slot); let mut by_code = BTreeMap::new(); for (character, code) in codes { by_code.insert(*code, *character); } let first = *by_code.keys().next().unwrap_or(&32); let last = *by_code.keys().next_back().unwrap_or(&32); let mut widths = Vec::new(); let mut differences = Vec::new(); let mut next_code = first; for code in first..=last { let width = by_code.get(&code).map_or(0, |character| { let width = match slot { slot if slot == FontFace::MathSymbol as usize => { crate::cmr10::math_symbol_width(*character) .unwrap_or_else(|| metrics.width(*character)) } slot if slot == FontFace::MathExtension as usize => { crate::cmr10::math_extension_width(*character) .unwrap_or_else(|| metrics.width(*character)) } _ => metrics.width(*character), }; (width * 100 / 65_536) as i64 }); widths.push(width.to_string()); let glyph = if slot == FontFace::MathSymbol as usize || slot == FontFace::MathExtension as usize { font.name_for_code(code).map(|name| (code, name)) } else { by_code .get(&code) .and_then(|character| font.code_and_name_for(*character)) }; if let Some((code, name)) = glyph { if code != next_code { differences.push(code.to_string()); } differences.push(format!("/{name}")); next_code = code + 1; } } objects.push( format!( "<< /Type /Font /Subtype /Type1 /BaseFont /{} /FirstChar {first} /LastChar {last} /Widths [{}] /Encoding << /Type /Encoding /Differences [{}] >> /FontDescriptor {descriptor_id} 0 R /ToUnicode {tounicode_id} 0 R >>", font.name, widths.join(" "), differences.join(" ") ) .into_bytes(), ); objects.push( format!( "<< /Type /FontDescriptor /FontName /{} /Flags 34 /FontBBox [-40 -250 1009 750] /ItalicAngle 0 /Ascent 694 /Descent -194 /CapHeight 683 /StemV 69 /FontFile {file_id} 0 R >>", font.name ) .into_bytes(), ); let mut stream = format!( "<< /Length {} /Length1 {} /Length2 {} /Length3 {} >>\nstream\n", font.program.len(), font.length1, font.length2, font.length3 ) .into_bytes(); stream.extend_from_slice(&font.program); stream.extend_from_slice(b"\nendstream"); objects.push(stream); let cmap = type1_tounicode(&by_code); 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); if !fallback_chars[slot].is_empty() { fallback_font_ids[slot] = write_type0_font(&mut objects, face, slot, &fallback_chars[slot]); } continue; } font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]); } let mut kids = Vec::new(); let mut page_ids: Vec = Vec::new(); let mut destinations = BTreeMap::new(); let mut form_ids = BTreeMap::new(); for list in pages { for item in &list.items { if let DisplayItem::PdfImageObject(object) = item { form_ids.entry(object.image.id).or_insert_with(|| { object .image .image .append_to(&mut objects, &object.attributes) }); } } } for list in pages { for item in &list.items { if let DisplayItem::PdfImage { image, .. } = item { form_ids .entry(image.id) .or_insert_with(|| image.image.append_to(&mut objects, &[])); } } } for list in pages { let width = if final_compression.is_some() { list.width } else { width }; let height = if final_compression.is_some() { list.height } else { height }; let physical = |n: i64| -> String { let scaled = crate::pdf_device::magnify(n, list.magnification); if list.units == crate::render::DisplayUnits::TeX { crate::pdf_device::print_sp( scaled, list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits), ) } else { pt(scaled) } }; 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 mut xobjects = used .iter() .map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot)) .collect::>() .join(" "); let forms = list .items .iter() .filter_map(|item| match item { DisplayItem::PdfImage { image, .. } => Some(image.id), _ => None, }) .collect::>(); for id in forms { xobjects.push_str(&format!(" /PI{id} {} 0 R", form_ids[&id])); } let mut fonts = (0..FACE_COUNT) .filter(|slot| used_faces[*slot]) .flat_map(|slot| { let mut entries = Vec::new(); if font_ids[slot] != 0 { entries.push(format!("/F{} {} 0 R", slot + 1, font_ids[slot])); } if fallback_font_ids[slot] != 0 { entries.push(format!("/T{} {} 0 R", slot + 1, fallback_font_ids[slot])); } entries }) .collect::>() .join(" "); for (face, id) in &math_font_ids { fonts.push_str(&format!(" /M{} {id} 0 R", face.0)); } for (face, id) in &native_font_ids { fonts.push_str(&format!(" /N{} {id} 0 R", face.index())); } let resources = if xobjects.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 annotation_count = links.len() + list.pdf_links.annotations.len(); let annots = if annotation_count == 0 { String::new() } else { let refs = (0..annotation_count) .map(|index| format!("{} 0 R", annotation_base + index)) .collect::>() .join(" "); format!(" /Annots [{refs}]") }; page_ids.push(page_id); 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 >>", physical(width), physical(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, &cm_views, &fallback_font_ids, origin, ); objects.push(objects::stream( "", content.as_bytes(), list.pdf.as_ref().map_or(0, |p| p.stream_compression), )); 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); } let link_border = match metadata.link_border { Some([red, green, blue]) => format!( "/Border [0 0 1] /C [{:.3} {:.3} {:.3}]", red as f64 / 255.0, green as f64 / 255.0, blue as f64 / 255.0 ), None => "/Border [0 0 0]".to_string(), }; for (index, (x, y, width, link_height, url)) in links.iter().enumerate() { let _ = index; objects.push( format!( "<< /Type /Annot /Subtype /Link /Rect [{} {} {} {}] {link_border} /A << /S /URI /URI ({}) >> >>", physical(*x), physical(height - *y - *link_height), physical(*x + *width), physical(height - *y), escape(url) ) .into_bytes(), ); } for annotation in &list.pdf_links.annotations { use crate::pdf_device::links::AnnotationAction; let [left, top, right, bottom] = annotation.rect; let coordinates = [left, height - bottom, right, height - top].map(physical); let action = match &annotation.action { AnnotationAction::User(raw) => raw.clone(), AnnotationAction::GotoName(name) => format!("/Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)), }; objects.push(format!("<< /Type /Annot {} /Rect [{}] {} >>", annotation.attributes, coordinates.join(" "), action).into_bytes()); } for destination in &list.pdf_links.destinations { use crate::pdf_device::links::DestinationView; let x = physical(destination.point[0]); let y = physical(height - destination.point[1]); let view = match destination.view { DestinationView::Xyz(zoom) => { let zoom = zoom.filter(|n| *n > 0).map_or("null".to_owned(), |n| crate::pdf_device::print_decimal(i64::from(n), 3)); format!("/XYZ {x} {y} {zoom}") } DestinationView::Fit => "/Fit".into(), DestinationView::FitB => "/FitB".into(), DestinationView::FitH => format!("/FitH {y}"), DestinationView::FitV => format!("/FitV {x}"), DestinationView::FitBH => format!("/FitBH {y}"), DestinationView::FitBV => format!("/FitBV {x}"), }; destinations.entry(destination.name.clone()).or_insert_with(|| format!("[{page_id} 0 R {view}]")); } } objects[1] = format!( "<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len() ) .into_bytes(); let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned(); if !metadata.outline.is_empty() { let root_id = objects.len() + 1; objects.push(Vec::new()); let item_ids: Vec = (0..metadata.outline.len()) .map(|_| { objects.push(Vec::new()); objects.len() }) .collect(); // Nest entries by heading level: an entry is a child of the nearest // preceding entry with a strictly smaller level. let mut parents: Vec> = vec![None; metadata.outline.len()]; let mut stack: Vec = Vec::new(); let mut children: HashMap> = HashMap::new(); for index in 0..metadata.outline.len() { let level = metadata.outline[index].level; while let Some(&top) = stack.last() { if metadata.outline[top].level >= level { stack.pop(); } else { break; } } let parent = stack.last().copied(); parents[index] = parent; children .entry(parent.unwrap_or(usize::MAX)) .or_default() .push(index); stack.push(index); } for (index, entry) in metadata.outline.iter().enumerate() { let page_id = page_ids .get(entry.page) .or_else(|| page_ids.last()) .copied() .unwrap_or(0); let parent_id = parents[index].map_or(root_id, |parent| item_ids[parent]); let mut dict = format!( "<< /Title {} /Parent {} 0 R /Dest [{} 0 R /Fit]", pdf_text(&entry.title), parent_id, page_id ); let siblings = &children[&parents[index].unwrap_or(usize::MAX)]; if let Some(position) = siblings.iter().position(|candidate| *candidate == index) { if position > 0 { dict.push_str(&format!(" /Prev {} 0 R", item_ids[siblings[position - 1]])); } if position + 1 < siblings.len() { dict.push_str(&format!(" /Next {} 0 R", item_ids[siblings[position + 1]])); } } if let Some(kids) = children.get(&index) { if !kids.is_empty() { dict.push_str(&format!( " /First {} 0 R /Last {} 0 R /Count {}", item_ids[kids[0]], item_ids[kids[kids.len() - 1]], descendant_count(&children, index) )); } } dict.push_str(" >>"); objects[item_ids[index] - 1] = dict.into_bytes(); } let roots = &children[&usize::MAX]; objects[root_id - 1] = format!( "<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {} >>", item_ids[roots[0]], item_ids[roots[roots.len() - 1]], metadata.outline.len() ) .into_bytes(); catalog.push_str(&format!(" /Outlines {root_id} 0 R")); } if !destinations.is_empty() { let mut entries = Vec::with_capacity(destinations.len()); let first = pdf_text(destinations.first_key_value().unwrap().0); let last = pdf_text(destinations.last_key_value().unwrap().0); for (name, destination) in destinations { objects.push(destination.into_bytes()); entries.push(format!("{} {} 0 R", pdf_text(&name), objects.len())); } objects.push(format!("<< /Names [{}] /Limits [{first} {last}] >>", entries.join(" ")).into_bytes()); catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len())); } catalog.push_str(" >>"); objects[0] = catalog.into_bytes(); let info_ref = match metadata_object(metadata) { Some(object) => { objects.push(object.into_bytes()); format!(" /Info {} 0 R", objects.len()) } None => String::new(), }; if let Some(level) = final_compression { let info = if info_ref.is_empty() { objects.push(b"<< /Producer (texrra Route-D native) >>".to_vec()); Some(objects.len()) } else { Some(objects.len()) }; let options = &pages[0] .pdf .as_ref() .expect("validated native PDF options") .file; return objects::serialize(&objects, info, options, level.max(0).min(9) as u8); } 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, info_ref, 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 truetype_pdf_keeps_cmmi_for_math() { let mut list = crate::render::DisplayList::default(); list.width = 612 * 65_536; list.height = 792 * 65_536; list.push(crate::render::DisplayItem::Text { font: crate::render::FontFace::MathItalic, x: 72 * 65_536, y: 100 * 65_536, size: 10 * 65_536, text: "α".to_string(), }); list.push(crate::render::DisplayItem::Text { font: crate::render::FontFace::Roman, x: 72 * 65_536, y: 120 * 65_536, size: 10 * 65_536, text: "Body".to_string(), }); let pdf = super::display_lists_to_pdf_with_truetype_and_metadata( &[list], 612 * 65_536, 792 * 65_536, super::PageOrigin::default(), &super::PdfMetadata::default(), ); let text = String::from_utf8_lossy(&pdf); assert!(text.contains("/BaseFont /CMMI10"), "missing CMMI10"); assert!( text.contains("/BaseFont /LiberationSerif"), "missing body face" ); } #[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("中文"), "??"); } } #[cfg(test)] mod type1_pdf_tests { use super::*; fn hello_list() -> DisplayList { let mut list = DisplayList { width: 200 * 65_536, height: 100 * 65_536, items: Vec::new(), images: Vec::new(), magnification: 1000, ..Default::default() }; list.push(DisplayItem::Text { x: 0, y: 800_000, size: 655_360, text: "Hi".to_string(), font: FontFace::Roman, }); list } fn write(list: &[DisplayList]) -> Vec { display_lists_to_pdf_with_cm_type1(list, 200 * 65_536, 800 * 65_536, PageOrigin::default()) } #[test] fn type1_fonts_map_omega_to_the_requested_code() { let font = type1_fonts()[0].as_ref().expect("cmr10 type1 program"); let code = font.code_for('\u{3a9}').expect("omega in cmr10"); let mut by_code = std::collections::BTreeMap::new(); by_code.insert(code, '\u{3a9}'); let cmap = String::from_utf8_lossy(&type1_tounicode(&by_code)).to_string(); assert!(cmap.contains(&format!("<{code:02X}> <03A9>")), "{cmap}"); } #[test] fn outline_entries_become_pdf_bookmarks() { let pages = vec![ DisplayList { width: 612 * 65536, height: 792 * 65536, items: Vec::new(), images: Vec::new(), magnification: 1000, ..Default::default() }, DisplayList { width: 612 * 65536, height: 792 * 65536, items: Vec::new(), images: Vec::new(), magnification: 1000, ..Default::default() }, ]; let metadata = PdfMetadata { title: Some("Book".into()), outline: vec![ PdfOutlineEntry { title: "1 One".into(), page: 0, level: 1, }, PdfOutlineEntry { title: "2 Two".into(), page: 1, level: 1, }, ], ..PdfMetadata::default() }; let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata( &pages, 612 * 65536, 792 * 65536, PageOrigin::default(), &metadata, )) .to_string(); assert!(pdf.contains("/Type /Outlines")); assert!(pdf.contains("/Title (1 One)")); assert!(pdf.contains("/Title (2 Two)")); assert!(pdf.contains("/Count 2")); assert!(pdf.contains("/Dest [")); assert!(pdf.contains("/Outlines")); } #[test] fn metadata_writes_the_pdf_info_dictionary() { let pages = vec![DisplayList { width: 612 * 65536, height: 792 * 65536, items: Vec::new(), images: Vec::new(), magnification: 1000, ..Default::default() }]; let metadata = PdfMetadata { title: Some("Plain Title".into()), author: Some("Ada".into()), subject: None, keywords: None, outline: Vec::new(), link_border: None, }; let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata( &pages, 612 * 65536, 792 * 65536, PageOrigin::default(), &metadata, )) .to_string(); assert!(pdf.contains("/Title (Plain Title)")); assert!(pdf.contains("/Author (Ada)")); assert!(pdf.contains("/Producer (texrra route-D)")); assert!(pdf.contains("/Info")); let unicode = PdfMetadata { title: Some("Ωmega".into()), ..PdfMetadata::default() }; let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata( &pages, 612 * 65536, 792 * 65536, PageOrigin::default(), &unicode, )) .to_string(); assert!(pdf.contains("/Title