//! 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::pdf_device::{ catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget}, links::DestinationId, }; use crate::render::{DisplayItem, DisplayList, FontFace}; use crate::type1::Type1Font; #[path = "pdf_text.rs"] pub(crate) mod native_text; #[path = "pdf_objects.rs"] pub(crate) 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, expansion: i32, size: i64, y: i64, cursor: f64, point_size: f64, text: String, } impl NativeTextRun { fn flush(run: &mut Option, content: &mut PageContent) { if let Some(run) = run.take() { content.push_str(&run.text); if run.expansion == 0 { content.push_str("] TJ ET\n"); } else { content.push_str("] TJ 100 Tz 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 } /// The PDF stream can contain an 8-bit TeX literal. Keep its bytes alongside /// the device origin used by subsequent positioned text, rules, and images. #[derive(Default)] struct PageContent { bytes: Vec, origin: crate::pdf_device::DeviceOrigin, measuring: bool, } impl PageContent { fn measuring() -> Self { Self { measuring: true, ..Self::default() } } fn push_str(&mut self, text: &str) { if !self.measuring { self.bytes.extend_from_slice(text.as_bytes()); } } fn push(&mut self, byte: u8) { if !self.measuring { self.bytes.push(byte); } } fn move_origin(&mut self, point: [i64; 2], units: crate::render::DisplayUnits, digits: u8) { let Some([h, v]) = self.origin.move_to(point, units, digits) else { return; }; self.push_str(&format!( "1 0 0 1 {} {} cm\n", crate::pdf_device::print_decimal(h, digits), crate::pdf_device::print_decimal(v, digits), )); } } pub(crate) fn prepare_text_spaces( pages: &mut [DisplayList], mut resolve: impl FnMut( std::sync::Arc, Option, ) -> Result, ) -> Result<(), String> { if !pages.iter().any(|page| page.pdf_text_spaces.is_some()) { return Ok(()); } let mut fonts = native_text::FontHistory::default(); let mut selected = None; for page in pages { let plan = native_text::plan_spaces(page, &mut fonts, || { if let Some(font) = &selected { return Ok(Some(crate::pdf_device::text_spaces::ResolvedSpaceFont::clone(font))); } let font = page.pdf_text_spaces.as_ref() .and_then(|settings| settings.dedicated_font.clone()) .ok_or("PDF space planner requires the font selected during shipout")?; let font = resolve(font, page.pdf.clone())?; selected = Some(font.clone()); Ok(Some(font)) })?.expect("PDF export always resolves the selected space font"); if page.pdf_text_spaces.is_some() { page.pdf_resources.needs_pdf_for_preview |= plan.spaces_in_previous_font || plan.dedicated.as_ref() .is_some_and(|font| !font.paint.glyph_paths[&b' '].is_empty()); page.pdf_space_plan = Some(plan); } } Ok(()) } 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, ) -> Vec { 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) } }; use crate::pdf_device::{PdfGraphics, PdfLiteralMode}; use crate::render::DisplayUnits; let mut content = PageContent::default(); content.push_str("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 (index, item) in list.items.iter().enumerate() { if let DisplayItem::PdfTextSpace { x, y, operation } = item { if let Some(dedicated) = list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()) && *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit { if tex_text.is_none() { content.move_origin([0, 0], list.units, digits); } native_text::NativeText::explicit_space( &mut tex_text, &mut content, *x, *y, height, digits, dedicated, ); } continue; } if let DisplayItem::PdfGraphics { x, y, operation: PdfGraphics::Literal { mode, bytes }, } = item { NativeTextRun::flush(&mut native_text, &mut content); match mode { PdfLiteralMode::Direct => { native_text::NativeText::break_string(&mut tex_text, &mut content); } PdfLiteralMode::Page | PdfLiteralMode::Origin => { native_text::NativeText::finish(&mut tex_text, &mut content); if *mode == PdfLiteralMode::Origin { content.move_origin([*x, height - *y], list.units, digits); } } } content.bytes.extend_from_slice(bytes); content.push(b'\n'); continue; } if list.units == DisplayUnits::TeX { if let DisplayItem::NativeGlyph { x, y, font, slot, paint, .. } = item { assert!(paint.is_some(), "native glyph program must be resolved"); if tex_text.is_none() { content.move_origin([0, 0], list.units, digits); } native_text::NativeText::glyph( &mut tex_text, &mut content, *x, *y, font, paint.as_ref().unwrap(), *slot, height, digits, list.pdf_space_plan.as_ref().and_then(|plan| plan.before_glyph.get(&index)).copied(), list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()), ); continue; } native_text::NativeText::finish(&mut tex_text, &mut content); if let DisplayItem::Rule { x, y, width, height: rule_height, } = item { let [h, v] = content.origin.position(); native_text::rule( &mut content, *x - h, *y + v, *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 && font.expansion==run.expansion && *size==run.size && *y==run.y) { NativeTextRun::flush(&mut native_text, &mut content); } } let [h, v] = content.origin.position(); let px = |x| pt(x - h); let py = |y| pt(height - y - v); 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; let spacing = if font.expansion == 0 { String::new() } else { format!("{} Tz ", crate::pdf_device::print_decimal( i64::from(1000 + font.expansion), 1, )) }; NativeTextRun { font: font.id, expansion: font.expansion, size: *size, y: *y, cursor: px(*x).parse().unwrap(), point_size: point_size * f64::from(1000 + font.expansion) / 1000.0, text: format!( "BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [", font.id.index(), px(*x), py(*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), px(*x), py(*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), px(*x), py(*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, px(*x), py(*y + *height), pt(*width), pt(*height) )); } DisplayItem::Rule { x, y, width, height: rule_height, } => { content.push_str(&format!( "{} {} {} {} re f\n", px(*x), py(*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), px(*x1), py(*y1), px(*x2), py(*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), px(*x), py(*y + *image_height) )); } } DisplayItem::PdfImage { x, y, width, height: image_height, image, } => { let [sx, sy] = if image.image.raster_frame().is_some() && list.units == crate::render::DisplayUnits::TeX { [ crate::pdf_device::print_sp(*width, 4), crate::pdf_device::print_sp(*image_height, 4), ] } else 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, 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", px(*x), py(*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, px(*x), pt(list.height - *y - *height - v), pt(*width), pt(*height) )); } DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {} 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(b'\n'); } DisplayItem::PdfColor(program) => { content.push_str(program.literal()); content.push(b'\n'); } DisplayItem::PdfGraphics { x, y, operation } => { let device_origin = list.units == DisplayUnits::TeX; if device_origin { content.move_origin([*x, height - *y], list.units, digits); } match operation { PdfGraphics::Save => content.push_str("q\n"), PdfGraphics::Restore { shift: [dx, dy] } => { content.push_str("Q\n"); if !device_origin && (*dx != 0 || *dy != 0) { content.push_str(&format!( "1 0 0 1 {} {} cm\n", pt(*dx), pt(-*dy), )); } } PdfGraphics::Matrix(matrix) => { let coordinates = if device_origin { [0.0, 0.0] } else { [*x, height - *y].map(|coordinate| { pt(coordinate).parse::().expect("formatted PDF dimension") }) }; let [a, b, c, d, e, f] = matrix .about(coordinates[0], coordinates[1], false) .0 .map(crate::pdf_image::real); content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n")); } PdfGraphics::Literal { .. } => unreachable!("literal handled before text"), } } } } NativeTextRun::flush(&mut native_text, &mut content); native_text::NativeText::finish(&mut tex_text, &mut content); content.push_str("Q\n"); content.bytes } /// 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(" "))) } fn native_information_dictionary(info: crate::pdf_device::PdfInfo<'_>) -> Vec { // pdfTeX suppresses defaults based on the raw byte spelling anywhere in // the expanded list. Preserve the supplied PDF syntax verbatim. let supplied = |key: &[u8]| info.entries.windows(key.len()).any(|value| value == key); let mut object = b"<<\n".to_vec(); if !supplied(b"/Producer") { object.extend_from_slice(b"/Producer (texrra Route-D native)\n"); } if !info.entries.is_empty() { object.extend_from_slice(info.entries); object.push(b'\n'); } if !supplied(b"/Creator") { object.extend_from_slice(b"/Creator (TeX)\n"); } if let Some(date) = info.date { for key in ["CreationDate", "ModDate"] { let name = format!("/{key}"); if !supplied(name.as_bytes()) { writeln!(&mut object, "{name} ({date})").unwrap(); } } } if !supplied(b"/Trapped") { object.extend_from_slice(b"/Trapped /False\n"); } object.extend_from_slice(b">>"); object } /// 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, 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, 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()); } if page.pdf_text_spaces.is_some() && page.pdf_space_plan.is_none() { return Err("native PDF text spaces require actual font resolution".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.same_base(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 raw_objects = unicode.and_then(|options| options.objects); let page_tree = unicode.map_or(&[][..], |options| options.page_tree_attributes); let font_attributes: BTreeMap<_, _> = fonts.keys().filter_map(|&font| { let settings = unicode?.fonts.pdf_settings(font)?; (!settings.attributes.is_empty()).then_some((font, settings.attributes.as_slice())) }).collect(); let resources = if raw_objects.is_some() || !font_attributes.is_empty() || !page_tree.is_empty() || pages.iter().any(|page| !page.pdf_resources.entries.is_empty() || !page.pdf_resources.attributes.is_empty() || page.pdf_links.destinations.iter().any(|destination| destination.structure.is_some())) { let (catalog, info) = if raw_objects.is_some() { ( unicode.and_then(|options| options.catalog).map(|catalog| catalog.entries.as_slice()), unicode.map(|options| options.info.entries), ) } else { (None, None) }; Some(crate::pdf_device::page_resources::ResourceOutput::prepare( pages, raw_objects, font_attributes, page_tree, catalog, info, )?) } else { None }; let mut diagnostics = Vec::new(); let bytes = write_pdf( pages, page_width, page_height, origin, FontBackend::ComputerModern, &PdfMetadata::default(), final_compression, unicode, resources, &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, 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, 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.fonts.pdf_settings(face.id).is_some_and(|settings| settings.omit_builtin_unicode) { None } else 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 pdf_file_specification(out: &mut Vec, file: &[u8]) { out.extend_from_slice(b"/F "); if file.starts_with(b"(") && file.ends_with(b")") { out.extend_from_slice(file); } else { out.push(b'('); for &byte in file { if matches!(byte, b'(' | b')' | b'\\') { out.push(b'\\'); } out.push(byte); } out.push(b')'); } out.push(b' '); } #[derive(Default)] struct PdfNavigation { pages: Vec, named: BTreeMap, numbered: BTreeMap, structures: BTreeMap, usize>, threads: BTreeMap, usize>, } fn destination_identifier(id: &DestinationId) -> String { match id { DestinationId::Name(name) => format!("name{{{name}}}"), DestinationId::Number(number) => format!("num{number}"), } } fn catalog_action_bytes( action: &CatalogAction, destinations: &mut PdfNavigation, objects: &mut Vec>, diagnostics: &mut Vec, ) -> Vec { let PdfNavigation { pages, named, numbered, structures, threads } = destinations; let mut output = b"<< ".to_vec(); match action { CatalogAction::User(object) => output.clone_from(object), CatalogAction::GoTo { target, file, window, structure, } => { if let Some(file) = file { pdf_file_specification(&mut output, file); if let Some(window) = window { write!(&mut output, "/NewWindow {window} ").unwrap(); } output.extend_from_slice(b"/S /GoToR /D "); } else { output.extend_from_slice(b"/S /GoTo /D "); } match target { CatalogTarget::Destination(DestinationId::Name(name)) => { if file.is_none() && !named.contains_key(name) { diagnostics.push(format!( "destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one" )); named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0])); } output.extend_from_slice(pdf_text(name).as_bytes()); } CatalogTarget::Destination(DestinationId::Number(number)) => { let id = numbered.entry(*number).or_insert_with(|| { diagnostics.push(format!( "destination num{number} has been referenced but does not exist, replaced by a fixed one" )); objects.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes()); objects.len() }); write!(&mut output, "{id} 0 R").unwrap(); } CatalogTarget::Page { number, view } => { let index = (*number - 1) as usize; if file.is_some() { write!(&mut output, "[{index} ").unwrap(); } else { let page = pages.get(index).copied().unwrap_or_else(|| { diagnostics.push(format!( "page {number} has been referenced but does not exist" )); objects.push(Vec::new()); objects.len() }); write!(&mut output, "[{page} 0 R ").unwrap(); } output.extend_from_slice(view); output.push(b']'); } } match structure { Some(StructureTarget::Local(destination)) => { let id = structures.entry(destination.clone()).or_insert_with(|| { diagnostics.push(format!( "structure destination {} has been referenced but does not exist", destination_identifier(destination) )); // pdfTeX leaves the missing destination in the free list. objects.push(Vec::new()); objects.len() }); write!(&mut output, " /SD {id} 0 R").unwrap(); } Some(StructureTarget::Remote(bytes)) => { output.extend_from_slice(b" /SD "); output.extend_from_slice(bytes); } None => {} } output.extend_from_slice(b"\n>>"); } CatalogAction::Thread { destination, file } => { let mut local_id = None; if let Some(file) = file { pdf_file_specification(&mut output, file); } else { let (title, identifier) = match destination { DestinationId::Name(name) => (name.clone(), format!("name{{{name}}}")), DestinationId::Number(number) => (number.to_string(), format!("num{number}")), }; local_id = Some(*threads.entry(destination.clone()).or_insert_with(|| { diagnostics.push(format!( "thread destination {identifier} has been referenced but does not exist, replaced by a fixed one" )); // Link the missing thread's single empty bead to the first page. let thread = objects.len() + 1; let bead = thread + 1; objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes()); objects.push(format!( "<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>", pages[0] ).into_bytes()); thread })); } output.extend_from_slice(b"/S /Thread /D "); match destination { DestinationId::Name(name) => output.extend_from_slice(pdf_text(name).as_bytes()), DestinationId::Number(number) => { if let Some(id) = local_id { write!(&mut output, "{id} 0 R").unwrap(); } else { write!(&mut output, "{number}").unwrap(); } } } output.extend_from_slice(b" >>"); } } output } #[derive(Clone, Default)] struct OutlinePosition { parent: usize, first: Option, last: Option, previous: Option, next: Option, visible_children: usize, } fn write_pdf_outlines( outlines: &[PdfOutline>], action_ids: &[usize], objects: &mut Vec>, ) -> usize { let mut positions = vec![OutlinePosition::default(); outlines.len() + 1]; let mut parents = vec![(0, usize::MAX)]; for (offset, outline) in outlines.iter().enumerate() { let index = offset + 1; let (parent, remaining) = parents.last_mut().unwrap(); let parent = *parent; *remaining -= 1; positions[parent].first.get_or_insert(index); if let Some(previous) = positions[parent].last.replace(index) { positions[previous].next = Some(index); positions[index].previous = Some(previous); } positions[index].parent = parent; if outline.count != 0 { parents.push((index, outline.count.unsigned_abs() as usize)); } else { while parents.last().is_some_and(|(_, remaining)| *remaining == 0) { parents.pop(); } } } for (offset, outline) in outlines.iter().enumerate().rev() { let position = &positions[offset + 1]; let visible = if outline.count > 0 { position.visible_children } else { 0 }; let parent = position.parent; positions[parent].visible_children += visible + 1; } let root_id = objects.len() + 1; objects.resize_with(root_id + outlines.len(), Vec::new); let root = &positions[0]; // pdfTeX uses the current sibling at the end of input as the root's Last. let last = positions[parents.last().unwrap().0].last.map_or(0, |index| root_id + index); objects[root_id - 1] = format!( "<< /Type /Outlines /First {} 0 R /Last {last} 0 R /Count {} >>", root_id + root.first.unwrap(), root.visible_children, ) .into_bytes(); for (offset, (outline, action_id)) in outlines.iter().zip(action_ids).enumerate() { let position = &positions[offset + 1]; let mut title = Vec::with_capacity(outline.title.len() + 2); title.push(b'('); title.extend_from_slice(&outline.title); title.push(b')'); objects.push(title); let mut entry = format!( "<< /Title {} 0 R /A {action_id} 0 R /Parent {} 0 R", objects.len(), root_id + position.parent, ) .into_bytes(); for (key, index) in [ ("Prev", position.previous), ("Next", position.next), ("First", position.first), ("Last", position.last), ] { if let Some(index) = index { write!(&mut entry, " /{key} {} 0 R", root_id + index).unwrap(); } } if position.visible_children != 0 { let sign = if outline.count < 0 { "-" } else { "" }; write!(&mut entry, " /Count {sign}{}", position.visible_children).unwrap(); } if !outline.attributes.is_empty() { entry.push(b'\n'); entry.extend_from_slice(&outline.attributes); entry.push(b'\n'); } entry.extend_from_slice(b" >>"); objects[root_id + offset] = entry; } root_id } fn write_pdf( pages: &[DisplayList], page_width: i64, page_height: i64, origin: PageOrigin, backend: FontBackend, metadata: &PdfMetadata, final_compression: Option, unicode: Option>, resources: 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!( entry.0.same_base(font), "native font ids from different jobs cannot share a PDF" ); entry.2.insert(*slot, *character); } } } for plan in pages.iter().filter_map(|page| page.pdf_space_plan.as_ref()) { for id in &plan.in_font { native_used.get_mut(id).expect("painted space font").2.insert(b' ', ' '); } if let Some(font) = &plan.dedicated { native_used.entry(font.font.id).or_insert_with(|| ( font.font.clone(), font.paint.clone(), BTreeMap::from([(b' ', ' ')]), )); } } 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 remapped = resources.map(|resources| resources.append(&mut objects, diagnostics)); if let Some(resources) = &remapped { for (font, entries) in &resources.fonts { if !entries.is_empty() { let body = &mut objects[native_font_ids[font] - 1]; body.truncate(body.len() - 2); body.extend_from_slice(b"\n"); body.extend_from_slice(entries); body.extend_from_slice(b"\n>>"); } } } let mut kids = Vec::new(); let mut navigation = PdfNavigation::default(); let mut annotation_actions = Vec::new(); let pdf_version = pages .first() .and_then(|page| page.pdf.as_ref()) .map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor))); 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, object.compression, pdf_version, ) }); } } } for list in pages { for item in &list.items { if let DisplayItem::PdfImage { image, .. } = item { form_ids.entry(image.id).or_insert_with(|| { let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression); image.image.append_to(&mut objects, &[], compression, pdf_version) }); } } } let mut png_group = None; for (page_index, list) in pages.iter().enumerate() { let png_group_ref = if !list.pdf_resources.has_page_group && list.items.iter().any(|item| { matches!(item, DisplayItem::PdfImage { image, .. } if image.image.png_transparency(pdf_version)) }) { let id = *png_group.get_or_insert_with(|| { objects.push(b"<< /Type /Group /S /Transparency /CS /DeviceRGB /I true >>".to_vec()); objects.len() }); format!(" /Group {id} 0 R") } else { String::new() }; 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 reserved_page = remapped.as_ref() .and_then(|resources| resources.page_objects.get(&page_index)) .copied(); let page_id = reserved_page.unwrap_or(objects.len() + 1); let content_id = objects.len() + 1 + usize::from(reserved_page.is_none()); 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 native_annotation_base = annotation_base + links.len(); let mut next_annotation = native_annotation_base; let native_annotation_ids: Vec<_> = list.pdf_links.annotations.iter().enumerate() .map(|(index, _)| { remapped.as_ref() .and_then(|resources| resources.link_objects.get(&(page_index, index)).copied()) .unwrap_or_else(|| { let id = next_annotation; next_annotation += 1; id }) }) .collect(); let annotation_refs = (annotation_base..native_annotation_base) .chain(native_annotation_ids.iter().copied()) .map(|id| format!("{id} 0 R")) .collect::>() .join(" "); let annots = if annotation_refs.is_empty() { String::new() } else { format!(" /Annots [{annotation_refs}]") }; navigation.pages.push(page_id); kids.push(format!("{page_id} 0 R")); let decorated = !list.pdf_resources.attributes.is_empty(); let mut page = b"<< /Type /Page".to_vec(); if !decorated { page.extend_from_slice(b" /Parent 2 0 R"); } if !crate::pdf_device::page_attributes::supplies_media_box(&list.pdf_resources.attributes) { page.extend_from_slice(format!(" /MediaBox [0 0 {} {}]", physical(width), physical(height)).as_bytes()); } page.extend_from_slice(b" /Resources "); if let Some(additional) = remapped.as_ref().map(|resources| &resources.pages[page_index]) && !additional.is_empty() { page.extend_from_slice(&resources.as_bytes()[..resources.len() - 2]); page.extend_from_slice(additional); page.extend_from_slice(b" >>"); } else { page.extend_from_slice(resources.as_bytes()); } if decorated { page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes()); page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]); page.extend_from_slice(format!(" /Parent 2 0 R{annots}{png_group_ref} >>").as_bytes()); } else { page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes()); } if let Some(id) = reserved_page { objects[id - 1] = page; } else { objects.push(page); } 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, 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 (index, (annotation, id)) in list.pdf_links.annotations.iter().zip(native_annotation_ids).enumerate() { use crate::pdf_device::links::AnnotationAction; let [left, top, right, bottom] = annotation.rect; let coordinates = [left, height - bottom, right, height - top].map(physical); let entries = remapped.as_ref().and_then(|resources| resources.annotations[page_index][index].as_deref()); let mut body = if let Some(entries) = entries { let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes(); body.extend_from_slice(entries); body } else { format!("<< /Type /Annot {} /Rect [{}] ", annotation.attributes, coordinates.join(" ")).into_bytes() }; match &annotation.action { AnnotationAction::User(raw) if entries.is_none() => body.extend_from_slice(raw.as_bytes()), AnnotationAction::User(_) => {} AnnotationAction::GotoName(name) => { write!(&mut body, " /Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)).unwrap(); } AnnotationAction::Catalog(action) => { // A local action may use a structure or page in a later shipout. body.extend_from_slice(b" /Subtype /Link /A "); annotation_actions.push((id, body, action)); if id == objects.len() + 1 { objects.push(Vec::new()); } continue; } } body.extend_from_slice(b" >>"); if id == objects.len() + 1 { objects.push(body); } else { objects[id - 1] = body; } } 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}"), DestinationView::FitR([left, top, right, bottom]) => { let coordinates = [left, height - bottom, right, height - top].map(physical); format!("/FitR {}", coordinates.join(" ")) } }; if let Some(number) = destination.structure { use std::collections::btree_map::Entry; match navigation.structures.entry(destination.destination.clone()) { Entry::Vacant(entry) => { let structure = remapped.as_ref().expect("structure objects were remapped") .structure_objects[&number]; objects.push(format!("[{structure} 0 R {view}]").into_bytes()); entry.insert(objects.len()); } Entry::Occupied(entry) => diagnostics.push(format!( "structure destination with the same identifier ({}) has been already used, duplicate ignored", destination_identifier(entry.key()) )), } } else { let object = || format!("[{page_id} 0 R {view}]"); match &destination.destination { DestinationId::Name(name) => { navigation.named.entry(name.clone()).or_insert_with(object); } DestinationId::Number(number) => { navigation.numbered.entry(*number).or_insert_with(|| { objects.push(object().into_bytes()); objects.len() }); } } } } } objects[1] = format!( "<< /Type /Pages /Kids [{}] /Count {}", kids.join(" "), pages.len() ) .into_bytes(); if let Some(resources) = &remapped && !resources.page_tree_attributes.is_empty() { objects[1].push(b' '); objects[1].extend_from_slice(&resources.page_tree_attributes); } objects[1].extend_from_slice(b" >>"); for (id, mut body, action) in annotation_actions { body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics)); body.extend_from_slice(b" >>"); objects[id - 1] = body; } 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 = navigation.pages .get(entry.page) .or_else(|| navigation.pages.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")); } let extra = unicode.and_then(|options| options.catalog); let mut action_object = |action| { let body = catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics); objects.push(body); objects.len() }; let action = extra.and_then(|extra| extra.open_action.as_ref()).map(&mut action_object); if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) { let action_ids: Vec<_> = extra.outlines.iter() .map(|outline| action_object(&outline.action)) .collect(); let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects); catalog.push_str(&format!(" /Outlines {outlines} 0 R")); } if !navigation.threads.is_empty() { let mut ids: Vec<_> = navigation.threads.into_values().collect(); ids.sort_unstable_by(|left, right| right.cmp(left)); let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect(); objects.push(format!("[{}]", references.join(" ")).into_bytes()); catalog.push_str(&format!(" /Threads {} 0 R", objects.len())); } let destinations = navigation.named; 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())); } let mut catalog = catalog.into_bytes(); if let Some(extra) = extra { let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref()) .unwrap_or(&extra.entries); if !entries.is_empty() { catalog.push(b'\n'); catalog.extend_from_slice(entries); catalog.push(b'\n'); } if let Some(id) = action { write!(&mut catalog, " /OpenAction {id} 0 R").unwrap(); } } catalog.extend_from_slice(b" >>"); objects[0] = catalog; if let Some(level) = final_compression { let info = match unicode { Some(options) => native_information_dictionary(crate::pdf_device::PdfInfo { entries: remapped.as_ref().and_then(|resources| resources.info.as_deref()) .unwrap_or(options.info.entries), date: options.info.date, }), None => metadata_object(metadata) .map(String::into_bytes) .unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()), }; objects.push(info); let options = &pages[0] .pdf .as_ref() .expect("validated native PDF options") .file; return objects::serialize(&objects, Some(objects.len()), options, level.max(0).min(9) as u8); } let info_ref = match metadata_object(metadata) { Some(object) => { objects.push(object.into_bytes()); format!(" /Info {} 0 R", objects.len()) } None => String::new(), }; 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