//! PDF 1.7 drawing for GridCraft print/export, with shared object and xref framing. //! //! - The 14 standard fonts (no embedding) with WinAnsiEncoding, plus approximate width tables //! ([`text_width`]) so callers can measure, align and wrap text. Latin Extended-A letters //! WinAnsiEncoding lacks (ő, ű, ł, č, …) are set in the same face through a second resource with //! a `/Differences` encoding of standard glyph names. Other characters outside //! WinAnsiEncoding (CJK and other scripts) are set in a predefined, non-embedded Adobe-GB1 CID //! font with the `UniGB-UTF16-H` CMap instead of being replaced by `?`. Symbol uses its own //! built-in encoding ([`symbol_code`]), for Greek letters and mathematical operators. //! - Arabic is shaped and set in embedded Type3 subsets, with exact shaped advances. //! - Vector drawing: rectangles, lines (solid or dashed), polygons, circles (Bézier), clipping. //! - RGBA images as RGB image XObjects with a soft mask for alpha (run-length encoded). //! - Coordinates are points with a **top-left origin** (y grows down); text `y` is the baseline. //! //! Streams are written uncompressed (images use the RunLengthDecode filter). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] mod arabic; mod metrics; mod symbol; pub use symbol::{symbol_code, symbol_width}; /// Paragraph base direction. Context follows spreadsheet reading order: the first /// non-whitespace character determines direction, including digits and punctuation. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TextDirection { #[default] Auto, Context, LeftToRight, RightToLeft, } impl TextDirection { /// Resolve once for a paragraph before wrapping it into visual lines. pub fn resolve(self, text: &str) -> Self { use unicode_bidi::{BidiClass, BidiInfo, bidi_class}; let rtl = match self { Self::Auto => BidiInfo::new(text, None).paragraphs.first().is_some_and(|p| p.level.is_rtl()), Self::Context => text.chars().find(|ch| !ch.is_whitespace()).is_some_and(|ch| matches!(bidi_class(ch), BidiClass::R | BidiClass::AL)), explicit => return explicit, }; if rtl { Self::RightToLeft } else { Self::LeftToRight } } fn level(self) -> Option { match self { Self::Auto => None, Self::LeftToRight | Self::Context => Some(unicode_bidi::Level::ltr()), Self::RightToLeft => Some(unicode_bidi::Level::rtl()), } } } /// A PDF export could not preserve the requested text or serialize its object envelope. #[derive(Clone, Debug)] pub struct Error(String); impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } } impl std::error::Error for Error {} impl From for Error { fn from(error: craft_pdf::classic::Error) -> Self { Self(error.to_string()) } } use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::fmt::Write as _; use std::hash::{Hash, Hasher}; /// RGB colour, 0–255 per channel. pub type Rgb = [u8; 3]; /// A point in page coordinates, measured from the top-left corner. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Point { pub x: f32, pub y: f32, } impl Point { pub const fn new(x: f32, y: f32) -> Self { Self { x, y } } } /// A text baseline origin and its clockwise rotation in radians. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Baseline { pub origin: Point, pub angle: f32, } /// A page-space rectangle described by its top-left corner and extent. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Rect { pub x: f32, pub y: f32, pub width: f32, pub height: f32, } impl Rect { pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self { Self { x, y, width, height } } } /// The standard 14 fonts minus ZapfDingbats. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Font { #[default] Helvetica, HelveticaBold, HelveticaOblique, HelveticaBoldOblique, TimesRoman, TimesBold, TimesItalic, TimesBoldItalic, Courier, CourierBold, CourierOblique, CourierBoldOblique, /// Greek letters and mathematical symbols, in the font's own encoding. Symbol, } /// How many fonts a document can use. const FONT_COUNT: usize = 13; /// A font family for [`Font::styled`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Family { #[default] Sans, Serif, Mono, } impl Font { pub const ALL: [Font; FONT_COUNT] = [ Font::Helvetica, Font::HelveticaBold, Font::HelveticaOblique, Font::HelveticaBoldOblique, Font::TimesRoman, Font::TimesBold, Font::TimesItalic, Font::TimesBoldItalic, Font::Courier, Font::CourierBold, Font::CourierOblique, Font::CourierBoldOblique, Font::Symbol, ]; /// PostScript base font name. pub fn base_name(self) -> &'static str { match self { Font::Helvetica => "Helvetica", Font::HelveticaBold => "Helvetica-Bold", Font::HelveticaOblique => "Helvetica-Oblique", Font::HelveticaBoldOblique => "Helvetica-BoldOblique", Font::TimesRoman => "Times-Roman", Font::TimesBold => "Times-Bold", Font::TimesItalic => "Times-Italic", Font::TimesBoldItalic => "Times-BoldItalic", Font::Courier => "Courier", Font::CourierBold => "Courier-Bold", Font::CourierOblique => "Courier-Oblique", Font::CourierBoldOblique => "Courier-BoldOblique", Font::Symbol => "Symbol", } } fn index(self) -> usize { Font::ALL.iter().position(|f| *f == self).unwrap_or(0) } /// The face of `family` with the given weight and slant. pub fn styled(family: Family, bold: bool, italic: bool) -> Font { match (family, bold, italic) { (Family::Sans, false, false) => Font::Helvetica, (Family::Sans, true, false) => Font::HelveticaBold, (Family::Sans, false, true) => Font::HelveticaOblique, (Family::Sans, true, true) => Font::HelveticaBoldOblique, (Family::Serif, false, false) => Font::TimesRoman, (Family::Serif, true, false) => Font::TimesBold, (Family::Serif, false, true) => Font::TimesItalic, (Family::Serif, true, true) => Font::TimesBoldItalic, (Family::Mono, false, false) => Font::Courier, (Family::Mono, true, false) => Font::CourierBold, (Family::Mono, false, true) => Font::CourierOblique, (Family::Mono, true, true) => Font::CourierBoldOblique, } } /// Picks a standard family for a font name: serif faces map to Times, monospaced ones to /// Courier, everything else to Helvetica. pub fn family_for(name: &str) -> Family { let n = name.to_ascii_lowercase(); const SERIF: [&str; 10] = ["times", "cambria", "georgia", "garamond", "serif", "book", "palatino", "baskerville", "tinos", "caladea"]; const MONO: [&str; 8] = ["courier", "consolas", "mono", "menlo", "lucida console", "cousine", "code", "typewriter"]; if MONO.iter().any(|m| n.contains(m)) { Family::Mono } else if SERIF.iter().any(|s| n.contains(s)) && !n.contains("sans") { Family::Serif } else { Family::Sans } } /// Whether this font can show `c` by itself (in its own encoding; for the text faces, /// without the CID fallback). pub fn can_encode(self, c: char) -> bool { match self { Font::Symbol => symbol_code(c).is_some(), _ => c == '?' || win_ansi(c) != b'?', } } /// Advance width of a character in 1/1000 em. pub fn char_width(self, c: char) -> u16 { if self == Font::Symbol { return symbol_code(c).and_then(symbol_width).unwrap_or(500); } let table: Option<&[u16; 95]> = match self { Font::Helvetica | Font::HelveticaOblique => Some(&metrics::HELVETICA), Font::HelveticaBold | Font::HelveticaBoldOblique => Some(&metrics::HELVETICA_BOLD), Font::TimesRoman | Font::TimesItalic => Some(&metrics::TIMES), Font::TimesBold | Font::TimesBoldItalic => Some(&metrics::TIMES_BOLD), _ => None, }; if needs_cid(c) { return CID_WIDTH; } let Some(table) = table else { return 600 }; let ascii = |c: char| -> Option { let i = (c as u32).checked_sub(32)? as usize; table.get(i).copied() }; if let Some(w) = ascii(c) { return w; } match c { '—' | '…' | '‰' | '™' => 1000, _ => metrics::fold(c).and_then(ascii).unwrap_or(match self { Font::TimesRoman | Font::TimesItalic | Font::TimesBold | Font::TimesBoldItalic => 500, _ => 556, }), } } } /// Whether [`text_width_with_direction`] is the sum of `text`'s character widths: not shaped, /// not reordered right to left and holding no bidi controls. A prefix's width is then a running sum. pub fn width_is_char_sum(font: Font, text: &str, direction: TextDirection) -> bool { let direction = if direction == TextDirection::Context { direction.resolve(text) } else { direction }; !arabic::shaped(font, text) && arabic::is_logical_order(text, direction) } /// Width of `text` in points when set in `font` at `size` points. /// Arabic uses shaped advances. If its font cannot render the text, measurement returns zero /// and drawing that text causes [`PdfDoc::finish`] to return the rendering error. pub fn text_width(font: Font, size: f32, text: &str) -> f32 { text_width_with_direction(font, size, text, TextDirection::Auto) } /// Width measured with the same base direction as drawing. pub fn text_width_with_direction(font: Font, size: f32, text: &str, direction: TextDirection) -> f32 { let direction = if direction == TextDirection::Context { direction.resolve(text) } else { direction }; if arabic::shaped(font, text) { return arabic::layout(font, text, direction).map(|layout| layout.width * size / 1000.0).unwrap_or(0.0); } // u64: a u32 sum overflows for ~8 million characters. let Ok(visual) = arabic::latin_visual(text, direction) else { return 0.0 }; let units: u64 = visual.chars().map(|c| u64::from(font.char_width(c))).sum(); units as f32 * size / 1000.0 } /// Unicode → WinAnsiEncoding (CP1252) byte; unmappable characters become `?`. pub fn win_ansi(c: char) -> u8 { let u = c as u32; if (0x20..0x7F).contains(&u) || (0xA0..=0xFF).contains(&u) { return u as u8; } match c { '€' => 0x80, '‚' => 0x82, 'ƒ' => 0x83, '„' => 0x84, '…' => 0x85, '†' => 0x86, '‡' => 0x87, 'ˆ' => 0x88, '‰' => 0x89, 'Š' => 0x8A, '‹' => 0x8B, 'Œ' => 0x8C, 'Ž' => 0x8E, '‘' => 0x91, '’' => 0x92, '“' => 0x93, '”' => 0x94, '•' => 0x95, '–' => 0x96, '—' => 0x97, '˜' => 0x98, '™' => 0x99, 'š' => 0x9A, '›' => 0x9B, 'œ' => 0x9C, 'ž' => 0x9E, 'Ÿ' => 0x9F, '\t' => b' ', _ => b'?', } } /// Index of the CID font in a page's font flags (after the [`Font::ALL`] faces). const CID_FONT: usize = Font::ALL.len(); /// Index of the first Latin Extended-A face (one per [`Font::ALL`] face, after the CID font). const EXT_FONT: usize = CID_FONT + 1; /// Number of font resources a page can use. const FONT_SLOTS: usize = EXT_FONT + Font::ALL.len(); /// Base font of the CID font used for characters WinAnsiEncoding lacks. const CID_BASE_FONT: &str = "STSong-Light"; /// Default glyph width of the CID font (full-width), in 1/1000 em. const CID_WIDTH: u16 = 1000; /// True when `c` has no WinAnsiEncoding byte and is drawn with the CID font. fn needs_cid(c: char) -> bool { !c.is_control() && c != '?' && win_ansi(c) == b'?' && ext_code(c).is_none() } /// The byte of `c` in the Latin Extended-A encoding (U+0100..=U+017F at 0x80..=0xFF), for /// characters WinAnsiEncoding lacks. These are set in the standard face with a `/Differences` /// encoding of standard glyph names, not in the CID font. fn ext_code(c: char) -> Option { let u = c as u32; ((0x100..=0x17F).contains(&u) && win_ansi(c) == b'?').then(|| (u - 0x80) as u8) } /// How a character is encoded in a text run. #[derive(Clone, Copy, PartialEq, Eq)] enum Run { Ansi, Ext, Cid, } fn run_kind(c: char) -> Run { if ext_code(c).is_some() { Run::Ext } else if needs_cid(c) { Run::Cid } else { Run::Ansi } } /// A PDF hex string `< … >` of `text` in the Latin Extended-A encoding of [`ext_code`]. fn pdf_ext_string(text: &str) -> String { let mut s = String::with_capacity(text.len() * 2 + 2); s.push('<'); for c in text.chars() { let _ = write!(s, "{:02X}", ext_code(c).unwrap_or(b'?')); } s.push('>'); s } /// A PDF hex string `< … >` of `text` in UTF-16BE (the `UniGB-UTF16-H` encoding). fn pdf_utf16_string(text: &str) -> String { let mut s = String::with_capacity(text.len() * 4 + 2); s.push('<'); for unit in text.encode_utf16() { let _ = write!(s, "{unit:04X}"); } s.push('>'); s } /// A PDF literal string `( … )` for `text` in WinAnsiEncoding. fn pdf_string(text: &str) -> String { pdf_string_in(text, false) } /// A PDF literal string for `text` in WinAnsiEncoding, or in Symbol's encoding (where a /// character Symbol lacks becomes `?`). fn pdf_string_in(text: &str, symbol: bool) -> String { let mut s = String::with_capacity(text.len() + 2); s.push('('); for c in text.chars() { let b = if symbol { symbol_code(c).unwrap_or(b'?') } else { win_ansi(c) }; match b { b'(' | b')' | b'\\' => { s.push('\\'); s.push(b as char); } 0x20..=0x7E => s.push(b as char), _ => { let _ = write!(s, "\\{b:03o}"); } } } s.push(')'); s } /// URI actions use byte strings. Percent-encode non-ASCII UTF-8 before PDF string escaping. fn pdf_uri_string(uri: &str) -> String { let mut ascii = String::with_capacity(uri.len()); for byte in uri.bytes() { if byte.is_ascii() { ascii.push(byte as char); } else { let _ = write!(ascii, "%{byte:02X}"); } } pdf_string(&ascii) } /// A number for a content stream: finite, short. fn n(v: f32) -> String { let v = if v.is_finite() { v.clamp(-1.0e7, 1.0e7) } else { 0.0 }; let r = (v * 1000.0).round() / 1000.0; if r == r.trunc() { format!("{}", r as i64) } else { let s = format!("{r:.3}"); s.trim_end_matches('0').trim_end_matches('.').to_string() } } /// Appends `v / 255` with at most three decimals, exactly what `n(v as f32 / 255.0)` gives, but /// without a float round trip or an allocation per channel. fn push_unit(s: &mut String, v: u8) { let m = (u32::from(v) * 1000 + 127) / 255; match m { 0 => s.push('0'), 1000 => s.push('1'), _ => { let _ = write!(s, "0.{m:03}"); while s.ends_with('0') { s.pop(); } } } } /// Appends a colour operator line without the trailing newline: `r g b rg` (fill) or `r g b RG`. fn push_rgb(s: &mut String, c: Rgb, stroke: bool) { for v in c { push_unit(s, v); s.push(' '); } s.push_str(if stroke { "RG" } else { "rg" }); } /// True when every value is finite (NaN and infinities are rejected). fn finite(v: &[f32]) -> bool { v.iter().all(|x| x.is_finite()) } /// A positive, finite extent (a width, height or radius). fn extent(v: f32) -> bool { v > 0.0 && v.is_finite() } /// A stroke width: negative, NaN and infinite become 0 (the thinnest line). fn stroke_width(w: f32) -> f32 { if w.is_finite() { w.max(0.0) } else { 0.0 } } /// The entries of a dash array (`[on, off, …]`, at most 8). A pattern the PDF specification /// forbids (any non-finite entry, or no entry that survives rounding to a positive number) is /// replaced by an empty array, i.e. a solid line. fn dash_values(dash: &[f32]) -> String { let d: Vec = dash.iter().take(8).map(|v| if v.is_finite() { v.max(0.0) } else { f32::NAN }).collect(); if !finite(&d) || !d.iter().any(|v| (v.min(1.0e7) * 1000.0).round() > 0.0) { return String::new(); } d.iter().map(|v| n(*v)).collect::>().join(" ") } struct ImageData { width: u32, height: u32, rgb: Vec, /// `None` when every pixel is fully opaque (no soft mask is written). alpha: Option>, /// Hash of all of the above, to find duplicates quickly; equality still compares the bytes. hash: u64, } impl ImageData { fn new(width: u32, height: u32, rgb: Vec, alpha: Option>) -> ImageData { let mut h = DefaultHasher::new(); width.hash(&mut h); height.hash(&mut h); rgb.hash(&mut h); alpha.hash(&mut h); ImageData { width, height, rgb, alpha, hash: h.finish() } } /// Same pixels (a hash match alone is never trusted). fn same(&self, o: &ImageData) -> bool { self.hash == o.hash && self.width == o.width && self.height == o.height && self.rgb == o.rgb && self.alpha == o.alpha } } /// The part of the graphics state the writer tracks so that a style operator is only emitted /// when it changes. `None` = not set yet on this page (or since the last restore that undid it). #[derive(Clone, Debug, Default, PartialEq)] struct Style { fill: Option, stroke: Option, /// Formatted line width. width: Option, /// Formatted dash array contents. dash: Option, /// Line join; PDF's initial value is 0 (miter). join: u8, } enum LinkTarget { Uri(String), Page { index: usize, x: f32, y: f32 }, } struct LinkAnnotation { /// PDF coordinates, with the origin at the bottom left. rect: [f32; 4], target: LinkTarget, } /// A page under construction. Obtain one with [`PdfDoc::add_page`]. pub struct Page { width: f32, height: f32, content: String, fonts: [bool; FONT_SLOTS], images: Vec, /// Indexes into `images`, by content hash; a hash match is confirmed with [`ImageData::same`]. image_index: HashMap>, /// Pixel comparisons made while looking up duplicate pictures (test instrumentation). #[cfg(test)] image_comparisons: usize, /// Style operators already in effect at the end of `content`. style: Style, /// One entry per accepted [`Page::save`], restored by [`Page::restore`]. saved: Vec