pdf: several rendering improvements
- Commit
740247d3e291e6898e50ead7ba4a053c4f1bc677- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-28 19:43 UTC (4 months ago)
- Parents
159ad1a
Diff
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex 36d48bab2d..c458744320 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -2450,7 +2450,9 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { val dst = floatArrayOf(c00.x, c00.y, c10.x, c10.y, c11.x, c11.y, c01.x, c01.y) val mat = android.graphics.Matrix() mat.setPolyToPoly(src, 0, dst, 0, 4)+ imagePaint.setBlend(prim.blend) nativeCanvas.drawBitmap(bmp, mat, imagePaint)+ imagePaint.setBlend(BlendMode.Normal) imagePaint.alpha = 255 }
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.ktindex f7ad2a8ffd..fc254dfccc 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -85,6 +85,7 @@ sealed interface PdfPrimitive { val ctm: FloatArray, val bitmap: android.graphics.Bitmap?, val alpha: Float = 1f,+ val blend: BlendMode = BlendMode.Normal, ) : PdfPrimitive /**
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktindex 3ead59c286..3988816a0f 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -17,7 +17,7 @@ import java.nio.ByteOrder * 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8 bytes], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5), f32 advance (v7), u8 fontFlags (v8 bold italic), f32 hScale (v8) * 2 Fill: u32 argb, u8 evenOdd, u16 nContours, [u16 nPts, [f32 x,y]...]... (v6), u8 blend (v5) * 3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, y]..., u8 blend (v5)- * 4 Image: 6*f32 ctm, u32 w, u32 h, u8 format, f32 alpha (v9 per-image alpha fix #2), u32 len, [bytes]+ * 4 Image: 6*f32 ctm, u32 w, u32 h, u8 format, f32 alpha (v9), u8 blend (v10), u32 len, [bytes] * 5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]..., u16 nPathOps, [...] (v4) * 6 ClipPop: empty * 7 GroupPush: u8 isolated, u8 knockout, f32 alpha, u8 blend@@ -50,7 +50,7 @@ object SafePdfParser { private const val PATHOP_CLOSE = 3 const val WIRE_MAGIC: Int = 0x50444657 // 'PDFW' little-endian as u32- const val WIRE_VERSION: Int = 9+ const val WIRE_VERSION: Int = 10 private const val WIRE_VERSION_V2 = 2 private const val WIRE_VERSION_V4 = 4 private const val WIRE_VERSION_V5 = 5@@ -58,6 +58,7 @@ object SafePdfParser { private const val WIRE_VERSION_V7 = 7 private const val WIRE_VERSION_V8 = 8 private const val WIRE_VERSION_V9 = 9+ private const val WIRE_VERSION_V10 = 10 const val MAX_PRIMITIVES = 50000 const val MAX_ANNOTATIONS = 10000 @@ -100,6 +101,7 @@ object SafePdfParser { val isV7 = wireVersion >= WIRE_VERSION_V7 val isV8 = wireVersion >= WIRE_VERSION_V8 val isV9 = wireVersion >= WIRE_VERSION_V9+ val isV10 = wireVersion >= WIRE_VERSION_V10 // Accept v1 (legacy), v2, v3 and v4. Newer versions are tolerated via // forward-compat parsing as long as the tags are known. if (wireVersion !in 1..WIRE_VERSION) {@@ -256,6 +258,7 @@ object SafePdfParser { if (buf.remaining() >= 5) { buf.get() // fmt if (isV9 && buf.remaining() >= 4) buf.float // alpha v9+ if (isV10 && buf.remaining() >= 1) buf.get() // blend v10 val len = buf.int if (len >=0 && buf.remaining() >= len) buf.position(buf.position()+len) }@@ -265,6 +268,7 @@ object SafePdfParser { if (buf.remaining() >= 5) { buf.get() if (isV9 && buf.remaining() >= 4) buf.float+ if (isV10 && buf.remaining() >= 1) buf.get() val len = buf.int if (len >=0 && buf.remaining() >= len) buf.position(buf.position()+len) }@@ -275,13 +279,17 @@ object SafePdfParser { if (buf.remaining() < 4) throw IllegalArgumentException("Image v9 alpha truncated") buf.float.coerceIn(0f,1f) } else 1f+ val imgBlend = if (isV10) {+ if (buf.remaining() < 1) throw IllegalArgumentException("Image v10 blend truncated")+ BlendMode.fromCode(buf.get().toInt() and 0xFF)+ } else BlendMode.Normal val len = buf.int if (len < 0 || len > 16*1024*1024) throw IllegalArgumentException("Image data length out of bounds $len") if (buf.remaining() < len) throw IllegalArgumentException("Image data truncated") val data = ByteArray(len) buf.get(data) val bmp = decodeBitmap(w, h, format, data)- primitives.add(PdfPrimitive.Image(ctm, bmp, imgAlpha))+ primitives.add(PdfPrimitive.Image(ctm, bmp, imgAlpha, imgBlend)) } TAG_CLIP_PUSH -> {
pdf/src/main/rust/src/afm.rs
diff --git a/pdf/src/main/rust/src/afm.rs b/pdf/src/main/rust/src/afm.rsnew file mode 100644index 0000000000..1e917bedbc--- /dev/null+++ b/pdf/src/main/rust/src/afm.rs@@ -0,0 +1,584 @@+//! Adobe Standard 14 ("Core 14") font glyph-width metrics.+//!+//! When a PDF references one of the 14 standard fonts (Helvetica, Times,+//! Courier, Symbol, ZapfDingbats and their bold/italic variants) without+//! embedding it *and* without supplying a `/Widths` array, a conforming reader+//! is expected to fall back to the publicly-standardized AFM metrics for that+//! face. This module provides those metrics as pure data so a non-embedded+//! standard font can still be spaced correctly.+//!+//! Widths are returned in *text-space units* (AFM units / 1000.0), so e.g. the+//! Helvetica space glyph is `0.278`. Values are the canonical Adobe AFM+//! `WX` numbers keyed by glyph name (the AFM `N` field).+//!+//! Pure data + lookup: no I/O, no external dependencies.++use std::collections::HashMap;++/// Returns a map of glyph-name -> advance width (in text-space units, i.e.+/// AFM width / 1000.0) for the given base font name, or `None` if the name does+/// not resolve to one of the Adobe Core-14 faces.+///+/// The name is matched case-insensitively and tolerates subset prefixes+/// (`ABCDEF+Helvetica`) and common style suffixes. Standard substitution+/// aliases are honoured (Arial -> Helvetica, TimesNewRoman -> Times, etc.).+pub(crate) fn standard_14_widths(base_font: &str) -> Option<HashMap<String, f64>> {+ let face = resolve_face(base_font)?;+ Some(match face {+ Face::Helvetica => build(HELVETICA),+ Face::HelveticaBold => build(HELVETICA_BOLD),+ Face::HelveticaOblique => build(HELVETICA),+ Face::HelveticaBoldOblique => build(HELVETICA_BOLD),+ Face::TimesRoman => build(TIMES_ROMAN),+ Face::TimesBold => build(TIMES_BOLD),+ Face::TimesItalic => build(TIMES_ITALIC),+ Face::TimesBoldItalic => build(TIMES_BOLD_ITALIC),+ Face::Courier => build_courier(),+ Face::Symbol => build(SYMBOL),+ Face::ZapfDingbats => build(ZAPF_DINGBATS),+ })+}++/// The canonical Core-14 face a base-font name resolves to. Oblique variants of+/// Helvetica share the upright metrics, so they map onto the same tables; they+/// are kept as distinct variants for clarity at the call site.+enum Face {+ Helvetica,+ HelveticaBold,+ HelveticaOblique,+ HelveticaBoldOblique,+ TimesRoman,+ TimesBold,+ TimesItalic,+ TimesBoldItalic,+ Courier,+ Symbol,+ ZapfDingbats,+}++/// Maps a (possibly subset-tagged / aliased) base-font name onto a Core-14 face.+fn resolve_face(base_font: &str) -> Option<Face> {+ // Strip a subset prefix like "ABCDEF+" then lowercase for matching.+ let name = base_font.split('+').next_back().unwrap_or(base_font);+ let n = name.to_ascii_lowercase();++ let bold = n.contains("bold");+ let italic = n.contains("italic") || n.contains("oblique");++ // Order matters: check the specific decorative faces before the text families.+ if n.contains("zapf") || n.contains("dingbat") {+ return Some(Face::ZapfDingbats);+ }+ if n.contains("symbol") {+ return Some(Face::Symbol);+ }+ if n.contains("courier") || n.contains("mono") {+ return Some(Face::Courier);+ }+ if n.contains("times") || n.contains("serif") {+ return Some(match (bold, italic) {+ (true, true) => Face::TimesBoldItalic,+ (true, false) => Face::TimesBold,+ (false, true) => Face::TimesItalic,+ (false, false) => Face::TimesRoman,+ });+ }+ if n.contains("helvetica") || n.contains("arial") || n.contains("sans") {+ return Some(match (bold, italic) {+ (true, true) => Face::HelveticaBoldOblique,+ (true, false) => Face::HelveticaBold,+ (false, true) => Face::HelveticaOblique,+ (false, false) => Face::Helvetica,+ });+ }+ None+}++/// Builds a glyph-name -> text-space-width map from an AFM `(name, WX)` slice.+fn build(entries: &[(&str, u16)]) -> HashMap<String, f64> {+ entries+ .iter()+ .map(|(name, wx)| ((*name).to_string(), f64::from(*wx) / 1000.0))+ .collect()+}++/// Courier and its variants are monospaced: every glyph advances 600 AFM units+/// (0.6). We synthesize the map from the full glyph-name set so any WinAnsi /+/// StandardEncoding name resolves to the correct 0.6.+fn build_courier() -> HashMap<String, f64> {+ HELVETICA+ .iter()+ .map(|(name, _)| ((*name).to_string(), 0.6))+ .collect()+}++// ---------------------------------------------------------------------------+// Canonical Adobe Core-14 AFM widths (name, WX-in-1000-units).+//+// These are the published, standardized AFM `WX` values. Covers the full+// StandardEncoding / WinAnsi Latin set (ASCII 0x20-0x7E plus common Latin-1+// accented glyphs and punctuation).+// ---------------------------------------------------------------------------++static HELVETICA: &[(&str, u16)] = &[+ ("space", 278), ("exclam", 278), ("quotedbl", 355), ("numbersign", 556),+ ("dollar", 556), ("percent", 889), ("ampersand", 667), ("quotesingle", 191),+ ("quoteright", 222), ("parenleft", 333), ("parenright", 333), ("asterisk", 389),+ ("plus", 584), ("comma", 278), ("hyphen", 333), ("period", 278), ("slash", 278),+ ("zero", 556), ("one", 556), ("two", 556), ("three", 556), ("four", 556),+ ("five", 556), ("six", 556), ("seven", 556), ("eight", 556), ("nine", 556),+ ("colon", 278), ("semicolon", 278), ("less", 584), ("equal", 584),+ ("greater", 584), ("question", 556), ("at", 1015),+ ("A", 667), ("B", 667), ("C", 722), ("D", 722), ("E", 667), ("F", 611),+ ("G", 778), ("H", 722), ("I", 278), ("J", 500), ("K", 667), ("L", 556),+ ("M", 833), ("N", 722), ("O", 778), ("P", 667), ("Q", 778), ("R", 722),+ ("S", 667), ("T", 611), ("U", 722), ("V", 667), ("W", 944), ("X", 667),+ ("Y", 667), ("Z", 611),+ ("bracketleft", 278), ("backslash", 278), ("bracketright", 278),+ ("asciicircum", 469), ("underscore", 556), ("grave", 333), ("quoteleft", 222),+ ("a", 556), ("b", 556), ("c", 500), ("d", 556), ("e", 556), ("f", 278),+ ("g", 556), ("h", 556), ("i", 222), ("j", 222), ("k", 500), ("l", 222),+ ("m", 833), ("n", 556), ("o", 556), ("p", 556), ("q", 556), ("r", 333),+ ("s", 500), ("t", 278), ("u", 556), ("v", 500), ("w", 722), ("x", 500),+ ("y", 500), ("z", 500),+ ("braceleft", 334), ("bar", 260), ("braceright", 334), ("asciitilde", 584),+ // Latin-1 / punctuation extras.+ ("exclamdown", 333), ("cent", 556), ("sterling", 556), ("fraction", 167),+ ("yen", 556), ("florin", 556), ("section", 556), ("currency", 556),+ ("quotedblleft", 333), ("guillemotleft", 556), ("guilsinglleft", 333),+ ("guilsinglright", 333), ("fi", 500), ("fl", 500), ("endash", 556),+ ("dagger", 556), ("daggerdbl", 556), ("periodcentered", 278), ("paragraph", 537),+ ("bullet", 350), ("quotesinglbase", 222), ("quotedblbase", 333),+ ("quotedblright", 333), ("guillemotright", 556), ("ellipsis", 1000),+ ("perthousand", 1000), ("questiondown", 611), ("acute", 333), ("circumflex", 333),+ ("tilde", 333), ("macron", 333), ("breve", 333), ("dotaccent", 333),+ ("dieresis", 333), ("ring", 333), ("cedilla", 333), ("hungarumlaut", 333),+ ("ogonek", 333), ("caron", 333), ("emdash", 1000), ("AE", 1000),+ ("ordfeminine", 370), ("Lslash", 556), ("Oslash", 778), ("OE", 1000),+ ("ordmasculine", 365), ("ae", 889), ("dotlessi", 278), ("lslash", 222),+ ("oslash", 611), ("oe", 944), ("germandbls", 611),+ ("Aacute", 667), ("Acircumflex", 667), ("Adieresis", 667), ("Agrave", 667),+ ("Aring", 667), ("Atilde", 667), ("Ccedilla", 722), ("Eacute", 667),+ ("Ecircumflex", 667), ("Edieresis", 667), ("Egrave", 667), ("Iacute", 278),+ ("Icircumflex", 278), ("Idieresis", 278), ("Igrave", 278), ("Ntilde", 722),+ ("Oacute", 778), ("Ocircumflex", 778), ("Odieresis", 778), ("Ograve", 778),+ ("Otilde", 778), ("Scaron", 667), ("Uacute", 722), ("Ucircumflex", 722),+ ("Udieresis", 722), ("Ugrave", 722), ("Yacute", 667), ("Ydieresis", 667),+ ("Zcaron", 611), ("Thorn", 667), ("Eth", 722),+ ("aacute", 556), ("acircumflex", 556), ("adieresis", 556), ("agrave", 556),+ ("aring", 556), ("atilde", 556), ("ccedilla", 500), ("eacute", 556),+ ("ecircumflex", 556), ("edieresis", 556), ("egrave", 556), ("iacute", 278),+ ("icircumflex", 278), ("idieresis", 278), ("igrave", 278), ("ntilde", 556),+ ("oacute", 556), ("ocircumflex", 556), ("odieresis", 556), ("ograve", 556),+ ("otilde", 556), ("scaron", 500), ("uacute", 556), ("ucircumflex", 556),+ ("udieresis", 556), ("ugrave", 556), ("yacute", 500), ("ydieresis", 500),+ ("zcaron", 500), ("thorn", 556), ("eth", 556), ("mu", 556), ("degree", 400),+ ("plusminus", 584), ("twosuperior", 333), ("threesuperior", 333),+ ("onesuperior", 333), ("onehalf", 834), ("onequarter", 834),+ ("threequarters", 834), ("multiply", 584), ("divide", 584), ("brokenbar", 260),+ ("logicalnot", 584), ("registered", 737), ("copyright", 737),+ ("trademark", 1000), ("minus", 584),+];++static HELVETICA_BOLD: &[(&str, u16)] = &[+ ("space", 278), ("exclam", 333), ("quotedbl", 474), ("numbersign", 556),+ ("dollar", 556), ("percent", 889), ("ampersand", 722), ("quotesingle", 238),+ ("quoteright", 278), ("parenleft", 333), ("parenright", 333), ("asterisk", 389),+ ("plus", 584), ("comma", 278), ("hyphen", 333), ("period", 278), ("slash", 278),+ ("zero", 556), ("one", 556), ("two", 556), ("three", 556), ("four", 556),+ ("five", 556), ("six", 556), ("seven", 556), ("eight", 556), ("nine", 556),+ ("colon", 333), ("semicolon", 333), ("less", 584), ("equal", 584),+ ("greater", 584), ("question", 611), ("at", 975),+ ("A", 722), ("B", 722), ("C", 722), ("D", 722), ("E", 667), ("F", 611),+ ("G", 778), ("H", 722), ("I", 278), ("J", 556), ("K", 722), ("L", 611),+ ("M", 833), ("N", 722), ("O", 778), ("P", 667), ("Q", 778), ("R", 722),+ ("S", 667), ("T", 611), ("U", 722), ("V", 667), ("W", 944), ("X", 667),+ ("Y", 667), ("Z", 611),+ ("bracketleft", 333), ("backslash", 278), ("bracketright", 333),+ ("asciicircum", 584), ("underscore", 556), ("grave", 333), ("quoteleft", 278),+ ("a", 556), ("b", 611), ("c", 556), ("d", 611), ("e", 556), ("f", 333),+ ("g", 611), ("h", 611), ("i", 278), ("j", 278), ("k", 556), ("l", 278),+ ("m", 889), ("n", 611), ("o", 611), ("p", 611), ("q", 611), ("r", 389),+ ("s", 556), ("t", 333), ("u", 611), ("v", 556), ("w", 778), ("x", 556),+ ("y", 556), ("z", 500),+ ("braceleft", 389), ("bar", 280), ("braceright", 389), ("asciitilde", 584),+ ("exclamdown", 333), ("cent", 556), ("sterling", 556), ("fraction", 167),+ ("yen", 556), ("florin", 556), ("section", 556), ("currency", 556),+ ("quotedblleft", 500), ("guillemotleft", 556), ("guilsinglleft", 333),+ ("guilsinglright", 333), ("fi", 611), ("fl", 611), ("endash", 556),+ ("dagger", 556), ("daggerdbl", 556), ("periodcentered", 278), ("paragraph", 556),+ ("bullet", 350), ("quotesinglbase", 278), ("quotedblbase", 500),+ ("quotedblright", 500), ("guillemotright", 556), ("ellipsis", 1000),+ ("perthousand", 1000), ("questiondown", 611), ("acute", 333), ("circumflex", 333),+ ("tilde", 333), ("macron", 333), ("breve", 333), ("dotaccent", 333),+ ("dieresis", 333), ("ring", 333), ("cedilla", 333), ("hungarumlaut", 333),+ ("ogonek", 333), ("caron", 333), ("emdash", 1000), ("AE", 1000),+ ("ordfeminine", 370), ("Lslash", 611), ("Oslash", 778), ("OE", 1000),+ ("ordmasculine", 365), ("ae", 889), ("dotlessi", 278), ("lslash", 278),+ ("oslash", 611), ("oe", 944), ("germandbls", 611),+ ("Aacute", 722), ("Acircumflex", 722), ("Adieresis", 722), ("Agrave", 722),+ ("Aring", 722), ("Atilde", 722), ("Ccedilla", 722), ("Eacute", 667),+ ("Ecircumflex", 667), ("Edieresis", 667), ("Egrave", 667), ("Iacute", 278),+ ("Icircumflex", 278), ("Idieresis", 278), ("Igrave", 278), ("Ntilde", 722),+ ("Oacute", 778), ("Ocircumflex", 778), ("Odieresis", 778), ("Ograve", 778),+ ("Otilde", 778), ("Scaron", 667), ("Uacute", 722), ("Ucircumflex", 722),+ ("Udieresis", 722), ("Ugrave", 722), ("Yacute", 667), ("Ydieresis", 667),+ ("Zcaron", 611), ("Thorn", 667), ("Eth", 722),+ ("aacute", 556), ("acircumflex", 556), ("adieresis", 556), ("agrave", 556),+ ("aring", 556), ("atilde", 556), ("ccedilla", 556), ("eacute", 556),+ ("ecircumflex", 556), ("edieresis", 556), ("egrave", 556), ("iacute", 278),+ ("icircumflex", 278), ("idieresis", 278), ("igrave", 278), ("ntilde", 611),+ ("oacute", 611), ("ocircumflex", 611), ("odieresis", 611), ("ograve", 611),+ ("otilde", 611), ("scaron", 556), ("uacute", 611), ("ucircumflex", 611),+ ("udieresis", 611), ("ugrave", 611), ("yacute", 556), ("ydieresis", 556),+ ("zcaron", 500), ("thorn", 611), ("eth", 611), ("mu", 611), ("degree", 400),+ ("plusminus", 584), ("twosuperior", 333), ("threesuperior", 333),+ ("onesuperior", 333), ("onehalf", 834), ("onequarter", 834),+ ("threequarters", 834), ("multiply", 584), ("divide", 584), ("brokenbar", 280),+ ("logicalnot", 584), ("registered", 737), ("copyright", 737),+ ("trademark", 1000), ("minus", 584),+];++static TIMES_ROMAN: &[(&str, u16)] = &[+ ("space", 250), ("exclam", 333), ("quotedbl", 408), ("numbersign", 500),+ ("dollar", 500), ("percent", 833), ("ampersand", 778), ("quotesingle", 180),+ ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),+ ("plus", 564), ("comma", 250), ("hyphen", 333), ("period", 250), ("slash", 278),+ ("zero", 500), ("one", 500), ("two", 500), ("three", 500), ("four", 500),+ ("five", 500), ("six", 500), ("seven", 500), ("eight", 500), ("nine", 500),+ ("colon", 278), ("semicolon", 278), ("less", 564), ("equal", 564),+ ("greater", 564), ("question", 444), ("at", 921),+ ("A", 722), ("B", 667), ("C", 667), ("D", 722), ("E", 611), ("F", 556),+ ("G", 722), ("H", 722), ("I", 333), ("J", 389), ("K", 722), ("L", 611),+ ("M", 889), ("N", 722), ("O", 722), ("P", 556), ("Q", 722), ("R", 667),+ ("S", 556), ("T", 611), ("U", 722), ("V", 722), ("W", 944), ("X", 722),+ ("Y", 722), ("Z", 611),+ ("bracketleft", 333), ("backslash", 278), ("bracketright", 333),+ ("asciicircum", 469), ("underscore", 500), ("grave", 333), ("quoteleft", 333),+ ("a", 444), ("b", 500), ("c", 444), ("d", 500), ("e", 444), ("f", 333),+ ("g", 500), ("h", 500), ("i", 278), ("j", 278), ("k", 500), ("l", 278),+ ("m", 778), ("n", 500), ("o", 500), ("p", 500), ("q", 500), ("r", 333),+ ("s", 389), ("t", 278), ("u", 500), ("v", 500), ("w", 722), ("x", 500),+ ("y", 500), ("z", 444),+ ("braceleft", 480), ("bar", 200), ("braceright", 480), ("asciitilde", 541),+ ("exclamdown", 333), ("cent", 500), ("sterling", 500), ("fraction", 167),+ ("yen", 500), ("florin", 500), ("section", 500), ("currency", 500),+ ("quotedblleft", 444), ("guillemotleft", 500), ("guilsinglleft", 333),+ ("guilsinglright", 333), ("fi", 556), ("fl", 556), ("endash", 500),+ ("dagger", 500), ("daggerdbl", 500), ("periodcentered", 250), ("paragraph", 453),+ ("bullet", 350), ("quotesinglbase", 333), ("quotedblbase", 444),+ ("quotedblright", 444), ("guillemotright", 500), ("ellipsis", 1000),+ ("perthousand", 1000), ("questiondown", 444), ("acute", 333), ("circumflex", 333),+ ("tilde", 333), ("macron", 333), ("breve", 333), ("dotaccent", 333),+ ("dieresis", 333), ("ring", 333), ("cedilla", 333), ("hungarumlaut", 333),+ ("ogonek", 333), ("caron", 333), ("emdash", 1000), ("AE", 889),+ ("ordfeminine", 276), ("Lslash", 611), ("Oslash", 722), ("OE", 889),+ ("ordmasculine", 310), ("ae", 667), ("dotlessi", 278), ("lslash", 278),+ ("oslash", 500), ("oe", 722), ("germandbls", 500),+ ("Aacute", 722), ("Acircumflex", 722), ("Adieresis", 722), ("Agrave", 722),+ ("Aring", 722), ("Atilde", 722), ("Ccedilla", 667), ("Eacute", 611),+ ("Ecircumflex", 611), ("Edieresis", 611), ("Egrave", 611), ("Iacute", 333),+ ("Icircumflex", 333), ("Idieresis", 333), ("Igrave", 333), ("Ntilde", 722),+ ("Oacute", 722), ("Ocircumflex", 722), ("Odieresis", 722), ("Ograve", 722),+ ("Otilde", 722), ("Scaron", 556), ("Uacute", 722), ("Ucircumflex", 722),+ ("Udieresis", 722), ("Ugrave", 722), ("Yacute", 722), ("Ydieresis", 722),+ ("Zcaron", 611), ("Thorn", 556), ("Eth", 722),+ ("aacute", 444), ("acircumflex", 444), ("adieresis", 444), ("agrave", 444),+ ("aring", 444), ("atilde", 444), ("ccedilla", 444), ("eacute", 444),+ ("ecircumflex", 444), ("edieresis", 444), ("egrave", 444), ("iacute", 278),+ ("icircumflex", 278), ("idieresis", 278), ("igrave", 278), ("ntilde", 500),+ ("oacute", 500), ("ocircumflex", 500), ("odieresis", 500), ("ograve", 500),+ ("otilde", 500), ("scaron", 389), ("uacute", 500), ("ucircumflex", 500),+ ("udieresis", 500), ("ugrave", 500), ("yacute", 500), ("ydieresis", 500),+ ("zcaron", 444), ("thorn", 500), ("eth", 500), ("mu", 500), ("degree", 400),+ ("plusminus", 564), ("twosuperior", 300), ("threesuperior", 300),+ ("onesuperior", 300), ("onehalf", 750), ("onequarter", 750),+ ("threequarters", 750), ("multiply", 564), ("divide", 564), ("brokenbar", 200),+ ("logicalnot", 564), ("registered", 760), ("copyright", 760),+ ("trademark", 980), ("minus", 564),+];++static TIMES_BOLD: &[(&str, u16)] = &[+ ("space", 250), ("exclam", 333), ("quotedbl", 555), ("numbersign", 500),+ ("dollar", 500), ("percent", 1000), ("ampersand", 833), ("quotesingle", 278),+ ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),+ ("plus", 570), ("comma", 250), ("hyphen", 333), ("period", 250), ("slash", 278),+ ("zero", 500), ("one", 500), ("two", 500), ("three", 500), ("four", 500),+ ("five", 500), ("six", 500), ("seven", 500), ("eight", 500), ("nine", 500),+ ("colon", 333), ("semicolon", 333), ("less", 570), ("equal", 570),+ ("greater", 570), ("question", 500), ("at", 930),+ ("A", 722), ("B", 667), ("C", 722), ("D", 722), ("E", 667), ("F", 611),+ ("G", 778), ("H", 778), ("I", 389), ("J", 500), ("K", 778), ("L", 667),+ ("M", 944), ("N", 722), ("O", 778), ("P", 611), ("Q", 778), ("R", 722),+ ("S", 556), ("T", 667), ("U", 722), ("V", 722), ("W", 1000), ("X", 722),+ ("Y", 722), ("Z", 667),+ ("bracketleft", 333), ("backslash", 278), ("bracketright", 333),+ ("asciicircum", 581), ("underscore", 500), ("grave", 333), ("quoteleft", 333),+ ("a", 500), ("b", 556), ("c", 444), ("d", 556), ("e", 444), ("f", 333),+ ("g", 500), ("h", 556), ("i", 278), ("j", 333), ("k", 556), ("l", 278),+ ("m", 833), ("n", 556), ("o", 500), ("p", 556), ("q", 556), ("r", 444),+ ("s", 389), ("t", 333), ("u", 556), ("v", 500), ("w", 722), ("x", 500),+ ("y", 500), ("z", 444),+ ("braceleft", 394), ("bar", 220), ("braceright", 394), ("asciitilde", 520),+ ("exclamdown", 333), ("cent", 500), ("sterling", 500), ("fraction", 167),+ ("yen", 500), ("florin", 500), ("section", 500), ("currency", 500),+ ("quotedblleft", 500), ("guillemotleft", 500), ("guilsinglleft", 333),+ ("guilsinglright", 333), ("fi", 556), ("fl", 556), ("endash", 500),+ ("dagger", 500), ("daggerdbl", 500), ("periodcentered", 250), ("paragraph", 540),+ ("bullet", 350), ("quotesinglbase", 333), ("quotedblbase", 500),+ ("quotedblright", 500), ("guillemotright", 500), ("ellipsis", 1000),+ ("perthousand", 1000), ("questiondown", 500), ("acute", 333), ("circumflex", 333),+ ("tilde", 333), ("macron", 333), ("breve", 333), ("dotaccent", 333),+ ("dieresis", 333), ("ring", 333), ("cedilla", 333), ("hungarumlaut", 333),+ ("ogonek", 333), ("caron", 333), ("emdash", 1000), ("AE", 1000),+ ("ordfeminine", 300), ("Lslash", 667), ("Oslash", 778), ("OE", 1000),+ ("ordmasculine", 330), ("ae", 722), ("dotlessi", 278), ("lslash", 278),+ ("oslash", 500), ("oe", 722), ("germandbls", 556),+ ("Aacute", 722), ("Acircumflex", 722), ("Adieresis", 722), ("Agrave", 722),+ ("Aring", 722), ("Atilde", 722), ("Ccedilla", 722), ("Eacute", 667),+ ("Ecircumflex", 667), ("Edieresis", 667), ("Egrave", 667), ("Iacute", 389),+ ("Icircumflex", 389), ("Idieresis", 389), ("Igrave", 389), ("Ntilde", 722),+ ("Oacute", 778), ("Ocircumflex", 778), ("Odieresis", 778), ("Ograve", 778),+ ("Otilde", 778), ("Scaron", 556), ("Uacute", 722), ("Ucircumflex", 722),+ ("Udieresis", 722), ("Ugrave", 722), ("Yacute", 722), ("Ydieresis", 722),+ ("Zcaron", 667), ("Thorn", 611), ("Eth", 722),+ ("aacute", 500), ("acircumflex", 500), ("adieresis", 500), ("agrave", 500),+ ("aring", 500), ("atilde", 500), ("ccedilla", 444), ("eacute", 444),+ ("ecircumflex", 444), ("edieresis", 444), ("egrave", 444), ("iacute", 278),+ ("icircumflex", 278), ("idieresis", 278), ("igrave", 278), ("ntilde", 556),+ ("oacute", 500), ("ocircumflex", 500), ("odieresis", 500), ("ograve", 500),+ ("otilde", 500), ("scaron", 389), ("uacute", 556), ("ucircumflex", 556),+ ("udieresis", 556), ("ugrave", 556), ("yacute", 500), ("ydieresis", 500),+ ("zcaron", 444), ("thorn", 556), ("eth", 500), ("mu", 556), ("degree", 400),+ ("plusminus", 570), ("twosuperior", 300), ("threesuperior", 300),+ ("onesuperior", 300), ("onehalf", 750), ("onequarter", 750),+ ("threequarters", 750), ("multiply", 570), ("divide", 570), ("brokenbar", 220),+ ("logicalnot", 570), ("registered", 747), ("copyright", 747),+ ("trademark", 1000), ("minus", 570),+];++static TIMES_ITALIC: &[(&str, u16)] = &[+ ("space", 250), ("exclam", 333), ("quotedbl", 420), ("numbersign", 500),+ ("dollar", 500), ("percent", 833), ("ampersand", 778), ("quotesingle", 214),+ ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),+ ("plus", 675), ("comma", 250), ("hyphen", 333), ("period", 250), ("slash", 278),+ ("zero", 500), ("one", 500), ("two", 500), ("three", 500), ("four", 500),+ ("five", 500), ("six", 500), ("seven", 500), ("eight", 500), ("nine", 500),+ ("colon", 333), ("semicolon", 333), ("less", 675), ("equal", 675),+ ("greater", 675), ("question", 500), ("at", 920),+ ("A", 611), ("B", 611), ("C", 667), ("D", 722), ("E", 611), ("F", 611),+ ("G", 722), ("H", 722), ("I", 333), ("J", 444), ("K", 667), ("L", 556),+ ("M", 833), ("N", 667), ("O", 722), ("P", 611), ("Q", 722), ("R", 611),+ ("S", 500), ("T", 556), ("U", 722), ("V", 611), ("W", 833), ("X", 611),+ ("Y", 556), ("Z", 556),+ ("bracketleft", 389), ("backslash", 278), ("bracketright", 389),+ ("asciicircum", 422), ("underscore", 500), ("grave", 333), ("quoteleft", 333),+ ("a", 500), ("b", 500), ("c", 444), ("d", 500), ("e", 444), ("f", 278),+ ("g", 500), ("h", 500), ("i", 278), ("j", 278), ("k", 444), ("l", 278),+ ("m", 722), ("n", 500), ("o", 500), ("p", 500), ("q", 500), ("r", 389),+ ("s", 389), ("t", 278), ("u", 500), ("v", 444), ("w", 667), ("x", 444),+ ("y", 444), ("z", 389),+ ("braceleft", 400), ("bar", 275), ("braceright", 400), ("asciitilde", 541),+ ("exclamdown", 389), ("cent", 500), ("sterling", 500), ("fraction", 167),+ ("yen", 500), ("florin", 500), ("section", 500), ("currency", 500),+ ("quotedblleft", 556), ("guillemotleft", 500), ("guilsinglleft", 333),+ ("guilsinglright", 333), ("fi", 500), ("fl", 500), ("endash", 500),+ ("dagger", 500), ("daggerdbl", 500), ("periodcentered", 250), ("paragraph", 523),+ ("bullet", 350), ("quotesinglbase", 333), ("quotedblbase", 556),+ ("quotedblright", 556), ("guillemotright", 500), ("ellipsis", 889),+ ("perthousand", 1000), ("questiondown", 500), ("acute", 333), ("circumflex", 333),+ ("tilde", 333), ("macron", 333), ("breve", 333), ("dotaccent", 333),+ ("dieresis", 333), ("ring", 333), ("cedilla", 333), ("hungarumlaut", 333),+ ("ogonek", 333), ("caron", 333), ("emdash", 889), ("AE", 889),+ ("ordfeminine", 276), ("Lslash", 556), ("Oslash", 722), ("OE", 944),+ ("ordmasculine", 310), ("ae", 667), ("dotlessi", 278), ("lslash", 278),+ ("oslash", 500), ("oe", 667), ("germandbls", 500),+ ("Aacute", 611), ("Acircumflex", 611), ("Adieresis", 611), ("Agrave", 611),+ ("Aring", 611), ("Atilde", 611), ("Ccedilla", 667), ("Eacute", 611),+ ("Ecircumflex", 611), ("Edieresis", 611), ("Egrave", 611), ("Iacute", 333),+ ("Icircumflex", 333), ("Idieresis", 333), ("Igrave", 333), ("Ntilde", 667),+ ("Oacute", 722), ("Ocircumflex", 722), ("Odieresis", 722), ("Ograve", 722),+ ("Otilde", 722), ("Scaron", 500), ("Uacute", 722), ("Ucircumflex", 722),+ ("Udieresis", 722), ("Ugrave", 722), ("Yacute", 556), ("Ydieresis", 556),+ ("Zcaron", 556), ("Thorn", 611), ("Eth", 722),+ ("aacute", 500), ("acircumflex", 500), ("adieresis", 500), ("agrave", 500),+ ("aring", 500), ("atilde", 500), ("ccedilla", 444), ("eacute", 444),+ ("ecircumflex", 444), ("edieresis", 444), ("egrave", 444), ("iacute", 278),+ ("icircumflex", 278), ("idieresis", 278), ("igrave", 278), ("ntilde", 500),+ ("oacute", 500), ("ocircumflex", 500), ("odieresis", 500), ("ograve", 500),+ ("otilde", 500), ("scaron", 389), ("uacute", 500), ("ucircumflex", 500),+ ("udieresis", 500), ("ugrave", 500), ("yacute", 444), ("ydieresis", 444),+ ("zcaron", 389), ("thorn", 500), ("eth", 500), ("mu", 500), ("degree", 400),+ ("plusminus", 675), ("twosuperior", 300), ("threesuperior", 300),+ ("onesuperior", 300), ("onehalf", 750), ("onequarter", 750),+ ("threequarters", 750), ("multiply", 675), ("divide", 675), ("brokenbar", 275),+ ("logicalnot", 675), ("registered", 760), ("copyright", 760),+ ("trademark", 980), ("minus", 675),+];++static TIMES_BOLD_ITALIC: &[(&str, u16)] = &[+ ("space", 250), ("exclam", 389), ("quotedbl", 555), ("numbersign", 500),+ ("dollar", 500), ("percent", 833), ("ampersand", 778), ("quotesingle", 278),+ ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),+ ("plus", 570), ("comma", 250), ("hyphen", 333), ("period", 250), ("slash", 278),+ ("zero", 500), ("one", 500), ("two", 500), ("three", 500), ("four", 500),+ ("five", 500), ("six", 500), ("seven", 500), ("eight", 500), ("nine", 500),+ ("colon", 333), ("semicolon", 333), ("less", 570), ("equal", 570),+ ("greater", 570), ("question", 500), ("at", 832),+ ("A", 667), ("B", 667), ("C", 667), ("D", 722), ("E", 667), ("F", 667),+ ("G", 722), ("H", 778), ("I", 389), ("J", 500), ("K", 667), ("L", 611),+ ("M", 889), ("N", 722), ("O", 722), ("P", 611), ("Q", 722), ("R", 667),+ ("S", 556), ("T", 611), ("U", 722), ("V", 667), ("W", 889), ("X", 667),+ ("Y", 611), ("Z", 611),+ ("bracketleft", 333), ("backslash", 278), ("bracketright", 333),+ ("asciicircum", 570), ("underscore", 500), ("grave", 333), ("quoteleft", 333),+ ("a", 500), ("b", 500), ("c", 444), ("d", 500), ("e", 444), ("f", 333),+ ("g", 500), ("h", 556), ("i", 278), ("j", 278), ("k", 500), ("l", 278),+ ("m", 778), ("n", 556), ("o", 500), ("p", 500), ("q", 500), ("r", 389),+ ("s", 389), ("t", 278), ("u", 556), ("v", 444), ("w", 667), ("x", 500),+ ("y", 444), ("z", 389),+ ("braceleft", 348), ("bar", 220), ("braceright", 348), ("asciitilde", 570),+ ("exclamdown", 389), ("cent", 500), ("sterling", 500), ("fraction", 167),+ ("yen", 500), ("florin", 500), ("section", 500), ("currency", 500),+ ("quotedblleft", 500), ("guillemotleft", 500), ("guilsinglleft", 333),+ ("guilsinglright", 333), ("fi", 556), ("fl", 556), ("endash", 500),+ ("dagger", 500), ("daggerdbl", 500), ("periodcentered", 250), ("paragraph", 500),+ ("bullet", 350), ("quotesinglbase", 333), ("quotedblbase", 500),+ ("quotedblright", 500), ("guillemotright", 500), ("ellipsis", 1000),+ ("perthousand", 1000), ("questiondown", 500), ("acute", 333), ("circumflex", 333),+ ("tilde", 333), ("macron", 333), ("breve", 333), ("dotaccent", 333),+ ("dieresis", 333), ("ring", 333), ("cedilla", 333), ("hungarumlaut", 333),+ ("ogonek", 333), ("caron", 333), ("emdash", 1000), ("AE", 944),+ ("ordfeminine", 266), ("Lslash", 611), ("Oslash", 722), ("OE", 944),+ ("ordmasculine", 300), ("ae", 722), ("dotlessi", 278), ("lslash", 278),+ ("oslash", 500), ("oe", 722), ("germandbls", 500),+ ("Aacute", 667), ("Acircumflex", 667), ("Adieresis", 667), ("Agrave", 667),+ ("Aring", 667), ("Atilde", 667), ("Ccedilla", 667), ("Eacute", 667),+ ("Ecircumflex", 667), ("Edieresis", 667), ("Egrave", 667), ("Iacute", 389),+ ("Icircumflex", 389), ("Idieresis", 389), ("Igrave", 389), ("Ntilde", 722),+ ("Oacute", 722), ("Ocircumflex", 722), ("Odieresis", 722), ("Ograve", 722),+ ("Otilde", 722), ("Scaron", 556), ("Uacute", 722), ("Ucircumflex", 722),+ ("Udieresis", 722), ("Ugrave", 722), ("Yacute", 611), ("Ydieresis", 611),+ ("Zcaron", 611), ("Thorn", 611), ("Eth", 722),+ ("aacute", 500), ("acircumflex", 500), ("adieresis", 500), ("agrave", 500),+ ("aring", 500), ("atilde", 500), ("ccedilla", 444), ("eacute", 444),+ ("ecircumflex", 444), ("edieresis", 444), ("egrave", 444), ("iacute", 278),+ ("icircumflex", 278), ("idieresis", 278), ("igrave", 278), ("ntilde", 556),+ ("oacute", 500), ("ocircumflex", 500), ("odieresis", 500), ("ograve", 500),+ ("otilde", 500), ("scaron", 389), ("uacute", 556), ("ucircumflex", 556),+ ("udieresis", 556), ("ugrave", 556), ("yacute", 444), ("ydieresis", 444),+ ("zcaron", 389), ("thorn", 500), ("eth", 500), ("mu", 576), ("degree", 400),+ ("plusminus", 570), ("twosuperior", 300), ("threesuperior", 300),+ ("onesuperior", 300), ("onehalf", 750), ("onequarter", 750),+ ("threequarters", 750), ("multiply", 570), ("divide", 570), ("brokenbar", 220),+ ("logicalnot", 606), ("registered", 747), ("copyright", 747),+ ("trademark", 1000), ("minus", 570),+];++// Symbol uses its own encoding; widths are keyed by the AFM glyph names.+static SYMBOL: &[(&str, u16)] = &[+ ("space", 250), ("exclam", 333), ("universal", 713), ("numbersign", 500),+ ("existential", 549), ("percent", 833), ("ampersand", 778), ("suchthat", 439),+ ("parenleft", 333), ("parenright", 333), ("asteriskmath", 500), ("plus", 549),+ ("comma", 250), ("minus", 549), ("period", 250), ("slash", 278),+ ("zero", 500), ("one", 500), ("two", 500), ("three", 500), ("four", 500),+ ("five", 500), ("six", 500), ("seven", 500), ("eight", 500), ("nine", 500),+ ("colon", 278), ("semicolon", 278), ("less", 549), ("equal", 549),+ ("greater", 549), ("question", 444), ("congruent", 549),+ ("Alpha", 722), ("Beta", 667), ("Chi", 722), ("Delta", 612), ("Epsilon", 611),+ ("Phi", 763), ("Gamma", 603), ("Eta", 722), ("Iota", 333), ("theta1", 631),+ ("Kappa", 722), ("Lambda", 686), ("Mu", 889), ("Nu", 722), ("Omicron", 722),+ ("Pi", 768), ("Theta", 741), ("Rho", 556), ("Sigma", 592), ("Tau", 611),+ ("Upsilon", 690), ("sigma1", 439), ("Omega", 768), ("Xi", 645), ("Psi", 795),+ ("Zeta", 611), ("bracketleft", 333), ("therefore", 863), ("bracketright", 333),+ ("perpendicular", 658), ("underscore", 500), ("radicalex", 500),+ ("alpha", 631), ("beta", 549), ("chi", 549), ("delta", 494), ("epsilon", 439),+ ("phi", 521), ("gamma", 411), ("eta", 603), ("iota", 329), ("phi1", 603),+ ("kappa", 549), ("lambda", 549), ("mu", 576), ("nu", 521), ("omicron", 549),+ ("pi", 549), ("theta", 521), ("rho", 549), ("sigma", 603), ("tau", 439),+ ("upsilon", 576), ("omega1", 713), ("omega", 686), ("xi", 493), ("psi", 686),+ ("zeta", 494), ("braceleft", 480), ("bar", 200), ("braceright", 480),+ ("similar", 549),+];++// ZapfDingbats decorative face; widths keyed by the AFM `aNNN` glyph names.+static ZAPF_DINGBATS: &[(&str, u16)] = &[+ ("space", 278),+ ("a1", 974), ("a2", 961), ("a202", 974), ("a3", 980), ("a4", 719),+ ("a5", 789), ("a119", 790), ("a118", 791), ("a117", 690), ("a11", 960),+ ("a12", 939), ("a13", 549), ("a14", 855), ("a15", 911), ("a16", 933),+ ("a105", 911), ("a17", 945), ("a18", 974), ("a19", 755), ("a20", 846),+ ("a21", 762), ("a22", 761), ("a23", 571), ("a24", 677), ("a25", 763),+ ("a26", 760), ("a27", 759), ("a28", 754), ("a6", 494), ("a7", 552),+ ("a8", 537), ("a9", 577), ("a10", 692), ("a29", 786), ("a30", 788),+ ("a31", 788), ("a32", 790), ("a33", 793), ("a34", 794), ("a35", 816),+ ("a36", 823), ("a37", 789), ("a38", 841), ("a39", 823), ("a40", 833),+ ("a41", 816), ("a42", 831), ("a43", 923), ("a44", 744), ("a45", 723),+ ("a46", 749), ("a47", 790), ("a48", 792), ("a49", 695), ("a50", 776),+ ("a51", 768), ("a52", 792), ("a53", 759), ("a54", 707), ("a55", 708),+ ("a56", 682), ("a57", 701), ("a58", 826), ("a59", 815), ("a60", 789),+ ("a61", 789), ("a62", 707), ("a63", 687), ("a64", 696), ("a65", 689),+ ("a66", 786), ("a67", 787), ("a68", 713), ("a69", 791), ("a70", 785),+ ("a71", 791), ("a72", 873), ("a73", 761), ("a74", 762), ("a203", 762),+ ("a75", 759), ("a204", 759), ("a76", 892), ("a77", 892), ("a78", 788),+ ("a79", 784), ("a81", 438), ("a82", 138), ("a83", 277), ("a84", 415),+ ("a97", 392), ("a98", 392), ("a99", 668), ("a100", 668), ("a89", 390),+ ("a90", 390), ("a93", 317), ("a94", 317), ("a91", 276), ("a92", 276),+ ("a205", 509), ("a85", 509), ("a206", 410), ("a86", 410), ("a87", 234),+ ("a88", 234), ("a95", 334), ("a96", 334), ("a101", 732), ("a102", 544),+ ("a103", 544), ("a104", 910), ("a106", 667), ("a107", 760), ("a108", 760),+ ("a112", 776), ("a111", 595), ("a110", 694), ("a109", 626), ("a120", 788),+ ("a121", 788), ("a122", 788), ("a123", 788), ("a124", 788), ("a125", 788),+ ("a126", 788), ("a127", 788), ("a128", 788), ("a129", 788), ("a130", 788),+ ("a131", 788), ("a132", 788), ("a133", 788), ("a134", 788), ("a135", 788),+ ("a136", 788), ("a137", 788), ("a138", 788), ("a139", 788), ("a140", 788),+ ("a141", 788), ("a142", 788), ("a143", 788), ("a144", 788), ("a145", 788),+ ("a146", 788), ("a147", 788), ("a148", 788), ("a149", 788), ("a150", 788),+ ("a151", 788), ("a152", 788), ("a153", 788), ("a154", 788), ("a155", 788),+ ("a156", 788), ("a157", 788), ("a158", 788), ("a159", 788), ("a160", 894),+ ("a161", 838), ("a163", 1016), ("a164", 458), ("a196", 748), ("a165", 924),+ ("a192", 748), ("a166", 918), ("a167", 927), ("a168", 928), ("a169", 928),+ ("a170", 834), ("a171", 873), ("a172", 828), ("a173", 924), ("a162", 924),+ ("a174", 917), ("a175", 930), ("a176", 931), ("a177", 463), ("a178", 883),+ ("a179", 836), ("a193", 836), ("a180", 867), ("a199", 867), ("a181", 696),+ ("a200", 696), ("a182", 874), ("a201", 760), ("a183", 946), ("a184", 771),+ ("a197", 865), ("a185", 771), ("a194", 888), ("a198", 967), ("a186", 888),+ ("a195", 831), ("a187", 873), ("a188", 927), ("a189", 970), ("a190", 918),+ ("a191", 748),+];++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn helvetica_metrics() {+ let m = standard_14_widths("Helvetica").unwrap();+ assert_eq!(m["space"], 0.278);+ assert_eq!(m["W"], 0.944);+ }++ #[test]+ fn times_metrics() {+ let m = standard_14_widths("Times-Roman").unwrap();+ assert_eq!(m["space"], 0.25);+ }++ #[test]+ fn courier_is_monospaced() {+ let m = standard_14_widths("Courier").unwrap();+ assert_eq!(m["m"], 0.6);+ assert_eq!(m["i"], 0.6);+ }++ #[test]+ fn tolerates_subset_prefix_and_aliases() {+ assert!(standard_14_widths("ABCDEF+Helvetica-BoldOblique").is_some());+ assert!(standard_14_widths("Arial").is_some());+ assert!(standard_14_widths("Arial-BoldMT").is_some());+ assert!(standard_14_widths("TimesNewRoman").is_some());+ assert!(standard_14_widths("Symbol").is_some());+ assert!(standard_14_widths("ZapfDingbats").is_some());+ assert!(standard_14_widths("SomeRandomFont").is_none());+ }+}
pdf/src/main/rust/src/annotations.rs
diff --git a/pdf/src/main/rust/src/annotations.rs b/pdf/src/main/rust/src/annotations.rsindex bd396a4b06..219eb62b8a 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -56,6 +56,15 @@ pub(crate) fn render_annotations(doc: &Document, page_id: ObjectId, base: &Mat, if flags & 0b10 != 0 || flags & 0b10_0000 != 0 { continue; }+ // Skip annotations on an optional-content group that is turned OFF.+ if dict.get(b"OC").ok().map(|oc| crate::oc_object_hidden(doc, oc)).unwrap_or(false) {+ continue;+ }+ // Popup annotations are only shown when their parent is open; don't paint+ // them inline on the page.+ if dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()) == Some(b"Popup") {+ continue;+ } render_annotation(doc, dict, base, prims); } }@@ -80,10 +89,14 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base: let normal = match ap.get(b"N").ok().and_then(|o| deref(doc, o)) { Some(Object::Stream(s)) => s, Some(Object::Dictionary(states)) => {+ // The appearance sub-state is selected by /AS. When /AS is missing or+ // doesn't match, fall back to the "Off" state (a button's default) —+ // NOT an arbitrary first entry, which is nondeterministic (HashMap order)+ // and can render an unchecked box as checked. let as_name = dict.get(b"AS").ok().and_then(|o| o.as_name().ok()); let picked = as_name .and_then(|n| states.get(n).ok())- .or_else(|| states.iter().next().map(|(_, v)| v));+ .or_else(|| states.get(b"Off").ok()); match picked.and_then(|o| deref(doc, o)) { Some(Object::Stream(s)) => s, _ => {@@ -359,6 +372,39 @@ pub(crate) fn synthesize_annotation_appearance( } } }+ b"FreeText" => {+ // Border/background box plus the /Contents text (no /AP fallback).+ let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];+ if let Some(f) = fill { emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal); }+ if let Some(s) = stroke {+ let mut ring = poly.clone(); ring.push(poly[0]);+ let mut sgs = gs.clone(); sgs.stroke = s;+ emit_stroke(prims, std::slice::from_ref(&ring), &sgs);+ }+ let text = dict.get(b"Contents").ok().and_then(|o| deref(doc, o)).and_then(|o| match o { Object::String(b,_) => Some(decode_pdf_text(b)), _ => None }).unwrap_or_default();+ if !text.is_empty() {+ let size = 12.0_f64;+ let dsize = (size * scale) as f32;+ let mut y = rect[3] - size; // top-down in page space+ for line in text.split(['\n', '\r']).filter(|l| !l.is_empty()) {+ if prims.len() >= MAX_PRIMITIVES || y < rect[1] { break; }+ let (px, py) = dev(rect[0] + 2.0, y);+ emit_annot_text(prims, px as f32, py as f32, dsize, 0xFF00_0000, line);+ y -= size * 1.2;+ }+ }+ }+ b"Text" => {+ // Sticky-note icon: a small filled square marker at the annotation rect.+ let x0 = rect[0]; let y1 = rect[3];+ let s = 18.0_f64.min((rect[2]-rect[0]).abs().max(12.0));+ let poly = vec![dev(x0, y1 - s), dev(x0 + s, y1 - s), dev(x0 + s, y1), dev(x0, y1)];+ let col = stroke.or(fill).unwrap_or(0xFFFFE0_00); // note yellow+ emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(col, ca), false, 1.0, BlendMode::Normal);+ let mut ring = poly.clone(); ring.push(poly[0]);+ let mut sgs = gs.clone(); sgs.stroke = 0xFF00_0000;+ emit_stroke(prims, std::slice::from_ref(&ring), &sgs);+ } b"Redact" => { // Show redaction box outline so user knows where to apply let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];@@ -368,6 +414,25 @@ pub(crate) fn synthesize_annotation_appearance( } } +/// Emit a single line of substitute-font text at a device-space baseline (used+/// for synthesized FreeText appearances).+fn emit_annot_text(prims: &mut Vec<Prim>, x: f32, y: f32, size: f32, argb: u32, text: &str) {+ prims.push(Prim::Text {+ x, y, size, argb,+ text: text.to_string(),+ stroke_argb: None,+ stroke_width: None,+ advance: size * 0.5,+ render_mode: 0,+ blend: BlendMode::Normal,+ is_bold: false,+ is_italic: false,+ font_family: 0,+ outline: false,+ h_scale: 1.0,+ });+}+ /// Device-space bounding box [x0,y0,x1,y1] of a polygon. fn bbox_of(poly: &[(f64,f64)]) -> [f64;4] { let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
pdf/src/main/rust/src/cff.rs
diff --git a/pdf/src/main/rust/src/cff.rs b/pdf/src/main/rust/src/cff.rsindex 10dd3aee92..d6efe810ce 100644--- a/pdf/src/main/rust/src/cff.rs+++ b/pdf/src/main/rust/src/cff.rs@@ -387,6 +387,49 @@ fn parse_custom_encoding(d: &[u8], off: usize) -> Option<(HashMap<u8, u16>, Hash Some((base, supplements)) } +/// For a CID-keyed CFF (Top DICT has ROS, op 1230), parse the charset — which for+/// a CIDFont maps GID -> CID — and invert it to CID -> GID so a CID can select the+/// right glyph outline. Returns `None` for non-CID CFF or on parse failure.+pub fn cid_to_gid_map(d: &[u8]) -> Option<HashMap<u32, u16>> {+ if u8a(d, 0)? != 1 {+ return None;+ }+ let hdr_size = u8a(d, 2)? as usize;+ if hdr_size < 4 || hdr_size > d.len() {+ return None;+ }+ let name_idx = read_index(d, hdr_size)?;+ let top_idx = read_index(d, name_idx.end)?;+ let string_idx = read_index(d, top_idx.end)?;+ let (ts, te) = *top_idx.entries.first()?;+ let top = parse_dict(d.get(ts..te)?);+ // Only CID-keyed fonts (ROS present) need CID->GID remapping.+ if !top.contains_key(&1230) {+ return None;+ }+ let cs_off = *top.get(&17)?.first()? as usize; // CharStrings INDEX offset (op 17)+ let nglyphs = read_index(d, cs_off)?.entries.len();+ if nglyphs == 0 || nglyphs > 65535 {+ return None;+ }+ let charset_off = top.get(&15).and_then(|v| v.first()).copied().unwrap_or(0.0) as usize;+ let mut map: HashMap<u32, u16> = HashMap::new();+ map.insert(0, 0); // CID 0 (.notdef) -> GID 0+ if charset_off > 2 {+ // Custom charset: entries are CIDs for CID-keyed fonts.+ let gid_to_cid = parse_charset(d, charset_off, nglyphs, string_idx.entries.len())?;+ for (gid, cid) in gid_to_cid {+ map.insert(cid as u32, gid);+ }+ } else {+ // Predefined charset offset (0/1/2): treat as identity (CID == GID).+ for gid in 0..nglyphs as u16 {+ map.insert(gid as u32, gid);+ }+ }+ Some(map)+}+ /// charset (format 0/1/2) -> GID -> SID with bounds checking. fn parse_charset(d: &[u8], off: usize, nglyphs: usize, custom_string_count: usize) -> Option<HashMap<u16, usize>> { if off == 0 {
pdf/src/main/rust/src/color.rs
diff --git a/pdf/src/main/rust/src/color.rs b/pdf/src/main/rust/src/color.rsindex 8bd5e3933d..e266104535 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -254,6 +254,34 @@ pub(crate) fn cs_kind_ncomp(kind: &CsKind) -> u8 { } } +/// Initial color value when a color space is selected via `cs`/`CS` (PDF 8.6.8):+/// black for device/CIE/ICC spaces, index 0 for Indexed, full tint (all 1.0) for+/// Separation/DeviceN. Returns `None` for Pattern (color unchanged).+pub(crate) fn cs_initial_color(doc: &Document, kind: &CsKind, resources: &HashMap<Vec<u8>, ObjectId>) -> Option<u32> {+ let comps: Vec<f64> = match kind {+ CsKind::Separation { .. } => vec![1.0],+ CsKind::DeviceN { names, .. } => vec![1.0; names.len().max(1)],+ CsKind::Indexed { .. } => vec![0.0],+ CsKind::Pattern { .. } => return None,+ _ => vec![0.0; cs_kind_ncomp(kind).max(1) as usize],+ };+ eval_cs_to_rgb(doc, kind, &comps, resources)+}++/// Default per-component value range for a color space, used to decode Indexed+/// palette bytes and image samples. All spaces use [0,1] except Lab, whose L is+/// [0,100] and a*/b* follow the space's /Range.+pub(crate) fn cs_kind_default_decode(kind: &CsKind) -> Vec<(f64, f64)> {+ match kind {+ CsKind::Lab { range, .. } => vec![+ (0.0, 100.0),+ (range[0][0], range[0][1]),+ (range[1][0], range[1][1]),+ ],+ _ => vec![(0.0, 1.0); cs_kind_ncomp(kind) as usize],+ }+}+ pub(crate) fn read_white_point(dict: &lopdf::Dictionary) -> Option<[f64;3]> { let arr = dict.get(b"WhitePoint").ok().and_then(|o| o.as_array().ok())?; if arr.len()>=3 {@@ -286,6 +314,39 @@ pub(crate) fn read_lab_range(dict: &lopdf::Dictionary) -> Option<[[f64;2];2]> { } else { None } } +/// Bradford chromatic adaptation of an XYZ triple from `src_white` to the D65+/// white used by the sRGB matrix. Used for CalRGB/CalGray with non-D65 whites.+fn adapt_to_d65(x: f64, y: f64, z: f64, src_white: [f64; 3]) -> (f64, f64, f64) {+ const B: [[f64; 3]; 3] = [+ [0.8951, 0.2664, -0.1614],+ [-0.7502, 1.7135, 0.0367],+ [0.0389, -0.0685, 1.0296],+ ];+ const BINV: [[f64; 3]; 3] = [+ [0.9869929, -0.1470543, 0.1599627],+ [0.4323053, 0.5183603, 0.0492912],+ [-0.0085287, 0.0400428, 0.9684867],+ ];+ let mul = |m: &[[f64; 3]; 3], v: [f64; 3]| {+ [+ m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],+ m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],+ m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],+ ]+ };+ let d65 = [0.95047, 1.0, 1.08883];+ let s = mul(&B, src_white);+ let d = mul(&B, d65);+ let lms = mul(&B, [x, y, z]);+ let scaled = [+ lms[0] * d[0] / s[0].abs().max(1e-9),+ lms[1] * d[1] / s[1].abs().max(1e-9),+ lms[2] * d[2] / s[2].abs().max(1e-9),+ ];+ let out = mul(&BINV, scaled);+ (out[0], out[1], out[2])+}+ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<u32> { match kind { CsKind::DeviceGray => {@@ -381,16 +442,15 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re Some(rgb_to_argb(gamma(r_lin), gamma(g_lin), gamma(b_lin))) } CsKind::CalRGB { white, gamma, matrix } => {- // CalRGB: A^GammaR, B^GammaG, C^GammaB -> XYZ via Matrix * white scaling per spec.+ // CalRGB: A^GammaR, B^GammaG, C^GammaB -> XYZ via Matrix, then adapt+ // from the space's /WhitePoint to D65 before XYZ -> sRGB (PDF 8.6.5.3). let a = comps.get(0).copied().unwrap_or(0.0).clamp(0.0,1.0).powf(gamma[0].clamp(0.1,10.0)); let b = comps.get(1).copied().unwrap_or(0.0).clamp(0.0,1.0).powf(gamma[1].clamp(0.1,10.0)); let c = comps.get(2).copied().unwrap_or(0.0).clamp(0.0,1.0).powf(gamma[2].clamp(0.1,10.0)); let x = matrix[0][0]*a + matrix[0][1]*b + matrix[0][2]*c; let y = matrix[1][0]*a + matrix[1][1]*b + matrix[1][2]*c; let z = matrix[2][0]*a + matrix[2][1]*b + matrix[2][2]*c;- // Apply whitepoint scaling (Cal uses white for full-int picture, but PDFWhite default ~D65? Actually spec white 0.9505,1,1.0890)- // D50->D65 Bradford from earlier Lab reused for Cal* too via same helper later.- let _ = white; // white already encoded in Matrix usually, ignore extra+ let (x, y, z) = adapt_to_d65(x, y, z, *white); let r_lin = 3.2406 * x -1.5372 * y -0.4986 * z; let g_lin = -0.9689 * x +1.8758 * y +0.0415 * z; let b_lin = 0.0557 * x -0.2040 * y +1.0570 * z;@@ -403,9 +463,8 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re CsKind::CalGray { gamma, white, .. } => { let g = comps.get(0).copied().unwrap_or(0.0).clamp(0.0,1.0); let a = g.powf(gamma.clamp(0.1,10.0));- let x = white[0]*a;- let y = white[1]*a;- let z = white[2]*a;+ // Scale the whitepoint by the gray value, then adapt to D65.+ let (x, y, z) = adapt_to_d65(white[0]*a, white[1]*a, white[2]*a, *white); let r_lin = 3.2406 * x -1.5372 * y -0.4986 * z; let g_lin = -0.9689 * x +1.8758 * y +0.0415 * z; let b_lin = 0.0557 * x -0.2040 * y +1.0570 * z;@@ -443,14 +502,24 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re let off = idx * *base_ncomp as usize; if off + *base_ncomp as usize <= lookup.len() { let slice = &lookup[off..off+*base_ncomp as usize];- // Convert lookup bytes 0..255 to 0..1 floats- let comps_f: Vec<f64> = slice.iter().map(|b| *b as f64 /255.0).collect();+ // Each lookup byte 0..255 maps to the RANGE of the corresponding base+ // component (PDF 8.6.6.3): [0,1] for device spaces, but [0,100]/Range+ // for a Lab base — dividing by 255 unconditionally would darken Lab.+ let ranges = cs_kind_default_decode(base);+ let comps_f: Vec<f64> = slice.iter().enumerate().map(|(i, b)| {+ let (lo, hi) = ranges.get(i).copied().unwrap_or((0.0, 1.0));+ lo + (*b as f64 / 255.0) * (hi - lo)+ }).collect(); eval_cs_to_rgb(doc, base, &comps_f, cs_resources) } else { None } }- CsKind::Separation { alt, tint_fn, .. } => {+ CsKind::Separation { name, alt, tint_fn } => {+ // The special colorant /None produces no marks (fully transparent).+ if name == b"None" {+ return Some(0x0000_0000);+ } let t = comps.get(0).copied().unwrap_or(1.0).clamp(0.0, 1.0); if let Some(tf) = tint_fn { let alt_comps = tf.eval(&[t]);@@ -473,7 +542,11 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re } Some(gray_to_argb(1.0 - t)) }- CsKind::DeviceN { alt, tint_fn, .. } => {+ CsKind::DeviceN { names, alt, tint_fn } => {+ // If every colorant is /None the region produces no marks.+ if !names.is_empty() && names.iter().all(|n| n == b"None") {+ return Some(0x0000_0000);+ } if let Some(tf) = tint_fn { // Evaluate the tint transform over all N input components. let alt_comps = tf.eval(comps);
pdf/src/main/rust/src/draw.rs
diff --git a/pdf/src/main/rust/src/draw.rs b/pdf/src/main/rust/src/draw.rsindex 75341e1751..ce58f7d555 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -156,16 +156,25 @@ pub(crate) fn show_string( let italic = fi.style.italic; let family = fi.family; let has_program = fi.glyph_program.is_some();+ // Vertical writing mode (WMode 1): glyphs advance down the page and are+ // centered on the vertical line (PDF 9.4.4). Metrics use typical CJK values.+ let vertical = fi.wmode == 1; fi.for_each_code(bytes, |code, is_space| {- let tx = fi.width(code) * tfs + gs.char_spacing + if is_space { gs.word_spacing } else { 0.0 };+ let w0 = fi.width(code); // horizontal glyph width (em)+ let tx = w0 * tfs + gs.char_spacing + if is_space { gs.word_spacing } else { 0.0 }; let glyph_advance_user = tx * th; // accurate advance using /Widths /W- // Map to device for advance field (used in search rect) - we store device advance as size * glyphCount? Actually plan says emit advance in Text prim extra- // Compute device-space x advance via trm x scale: approximated via y_scale already for size, but use x scale of CTM? We'll store glyph_advance_user * y_scale as device equivalent for simplicity, but Kotlin uses Paint.measureText fallback.- // Emit glyphs for every mode except 3 (invisible). Clip-only mode 7- // still emits (with no paint) so Kotlin can add the outline to the clip.+ // Placement point (text space) and pen advance depend on writing mode.+ // Vertical: center horizontally (-w0/2), drop by the vertical origin+ // (~0.88 em), and advance one em downward (plus Tc/Tw).+ let (place_x, place_y, advance) = if vertical {+ let adv_down = tfs + gs.char_spacing + if is_space { gs.word_spacing } else { 0.0 };+ (-0.5 * w0 * tfs, pen - 0.880 * tfs, -adv_down)+ } else {+ (pen, gs.rise, glyph_advance_user)+ }; if gs.render_mode != 3 {- let (x, y) = transform(&trm, pen, gs.rise);+ let (x, y) = transform(&trm, place_x, place_y); let mut s = String::new(); fi.push_code(code, &mut s); if !s.is_empty() {@@ -175,7 +184,11 @@ pub(crate) fn show_string( let has_stroke = matches!(gs.render_mode, 1|2|5|6); let clip_only = gs.render_mode == 7; let rm = gs.render_mode as u8;- let glyph_device_adv = (glyph_advance_user * x_scale) as f32;+ let glyph_device_adv = if vertical {+ (advance.abs() * y_scale) as f32+ } else {+ (glyph_advance_user * x_scale) as f32+ }; // Real embedded outline for pure paint modes (0/1/2). Clip modes // (4-7) keep the substitute-glyph path so Kotlin can build the clip. let outline = if has_program && matches!(gs.render_mode, 0 | 1 | 2) {@@ -188,7 +201,7 @@ pub(crate) fn show_string( // translate(pen, rise) · Tm · CTM. Mirrors the Type 3 pipeline. let font_matrix: Mat = [1.0 / upm, 0.0, 0.0, 1.0 / upm, 0.0, 0.0]; let scale_m: Mat = [tfs * th, 0.0, 0.0, tfs, 0.0, 0.0];- let place = translate(pen, gs.rise);+ let place = translate(place_x, place_y); let m1 = mat_mul(&scale_m, &mat_mul(&place, &trm)); let glyph_ctm = mat_mul(&font_matrix, &m1); let dev: Vec<Vec<(f32, f32)>> = contours@@ -310,7 +323,7 @@ pub(crate) fn show_string( } } }- pen += glyph_advance_user;+ pen += advance; }); // Enforce primitive cap if prims.len() > MAX_PRIMITIVES {
pdf/src/main/rust/src/fonts.rs
diff --git a/pdf/src/main/rust/src/fonts.rs b/pdf/src/main/rust/src/fonts.rsindex a2c1e4f97d..8938c385f8 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -25,6 +25,9 @@ pub(crate) struct FontInfo { /// `code -> unicode char` recovered from an embedded TrueType `cmap`, for /// re-encoded subset fonts without `/ToUnicode`. Preferred over `encoding`. pub(crate) cmap_uni: HashMap<u32, char>,+ /// Type0 `/Encoding` CMap mapping character codes -> CIDs (non-Identity CJK+ /// encodings). `None` for Identity-H/V (code == CID) and simple fonts.+ pub(crate) cmap: Option<cmap::EncodingCMap>, /// `code (or CID) -> glyph width` in text-space units (glyph units / 1000). pub(crate) widths: HashMap<u32, f64>, /// Fallback width (glyph units / 1000) for codes absent from `widths`.@@ -76,19 +79,31 @@ impl FontInfo { /// string, honoring this font's code width (1 or 2 bytes). pub(crate) fn for_each_code(&self, bytes: &[u8], mut f: impl FnMut(u32, bool)) { if self.two_byte {- let mut i = 0;- while i + 1 < bytes.len() {- let code = ((bytes[i] as u32) << 8) | bytes[i + 1] as u32;- // Word spacing (Tw) should apply to all unicode spaces, not just 0x20.- // Check full-width (0x3000), NBSP (0xA0), and ToUnicode == " " or- // any whitespace-like mapping.- let to_uni = self.to_unicode.as_ref().and_then(|m| m.get(&code));- let is_space = code == 32- || code == 0x00A0- || code == 0x3000- || to_uni.map(|s| s == " " || s.chars().any(|c| c.is_whitespace())).unwrap_or(false);- f(code, is_space);- i += 2;+ match &self.cmap {+ // Non-Identity CMap: segment bytes by the codespace (variable+ // length) and yield the raw character code. Width/glyph lookups+ // map code -> CID via `to_cid`.+ Some(cm) => {+ let mut i = 0;+ while i < bytes.len() {+ let n = cm.code_len(bytes[i]).clamp(1, 4).min(bytes.len() - i);+ let mut c = 0u32;+ for k in 0..n { c = (c << 8) | bytes[i + k] as u32; }+ // Tw applies only to a single-byte code 32.+ f(c, n == 1 && c == 32);+ i += n;+ }+ }+ // Identity-H/V: fixed 2-byte codes, code == CID.+ None => {+ let mut i = 0;+ while i + 1 < bytes.len() {+ let code = ((bytes[i] as u32) << 8) | bytes[i + 1] as u32;+ // Word spacing (Tw) never applies to 2-byte codes (PDF 9.3.3).+ f(code, false);+ i += 2;+ }+ } } } else { for &b in bytes {@@ -101,9 +116,20 @@ impl FontInfo { } } - /// Width of `code` in text-space units (glyph units / 1000).+ /// Map a raw character code to a CID via the `/Encoding` CMap (identity when+ /// there is no CMap, i.e. Identity-H/V or simple fonts).+ pub(crate) fn to_cid(&self, code: u32) -> u32 {+ match &self.cmap {+ Some(cm) => cm.to_cid(code),+ None => code,+ }+ }++ /// Width of `code` in text-space units (glyph units / 1000). Widths (`/W`)+ /// are keyed by CID, so the code is mapped through the CMap first. pub(crate) fn width(&self, code: u32) -> f64 {- self.widths.get(&code).copied().unwrap_or(self.default_width)+ let cid = self.to_cid(code);+ self.widths.get(&cid).copied().unwrap_or(self.default_width) } pub(crate) fn push_code(&self, code: u32, out: &mut String) {@@ -160,10 +186,31 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { }) .map(|data| cmap::parse(&data)); + // Type0 /Encoding CMap: Identity-H/V need no code->CID map (code == CID); a+ // named predefined CMap can't be embedded here (best-effort identity), but an+ // embedded CMap stream is parsed for real code->CID mapping and WMode.+ let mut encoding_cmap: Option<cmap::EncodingCMap> = None;+ let mut cmap_wmode: u8 = 0;+ if two_byte {+ match font.get(b"Encoding").ok().and_then(|o| deref(doc, o)) {+ Some(Object::Name(n)) => {+ let name = String::from_utf8_lossy(n);+ if name.ends_with("-V") { cmap_wmode = 1; }+ // Identity-H/V and unembeddable predefined names -> identity (None).+ }+ Some(Object::Stream(s)) => {+ let cm = cmap::parse_encoding_cmap(&stream_data(s));+ cmap_wmode = cm.wmode;+ encoding_cmap = Some(cm);+ }+ _ => {}+ }+ }+ // WMode: 0 horizontal (default), 1 vertical. Detect from Type0 font dict and descendant. let wmode: u8 = font.get(b"WMode").ok().and_then(num).map(|v| if v >= 1.0 { 1 } else { 0 }).unwrap_or(0) as u8; let desc_wmode: u8 = font.get(b"DescendantFonts").ok().and_then(|o| deref(doc, o)).and_then(|o| match o { Object::Array(a) => a.first(), _ => None }).and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()).and_then(|d| d.get(b"WMode").ok()).and_then(num).map(|v| if v >= 1.0 { 1 } else { 0 }).unwrap_or(wmode as u8) as u8;- let effective_wmode = desc_wmode.max(wmode as u8);+ let effective_wmode = desc_wmode.max(wmode as u8).max(cmap_wmode); // CIDToGIDMap let cid_to_gid: Option<HashMap<u32, u16>> = {@@ -202,7 +249,7 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { None }; - let (widths, default_width) = if two_byte {+ let (mut widths, default_width) = if two_byte { cid_widths(doc, font) } else if is_type3 { let fm_scale = t3.as_ref().map(|t| t.font_matrix[0]).unwrap_or(0.001);@@ -348,6 +395,28 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { crate::outlines::encoding_differences(doc, font) }; + // --- Standard-14 metrics fallback ---+ // A non-embedded standard font (Helvetica/Times/Courier/Symbol/ZapfDingbats)+ // may omit /Widths; use the Core-14 AFM widths (keyed by glyph name) so text+ // is spaced correctly instead of at a flat 0.5 em. Resolve code -> glyph name+ // via /Differences, falling back to StandardEncoding.+ if !two_byte && !is_type3 && widths.is_empty() {+ if let Some(afm) = crate::afm::standard_14_widths(&base_font_name) {+ for code in 0u32..=255 {+ let name = glyph_names.get(&code).cloned().or_else(|| {+ crate::type1::STANDARD_ENCODING.iter()+ .find(|(c, _)| *c as u32 == code)+ .map(|(_, n)| (*n).to_string())+ });+ if let Some(name) = name {+ if let Some(w) = afm.get(&name) {+ widths.insert(code, *w);+ }+ }+ }+ }+ }+ // --- Generic family detection for substitute shaping (0 sans, 1 serif, 2 mono) --- // The embedded base font is not rendered directly; Kotlin picks a matching // system typeface, so we only need the broad family. BaseFont names (including@@ -383,6 +452,7 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { to_unicode, encoding, cmap_uni,+ cmap: encoding_cmap, widths, default_width, t3,@@ -1209,10 +1279,18 @@ use std::io::Cursor; m } - /// StandardEncoding: for the ASCII range it matches Latin-1; good enough as- /// a base to which /Differences are applied.+ /// Adobe StandardEncoding: matches Latin-1 for the core ASCII letters/digits+ /// but differs across punctuation (0x27 quoteright, 0x60 quoteleft) and the+ /// whole 0x80–0xFF range, so it is built from the real name table rather than+ /// aliased to Latin-1. fn standard() -> HashMap<u32, char> {- latin1()+ let mut m = HashMap::new();+ for (code, name) in crate::type1::STANDARD_ENCODING {+ if let Some(c) = glyph_to_char(name) {+ m.insert(*code as u32, c);+ }+ }+ m } /// Codes 0x20–0xFF mapped as Latin-1 (identity to Unicode).@@ -1486,6 +1564,128 @@ use std::io::Cursor; c } + /// A Type0 `/Encoding` CMap: variable-length codespace ranges plus code->CID+ /// mappings (from `begincidrange`/`begincidchar`), and the writing mode.+ #[derive(Default)]+ pub struct EncodingCMap {+ /// (lo, hi, byte_len) codespace ranges.+ pub codespace: Vec<(u32, u32, u8)>,+ pub single: HashMap<u32, u32>,+ /// (lo, hi, cid_of_lo) contiguous ranges.+ pub ranges: Vec<(u32, u32, u32)>,+ pub wmode: u8,+ }++ impl EncodingCMap {+ /// Map a character code to a CID (identity fallback if unmapped).+ pub fn to_cid(&self, code: u32) -> u32 {+ if let Some(c) = self.single.get(&code) {+ return *c;+ }+ for &(lo, hi, c0) in &self.ranges {+ if code >= lo && code <= hi {+ return c0 + (code - lo);+ }+ }+ code+ }++ /// Byte length of the code beginning with `first_byte`, using the+ /// codespace ranges (defaults to 2 bytes, the Identity case).+ pub fn code_len(&self, first_byte: u8) -> usize {+ for &(lo, hi, n) in &self.codespace {+ let shift = (n.saturating_sub(1)) * 8;+ let flo = (lo >> shift) & 0xFF;+ let fhi = (hi >> shift) & 0xFF;+ if (first_byte as u32) >= flo && (first_byte as u32) <= fhi {+ return n as usize;+ }+ }+ if self.codespace.is_empty() { 2 } else { self.codespace[0].2 as usize }+ }+ }++ /// Parse a Type0 `/Encoding` CMap stream. Handles `codespacerange`,+ /// `cidrange`, `cidchar`, and `/WMode`. Numeric CID operands are decimal.+ pub fn parse_encoding_cmap(data: &[u8]) -> EncodingCMap {+ let mut cm = EncodingCMap::default();+ // Lightweight token scan: hex strings <..>, decimal integers, keywords.+ #[derive(PartialEq)]+ enum T { Hex(Vec<u8>), Int(u32), Kw(String) }+ let mut toks: Vec<T> = Vec::new();+ let mut i = 0;+ while i < data.len() {+ let b = data[i];+ if b == b'<' {+ let mut hex = String::new();+ i += 1;+ while i < data.len() && data[i] != b'>' {+ if !data[i].is_ascii_whitespace() { hex.push(data[i] as char); }+ i += 1;+ }+ i += 1;+ toks.push(T::Hex(hex_to_bytes(&hex)));+ } else if b.is_ascii_digit() {+ let s = i;+ while i < data.len() && data[i].is_ascii_digit() { i += 1; }+ let n: u32 = std::str::from_utf8(&data[s..i]).ok().and_then(|x| x.parse().ok()).unwrap_or(0);+ toks.push(T::Int(n));+ } else if b.is_ascii_alphabetic() || b == b'/' {+ let s = i;+ i += 1;+ while i < data.len() && (data[i].is_ascii_alphanumeric() || data[i] == b'/' || data[i] == b'.') { i += 1; }+ toks.push(T::Kw(String::from_utf8_lossy(&data[s..i]).into_owned()));+ } else {+ i += 1;+ }+ }+ let byte_len = |bytes: &[u8]| -> u8 { bytes.len().clamp(1, 4) as u8 };+ let mut j = 0;+ while j < toks.len() {+ match &toks[j] {+ T::Kw(k) if k == "/WMode" => {+ if let Some(T::Int(w)) = toks.get(j + 1) { cm.wmode = if *w >= 1 { 1 } else { 0 }; }+ j += 1;+ }+ T::Kw(k) if k == "begincodespacerange" => {+ j += 1;+ while j + 1 < toks.len() {+ if let (T::Hex(lo), T::Hex(hi)) = (&toks[j], &toks[j + 1]) {+ cm.codespace.push((code(lo), code(hi), byte_len(lo)));+ j += 2;+ } else { break; }+ }+ }+ T::Kw(k) if k == "begincidrange" => {+ j += 1;+ while j + 2 < toks.len() {+ match (&toks[j], &toks[j + 1], &toks[j + 2]) {+ (T::Hex(lo), T::Hex(hi), T::Int(cid)) => {+ cm.ranges.push((code(lo), code(hi), *cid));+ j += 3;+ }+ _ => break,+ }+ }+ }+ T::Kw(k) if k == "begincidchar" => {+ j += 1;+ while j + 1 < toks.len() {+ match (&toks[j], &toks[j + 1]) {+ (T::Hex(c), T::Int(cid)) => {+ cm.single.insert(code(c), *cid);+ j += 2;+ }+ _ => break,+ }+ }+ }+ _ => { j += 1; }+ }+ }+ cm+ }+ fn utf16be_units(bytes: &[u8]) -> Vec<u16> { bytes .chunks(2)
pdf/src/main/rust/src/graphics_state.rs
diff --git a/pdf/src/main/rust/src/graphics_state.rs b/pdf/src/main/rust/src/graphics_state.rsindex 04700915af..4632a4a18d 100644--- a/pdf/src/main/rust/src/graphics_state.rs+++ b/pdf/src/main/rust/src/graphics_state.rs@@ -85,6 +85,9 @@ pub(crate) struct GraphicsState { pub(crate) h_scale: f64, /// Text rise (Ts), user-space units. pub(crate) rise: f64,+ /// Text leading (TL), user-space units. Part of the text state, so it is+ /// saved/restored by q/Q.+ pub(crate) leading: f64, /// Text rendering mode (Tr). 3 = invisible, 7 = clip-only (not drawn). pub(crate) render_mode: i64, /// Dash pattern (user-space segment lengths) and phase; empty = solid.@@ -123,6 +126,7 @@ impl Default for GraphicsState { word_spacing: 0.0, h_scale: 1.0, rise: 0.0,+ leading: 0.0, render_mode: 0, dash: Vec::new(), dash_phase: 0.0,
pdf/src/main/rust/src/images.rs
diff --git a/pdf/src/main/rust/src/images.rs b/pdf/src/main/rust/src/images.rsindex 29cd316161..4f5b968df7 100644--- a/pdf/src/main/rust/src/images.rs+++ b/pdf/src/main/rust/src/images.rs@@ -298,6 +298,58 @@ pub(crate) fn ocg_is_visible_alias(doc: &Document, id: ObjectId) -> Option<bool> Some(is_ocg_visible(doc, id)) } +/// Evaluate an OCMD (Optional Content Membership Dictionary) `/OCGs` + `/P`+/// visibility policy. Returns true if the membership resolves to HIDDEN.+fn ocmd_hidden(doc: &Document, d: &Dictionary) -> bool {+ let mut ids: Vec<ObjectId> = Vec::new();+ match d.get(b"OCGs").ok() {+ Some(Object::Reference(id)) => ids.push(*id),+ Some(Object::Array(a)) => {+ for o in a {+ if let Ok(id) = o.as_reference() { ids.push(id); }+ }+ }+ _ => {}+ }+ if ids.is_empty() {+ return false; // no member groups -> visible+ }+ let vis: Vec<bool> = ids.iter().map(|id| is_ocg_visible(doc, *id)).collect();+ let policy = d.get(b"P").ok().and_then(|o| o.as_name().ok());+ let visible = match policy {+ Some(b"AllOn") => vis.iter().all(|v| *v),+ Some(b"AnyOff") => vis.iter().any(|v| !*v),+ Some(b"AllOff") => vis.iter().all(|v| !*v),+ _ => vis.iter().any(|v| *v), // AnyOn (default)+ };+ !visible+}++/// Decide whether marked content / an XObject tagged with the given `/OC` object+/// (an OCG or OCMD, possibly an indirect reference) should be HIDDEN.+pub(crate) fn oc_object_hidden(doc: &Document, obj: &Object) -> bool {+ match obj {+ Object::Reference(id) => {+ if let Ok(Object::Dictionary(d)) = doc.get_object(*id) {+ if d.get(b"Type").ok().and_then(|o| o.as_name().ok()) == Some(b"OCMD") {+ return ocmd_hidden(doc, d);+ }+ }+ !is_ocg_visible(doc, *id)+ }+ Object::Dictionary(d) => {+ if d.get(b"Type").ok().and_then(|o| o.as_name().ok()) == Some(b"OCMD") {+ ocmd_hidden(doc, d)+ } else {+ // Inline OCG dict without an object id can't be matched against the+ // ON/OFF lists; default to visible.+ false+ }+ }+ _ => false,+ }+}+ /// Whether a colorspace requires the full `eval_cs_to_rgb` path (vs the fast /// `comps_to_rgb` device path which is equivalent for plain RGB/Gray/CMYK).@@ -369,11 +421,27 @@ fn image_samples_to_rgba( let kind = match cs_kind { Some(k) if cs_needs_eval(&k) => k, _ => {- // Fast device path.+ // Fast device path. Apply the image's /Decode array (default identity+ // [0,1] per component) — e.g. a DeviceGray image with /Decode [1 0]+ // must be inverted. Device spaces have <=4 components.+ let has_decode = decode_arr.len() >= ncomp * 2+ && (0..ncomp).any(|c| decode_arr[c * 2] != 0.0 || (decode_arr[c * 2 + 1] - 1.0).abs() > 1e-9); for i in 0..w * h { let base = i * ncomp; let (r, g, b) = if base + ncomp <= decoded_comps.len() {- comps_to_rgb(&decoded_comps[base..base + ncomp], ncomp as u8)+ if has_decode {+ let mut tmp = [0u8; 4];+ for c in 0..ncomp.min(4) {+ let dmin = decode_arr[c * 2];+ let dmax = decode_arr[c * 2 + 1];+ let v = decoded_comps[base + c] as f64 / 255.0;+ let mapped = (dmin + v * (dmax - dmin)).clamp(0.0, 1.0);+ tmp[c] = (mapped * 255.0).round() as u8;+ }+ comps_to_rgb(&tmp[..ncomp.min(4)], ncomp as u8)+ } else {+ comps_to_rgb(&decoded_comps[base..base + ncomp], ncomp as u8)+ } } else { (0, 0, 0) };@@ -464,6 +532,24 @@ fn image_samples_to_rgba( /// Extract a drawable image from an image XObject stream, or `None` if the /// format is unsupported (e.g. JPEG2000, exotic color spaces).+/// Turn a decoded 1-bit codec raster (black-on-white RGBA) into a stencil: dark+/// pixels are painted with `fill_argb` (opaque), light pixels become transparent.+/// `invert` swaps the sense (for `/Decode [1 0]`).+fn stencilize(rgba: &mut [u8], fill_argb: u32, invert: bool) {+ let fr = ((fill_argb >> 16) & 0xFF) as u8;+ let fg = ((fill_argb >> 8) & 0xFF) as u8;+ let fb = (fill_argb & 0xFF) as u8;+ for px in rgba.chunks_exact_mut(4) {+ let luma = (px[0] as u32 * 299 + px[1] as u32 * 587 + px[2] as u32 * 114) / 1000;+ let paint = if invert { luma >= 128 } else { luma < 128 };+ if paint {+ px[0] = fr; px[1] = fg; px[2] = fb; px[3] = 255;+ } else {+ px[3] = 0;+ }+ }+}+ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u32, cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<ImageData> { let dict = &stream.dict; let w = dict.get(b"Width").ok().and_then(num)? as u32;@@ -491,6 +577,16 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u let is_ccitt = has_kind(filters::FilterKind::Ccitt); let is_jbig2 = has_kind(filters::FilterKind::Jbig2); + // A CCITT/JBIG2 stencil (`/ImageMask true`) must paint the current fill color+ // where the sample selects "paint" and be transparent elsewhere — not render+ // an opaque black/white raster. Detect it up front so the codec branches can+ // stencil their output.+ let mask_stencil = matches!(dict.get(b"ImageMask").ok(), Some(Object::Boolean(true)));+ let mask_invert = mask_stencil && matches!(+ dict.get(b"Decode").ok().and_then(|o| deref(doc, o)),+ Some(Object::Array(a)) if a.first().and_then(num) == Some(1.0)+ );+ // JBIG2: attempt with Globals if is_jbig2 { let mut globals_bytes: Option<Vec<u8>> = None;@@ -532,6 +628,7 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u // Attempt decode from raw content if let Some((jw,jh,mut rgba)) = jbig2::decode_jbig2(&stream.content, globals_bytes.as_deref(), w, h) {+ if mask_stencil { stencilize(&mut rgba, fill_argb, mask_invert); return Some(ImageData{ w: jw, h: jh, format: 0, data: rgba }); } let smask = read_smask(doc, dict, jw, jh); apply_smask(&mut rgba, &smask); if let Some(ck) = read_color_key_mask(doc, dict) { apply_color_key_mask(&mut rgba, &Some(ck)); }@@ -541,6 +638,7 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u let raw = stream.content.clone(); if let Some(chain) = filters::decode_stream_chain(raw, &specs, doc) { if let Some((jw, jh, mut rgba)) = jbig2::decode_jbig2(&chain, globals_bytes.as_deref(), w, h) {+ if mask_stencil { stencilize(&mut rgba, fill_argb, mask_invert); return Some(ImageData{ w: jw, h: jh, format: 0, data: rgba }); } let smask = read_smask(doc, dict, jw, jh); apply_smask(&mut rgba, &smask); if let Some(ck) = read_color_key_mask(doc, dict) { apply_color_key_mask(&mut rgba, &Some(ck)); }@@ -613,6 +711,10 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u } } }+ if mask_stencil {+ stencilize(&mut rgba, fill_argb, mask_invert);+ return Some(ImageData { w: out_w, h: out_h, format: 0, data: rgba });+ } let smask = read_smask(doc, dict, out_w, out_h); apply_smask(&mut rgba, &smask); if let Some(ck) = read_color_key_mask(doc, dict) { apply_color_key_mask(&mut rgba, &Some(ck)); }@@ -918,18 +1020,25 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm: // Function: full PDF function support (Type 0/2/3/4, or array-of-functions). let pdf_func = dict.get(b"Function").ok().and_then(|o| PdfFunction::parse(doc, o)); - // Extend [bool bool]+ // Extend [bool bool] — spec default is [false false] (ISO 32000 Table 79). let extend = dict.get(b"Extend").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())- .map(|a| a.iter().filter_map(|o| deref(doc, o).map(|v| matches!(v, Object::Boolean(true)))).collect::<Vec<bool>>()).unwrap_or(vec![true,true]);+ .map(|a| a.iter().filter_map(|o| deref(doc, o).map(|v| matches!(v, Object::Boolean(true)))).collect::<Vec<bool>>()).unwrap_or(vec![false,false]);+ // Domain [t0 t1] maps the normalized axis parameter to the function domain+ // (default [0 1]).+ let domain = dict.get(b"Domain").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())+ .map(|a| a.iter().filter_map(|o| deref(doc, o).and_then(num)).collect::<Vec<f64>>())+ .filter(|v| v.len() >= 2).unwrap_or(vec![0.0, 1.0]); let w = size; let h = size; let mut rgba = vec![0u8; (w*h*4) as usize]; - // Helpers to evaluate color at t 0..1 via function+ // Helpers to evaluate color at t 0..1 via function. The normalized parameter+ // is first mapped through /Domain before the function is evaluated. let eval_func = |t: f64| -> Option<Vec<f64>> { if let Some(ref f) = pdf_func {- return Some(f.eval(&[t]));+ let td = domain[0] + t * (domain[1] - domain[0]);+ return Some(f.eval(&[td])); } // If no function, try to use Background as single color. if let Some(ref bgc) = bg {@@ -963,8 +1072,8 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm: if coords.len()>=6 { radial_shading_param( &coords,- extend.get(0).copied().unwrap_or(true),- extend.get(1).copied().unwrap_or(true),+ extend.get(0).copied().unwrap_or(false),+ extend.get(1).copied().unwrap_or(false), fx, fy, ).unwrap_or(f64::NAN) } else { 0.0 }@@ -977,7 +1086,7 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm: // Extend handling let t_clamped = if t<0.0 {- if extend.get(0).copied().unwrap_or(true) { 0.0 } else {+ if extend.get(0).copied().unwrap_or(false) { 0.0 } else { // background outside // pixel stays background/transparent let idx = (y*w as usize + x)*4;@@ -994,7 +1103,7 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm: continue; } } else if t>1.0 {- if extend.get(1).copied().unwrap_or(true) { 1.0 } else {+ if extend.get(1).copied().unwrap_or(false) { 1.0 } else { let idx = (y*w as usize + x)*4; if let Some(ref bgc) = bg { let cs = color_space_obj.as_ref().unwrap_or(&CsKind::DeviceRGB);@@ -1692,7 +1801,11 @@ pub(crate) fn read_smask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u3 let sh = s.dict.get(b"Height").ok().and_then(num).unwrap_or(h as f64) as usize; if sw == 0 || sh == 0 || sw > 20000 || sh > 20000 { return None; } // P0 fix critical #1: previously DCT/JPX only; now uses unified decoder for all filters- let gray = decode_mask_stream_gray(doc, s, sw, sh)?;+ let mut gray = decode_mask_stream_gray(doc, s, sw, sh)?;+ // Honor the SMask's own /Decode [1 0], which inverts the alpha ramp.+ if matches!(s.dict.get(b"Decode").ok().and_then(|o| deref(doc, o)), Some(Object::Array(a)) if a.first().and_then(num) == Some(1.0)) {+ for v in gray.iter_mut() { *v = 255 - *v; }+ } // Bilinear resample sw*sh -> w*h let (w_us, h_us) = (w as usize, h as usize); if sw == w_us && sh == h_us { return Some(gray); }
pdf/src/main/rust/src/interpret.rs
diff --git a/pdf/src/main/rust/src/interpret.rs b/pdf/src/main/rust/src/interpret.rsindex 69b858d5ed..b9e0630900 100644--- a/pdf/src/main/rust/src/interpret.rs+++ b/pdf/src/main/rust/src/interpret.rs@@ -153,6 +153,7 @@ pub(crate) fn interpret_content( gs: GraphicsState, clip_depth: usize, group_depth: usize,+ clip_bbox: Option<[f64; 4]>, } let mut stack: Vec<SavedState> = Vec::new(); let mut q_overflow: usize = 0;@@ -163,13 +164,30 @@ pub(crate) fn interpret_content( path_ops: Vec<PathOp>, } - // single ClipPush per W op preserving holes via full path_ops (fix high #7)+ // single ClipPush per W op preserving holes via full path_ops (fix high #7).+ // Also intersects the new clip's device-space bbox into `clip_bbox` so that+ // later `sh` operators know the current clip region even after `W n` commits. #[inline]- fn emit_one_clip(prims: &mut Vec<Prim>, pc: PendingClip, clip_depth: &mut usize, text_only: bool, oc_hidden: bool) {+ fn emit_one_clip(prims: &mut Vec<Prim>, pc: PendingClip, clip_depth: &mut usize, clip_bbox: &mut Option<[f64;4]>, text_only: bool, oc_hidden: bool) { if text_only || oc_hidden { return; } if *clip_depth >= MAX_CLIP_DEPTH { return; } let has_valid = pc.polys.iter().any(|poly| poly.len() >= 3 && shoelace_area(poly).abs() >= 1e-3) || !pc.path_ops.is_empty(); if !has_valid && pc.polys.is_empty() && pc.path_ops.is_empty() { return; }+ // Intersect the accumulated clip bbox with this clip's device bbox.+ let mut nx0 = f64::INFINITY; let mut ny0 = f64::INFINITY;+ let mut nx1 = f64::NEG_INFINITY; let mut ny1 = f64::NEG_INFINITY;+ for poly in &pc.polys {+ for &(x, y) in poly {+ nx0 = nx0.min(x); ny0 = ny0.min(y);+ nx1 = nx1.max(x); ny1 = ny1.max(y);+ }+ }+ if nx1 > nx0 && ny1 > ny0 {+ *clip_bbox = Some(match *clip_bbox {+ Some(cur) => [cur[0].max(nx0), cur[1].max(ny0), cur[2].min(nx1), cur[3].min(ny1)],+ None => [nx0, ny0, nx1, ny1],+ });+ } let pts: Vec<(f32,f32)> = pc.polys.first().map(|p| p.iter().map(|&(x,y)| (x as f32, y as f32)).collect()).unwrap_or_default(); let po = if pc.path_ops.is_empty() { None } else { Some(pc.path_ops) }; prims.push(Prim::ClipPush { even_odd: pc.even_odd, pts, path_ops: po });@@ -178,7 +196,6 @@ pub(crate) fn interpret_content( let mut text_matrix = IDENTITY; let mut line_matrix = IDENTITY;- let mut leading = 0.0_f64; let mut subpaths: Vec<Vec<(f64, f64)>> = Vec::new(); let mut cur_user: (f64, f64) = (0.0, 0.0);@@ -187,6 +204,9 @@ pub(crate) fn interpret_content( let mut oc_stack: Vec<bool> = Vec::new(); // true means currently invisible due to OCG suppression let mut group_depth: usize = 0; let mut pending_clip: Option<PendingClip> = None;+ // Device-space bbox of the accumulated (committed) clip region, tracked so the+ // `sh` operator can fill the current clip even after `W n` clears pending_clip.+ let mut current_clip_bbox: Option<[f64; 4]> = None; let mut clip_depth: usize = 0; let mut clip_path_ops: Vec<PathOp> = Vec::new(); // current clip path ops before W // Whether the current text object (BT..ET) used a clip render mode (Tr 4-7).@@ -200,7 +220,7 @@ pub(crate) fn interpret_content( "q" => { const MAX_SUBPATHS_LOCAL: usize = 20000; if stack.len() < MAX_GRAPHICS_STACK {- stack.push(SavedState { gs: gs.clone(), clip_depth, group_depth });+ stack.push(SavedState { gs: gs.clone(), clip_depth, group_depth, clip_bbox: current_clip_bbox }); } else { q_overflow += 1; }@@ -220,6 +240,7 @@ pub(crate) fn interpret_content( if !text_only { prims.push(Prim::GroupPop); } group_depth = group_depth.saturating_sub(1); }+ current_clip_bbox = saved.clip_bbox; gs = saved.gs; } }@@ -362,13 +383,13 @@ pub(crate) fn interpret_content( "W" => { // P0 fix: emit as single ClipPush preserving holes via path_ops (was per-poly loop) if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } pending_clip = Some(PendingClip { even_odd: false, polys: subpaths.clone(), path_ops: clip_path_ops.clone() }); } "W*" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } pending_clip = Some(PendingClip { even_odd: true, polys: subpaths.clone(), path_ops: clip_path_ops.clone() }); }@@ -466,7 +487,7 @@ pub(crate) fn interpret_content( } "S" | "s" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } if op.operator == "s" { if let Some(sp) = subpaths.last_mut() {@@ -488,12 +509,12 @@ pub(crate) fn interpret_content( } "f" | "F" | "f*" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } if !text_only && !oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len(); if let Some(pid) = gs.fill_pattern {- paint_pattern_fill(doc, pid, &subpaths, op.operator == "f*", &pattern_base_ctm, gs.fill, prims, depth);+ paint_pattern_fill(doc, pid, &subpaths, op.operator == "f*", &pattern_base_ctm, gs.fill, gs.alpha_fill as f32, gs.blend_mode, prims, depth); } else if prims.len() < MAX_PRIMITIVES { let fb = if gs.overprint_fill && gs.blend_mode == BlendMode::Normal { BlendMode::Multiply } else { gs.blend_mode }; emit_fill(prims, &subpaths, gs.fill, op.operator == "f*", gs.alpha_fill, fb);@@ -506,7 +527,7 @@ pub(crate) fn interpret_content( } "B" | "B*" | "b" | "b*" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } if op.operator.starts_with('b') { if let Some(sp) = subpaths.last_mut() {@@ -516,7 +537,7 @@ pub(crate) fn interpret_content( if !text_only && !oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len(); if let Some(pid) = gs.fill_pattern {- paint_pattern_fill(doc, pid, &subpaths, op.operator.ends_with('*'), &pattern_base_ctm, gs.fill, prims, depth);+ paint_pattern_fill(doc, pid, &subpaths, op.operator.ends_with('*'), &pattern_base_ctm, gs.fill, gs.alpha_fill as f32, gs.blend_mode, prims, depth); } else if prims.len() < MAX_PRIMITIVES { let fb = if gs.overprint_fill && gs.blend_mode == BlendMode::Normal { BlendMode::Multiply } else { gs.blend_mode }; emit_fill(prims, &subpaths, gs.fill, op.operator.ends_with('*'), gs.alpha_fill, fb);@@ -534,19 +555,19 @@ pub(crate) fn interpret_content( } "n" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } subpaths.clear(); clip_path_ops.clear(); } "BI" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } if !text_only && !oc_stack.last().copied().unwrap_or(false) { if let Some(Object::Stream(stream)) = o.first() { if let Some(img) = extract_inline_image(doc, stream, gs.fill, &colorspaces) { let sm_start = prims.len();- if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: 1.0 }); }+ if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: gs.alpha_fill as f32, blend: gs.blend_mode }); } if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } } }@@ -554,11 +575,15 @@ pub(crate) fn interpret_content( } "Do" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } if let Some(Object::Name(name)) = o.first() { if let Some(&id) = xobjects.get(name) { if let Ok(Object::Stream(stream)) = doc.get_object(id) {+ // Skip the whole XObject if its optional-content group is OFF.+ if stream.dict.get(b"OC").ok().map(|oc| oc_object_hidden(doc, oc)).unwrap_or(false) {+ continue;+ } let subtype = stream .dict .get(b"Subtype")@@ -568,7 +593,7 @@ pub(crate) fn interpret_content( if !text_only && !oc_stack.last().copied().unwrap_or(false) { if let Some(img) = extract_image(doc, stream, gs.fill, &colorspaces) { let sm_start = prims.len();- if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: 1.0 }); }+ if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: gs.alpha_fill as f32, blend: gs.blend_mode }); } if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } } }@@ -619,9 +644,35 @@ pub(crate) fn interpret_content( group_depth+=1; } }+ // Form content shall be clipped to /BBox (transformed by+ // /Matrix), per PDF 8.10.1, so it can't bleed past its box.+ let form_ctm = mat_mul(&form_matrix, &gs.ctm);+ let mut bbox_clipped = false;+ if !text_only && !oc_stack.last().copied().unwrap_or(false) {+ if let Some(bb) = stream.dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)) {+ if prims.len() < MAX_PRIMITIVES {+ let c = [+ transform(&form_ctm, bb[0], bb[1]),+ transform(&form_ctm, bb[2], bb[1]),+ transform(&form_ctm, bb[2], bb[3]),+ transform(&form_ctm, bb[0], bb[3]),+ ];+ let pts: Vec<(f32, f32)> = c.iter().map(|&(x, y)| (x as f32, y as f32)).collect();+ let po = vec![+ PathOp::Move(c[0].0 as f32, c[0].1 as f32),+ PathOp::Line(c[1].0 as f32, c[1].1 as f32),+ PathOp::Line(c[2].0 as f32, c[2].1 as f32),+ PathOp::Line(c[3].0 as f32, c[3].1 as f32),+ PathOp::Close,+ ];+ prims.push(Prim::ClipPush { even_odd: false, pts, path_ops: Some(po) });+ bbox_clipped = true;+ }+ }+ } if let Ok(sub) = Content::decode(&stream_data_with_doc(doc, &stream)) { let mut sub_gs = gs.clone();- sub_gs.ctm = mat_mul(&form_matrix, &gs.ctm);+ sub_gs.ctm = form_ctm; // A soft mask does not re-apply to nested Do's inside the // (masked) form content. sub_gs.soft_mask = None;@@ -646,6 +697,11 @@ pub(crate) fn interpret_content( text_only, ); }+ if bbox_clipped {+ // Always balance the ClipPush, even if the prim cap+ // was hit inside the form, to keep the clip stack sane.+ prims.push(Prim::ClipPop);+ } // Bracket the whole form as the masked content, then // append the mask group (rendered at the mask's set-time CTM). if use_smask {@@ -707,6 +763,9 @@ pub(crate) fn interpret_content( "CS" => { if let Some(cs_name) = o.first() { if let Some(kind) = parse_named_cs(doc, cs_name, resources, &colorspaces) {+ // Selecting a color space resets the current color to its+ // initial value (PDF 8.6.8).+ if let Some(c) = cs_initial_color(doc, &kind, &colorspaces) { gs.stroke = c; } gs.stroke_cs = kind; } gs.stroke_pattern = None;@@ -715,6 +774,7 @@ pub(crate) fn interpret_content( "cs" => { if let Some(cs_name) = o.first() { if let Some(kind) = parse_named_cs(doc, cs_name, resources, &colorspaces) {+ if let Some(c) = cs_initial_color(doc, &kind, &colorspaces) { gs.fill = c; } gs.non_stroke_cs = kind; } gs.fill_pattern = None;@@ -771,9 +831,12 @@ pub(crate) fn interpret_content( } } [x0, y0, x1, y1]- }).filter(|b| b[2] > b[0] && b[3] > b[1]);+ }).filter(|b| b[2] > b[0] && b[3] > b[1])+ // Fall back to the already-committed clip region (the common+ // `re W n /Sh sh` case, where pending_clip is None by now).+ .or(current_clip_bbox); if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } if !text_only { if let Some(Object::Name(name)) = o.first() {@@ -782,7 +845,7 @@ pub(crate) fn interpret_content( if let Some((ctm,w,h,data)) = rasterize_shading(doc, obj, &gs.ctm, &colorspaces, 0, clip_bbox_device) { if prims.len() < MAX_PRIMITIVES && !oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len();- prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });+ prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: gs.alpha_fill as f32, blend: gs.blend_mode }); if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } } }@@ -798,42 +861,45 @@ pub(crate) fn interpret_content( } } }- "BDC" | "MP" | "DP" => {+ "BDC" => {+ // Optional content: `/OC <props> BDC`, where <props> is the OCG/OCMD+ // itself (an inline dict or a name resolved via /Properties). The+ // property list IS the group — there is no nested /OC key. let mut should_hide = false;- if let Some(prop_obj) = o.get(1) {- let prop_deref = deref(doc, prop_obj).unwrap_or(prop_obj);- let resolve_oc_ref = |obj: &Object, doc: &Document| -> Option<bool> {- match deref(doc, obj).unwrap_or(obj) {- Object::Reference(id) => Some(!is_ocg_visible(doc, *id)),- _ => None- }- };- if let Object::Dictionary(d) = prop_deref {- if let Some(oc_obj) = d.get(b"OC").ok().and_then(|ob| deref(doc,ob).or(Some(ob))) {- if let Some(h) = resolve_oc_ref(oc_obj, doc) { should_hide = h; }- }- } else if let Object::Name(n) = prop_deref {- if let Some(res_dict) = resources {- if let Some(prop_dict) = res_dict.get(b"Properties").ok().and_then(|ob| deref(doc,ob)).and_then(|ob| ob.as_dict().ok()) {- if let Some(ocg_dict_obj) = prop_dict.get(n).ok().and_then(|ob| deref(doc,ob).or(Some(ob))) {- if let Object::Dictionary(pd) = ocg_dict_obj {- if let Some(oc_obj) = pd.get(b"OC").ok().and_then(|ob| deref(doc,ob).or(Some(ob))) {- if let Some(h) = resolve_oc_ref(oc_obj, doc) { should_hide = h; }+ let tag = o.first().and_then(|t| t.as_name().ok());+ if tag == Some(b"OC") {+ if let Some(prop_obj) = o.get(1) {+ match prop_obj {+ Object::Name(n) => {+ // Resolve via the /Properties resource, keeping the+ // indirect reference so ON/OFF lists can match it.+ if let Some(res_dict) = resources {+ if let Some(prop_dict) = res_dict.get(b"Properties").ok().and_then(|ob| deref(doc, ob)).and_then(|ob| ob.as_dict().ok()) {+ if let Ok(oc_ref) = prop_dict.get(n) {+ should_hide = oc_object_hidden(doc, oc_ref); } } } }+ other => {+ should_hide = oc_object_hidden(doc, other);+ } } } } if should_hide { if oc_stack.len() < MAX_OC_STACK { oc_stack.push(true); } } else {+ // Non-OC (or visible) marked content: inherit the current hidden state. if let Some(&hidden) = oc_stack.last() { if hidden && oc_stack.len() < MAX_OC_STACK { oc_stack.push(true); } } } }+ "MP" | "DP" => {+ // Marked-content point operators: no matching EMC, so they must not+ // affect the marked-content / optional-content stack.+ } "EMC" => { if !oc_stack.is_empty() { oc_stack.pop(); } }@@ -844,7 +910,7 @@ pub(crate) fn interpret_content( } "BT" => { if let Some(pc) = pending_clip.take() {- emit_one_clip(prims, pc, &mut clip_depth, text_only, oc_stack.last().copied().unwrap_or(false));+ emit_one_clip(prims, pc, &mut clip_depth, &mut current_clip_bbox, text_only, oc_stack.last().copied().unwrap_or(false)); } text_matrix = IDENTITY; line_matrix = IDENTITY;@@ -870,7 +936,7 @@ pub(crate) fn interpret_content( } "TL" => { if let Some(v) = o.first().and_then(num) {- leading = v;+ gs.leading = v; } } "Tc" => {@@ -909,7 +975,7 @@ pub(crate) fn interpret_content( } "TD" => { if let (Some(tx), Some(ty)) = (o.first().and_then(num), o.get(1).and_then(num)) {- leading = -ty;+ gs.leading = -ty; line_matrix = mat_mul(&translate(tx, ty), &line_matrix); text_matrix = line_matrix; }@@ -921,27 +987,35 @@ pub(crate) fn interpret_content( } } "T*" => {- line_matrix = mat_mul(&translate(0.0, -leading), &line_matrix);+ line_matrix = mat_mul(&translate(0.0, -gs.leading), &line_matrix); text_matrix = line_matrix; } "Tj" => { if let Some(Object::String(bytes, _)) = o.first() { let sm_start = prims.len(); let adv = show_string(doc, prims, &gs, &fonts, &text_matrix, bytes, depth);- text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ if fonts.get(&gs.font_key).map(|f| f.wmode == 1).unwrap_or(false) {+ text_matrix = mat_mul(&translate(0.0, adv), &text_matrix);+ } else {+ text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ } // P0 fix #24/#25: soft-mask must also cover invisible-clip modes 4-6, not only 0-2 let paint_mode = matches!(gs.render_mode, 0|1|2|4|5|6); if paint_mode { if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } } } } "'" => {- line_matrix = mat_mul(&translate(0.0, -leading), &line_matrix);+ line_matrix = mat_mul(&translate(0.0, -gs.leading), &line_matrix); text_matrix = line_matrix; if let Some(Object::String(bytes, _)) = o.first() { // P0 fix #24: soft-mask must apply to ' operator let sm_start = prims.len(); let adv = show_string(doc, prims, &gs, &fonts, &text_matrix, bytes, depth);- text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ if fonts.get(&gs.font_key).map(|f| f.wmode == 1).unwrap_or(false) {+ text_matrix = mat_mul(&translate(0.0, adv), &text_matrix);+ } else {+ text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ } let paint_mode = matches!(gs.render_mode, 0|1|2|4|5|6); if paint_mode { if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } } }@@ -949,13 +1023,17 @@ pub(crate) fn interpret_content( "\"" => { if let Some(aw) = o.first().and_then(num) { gs.word_spacing = aw; } if let Some(ac) = o.get(1).and_then(num) { gs.char_spacing = ac; }- line_matrix = mat_mul(&translate(0.0, -leading), &line_matrix);+ line_matrix = mat_mul(&translate(0.0, -gs.leading), &line_matrix); text_matrix = line_matrix; if let Some(Object::String(bytes, _)) = o.get(2) { // P0 fix #24: soft-mask must apply to " operator let sm_start = prims.len(); let adv = show_string(doc, prims, &gs, &fonts, &text_matrix, bytes, depth);- text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ if fonts.get(&gs.font_key).map(|f| f.wmode == 1).unwrap_or(false) {+ text_matrix = mat_mul(&translate(0.0, adv), &text_matrix);+ } else {+ text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ } let paint_mode = matches!(gs.render_mode, 0|1|2|4|5|6); if paint_mode { if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } } }@@ -967,12 +1045,22 @@ pub(crate) fn interpret_content( match el { Object::String(bytes, _) => { let adv = show_string(doc, prims, &gs, &fonts, &text_matrix, bytes, depth);- text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ if fonts.get(&gs.font_key).map(|f| f.wmode == 1).unwrap_or(false) {+ text_matrix = mat_mul(&translate(0.0, adv), &text_matrix);+ } else {+ text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+ } } Object::Integer(_) | Object::Real(_) => { let n = num(el).unwrap_or(0.0);- let tx = -n / 1000.0 * gs.font_size * gs.h_scale;- text_matrix = mat_mul(&translate(tx, 0.0), &text_matrix);+ // TJ adjustment applies along the writing axis.+ if fonts.get(&gs.font_key).map(|f| f.wmode == 1).unwrap_or(false) {+ let ty = -n / 1000.0 * gs.font_size;+ text_matrix = mat_mul(&translate(0.0, ty), &text_matrix);+ } else {+ let tx = -n / 1000.0 * gs.font_size * gs.h_scale;+ text_matrix = mat_mul(&translate(tx, 0.0), &text_matrix);+ } } _ => {} }@@ -1213,7 +1301,7 @@ pub(crate) fn paint_pattern_stroke( if let Some(shobj) = dict.get(b"Shading").ok().and_then(|o| deref(doc, o)) { if let Some((ctm, w, h, data)) = rasterize_shading(doc, shobj, &pmat, &HashMap::new(), 0, stroke_bbox) { if prims.len() < MAX_PRIMITIVES {- prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });+ prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: gs.alpha_stroke as f32, blend: gs.blend_mode }); } } }@@ -1232,6 +1320,8 @@ pub(crate) fn paint_pattern_fill( even_odd: bool, pattern_base_ctm: &Mat, base_argb: u32,+ alpha_fill: f32,+ blend: BlendMode, prims: &mut Vec<Prim>, depth: u32, ) {@@ -1272,7 +1362,7 @@ pub(crate) fn paint_pattern_fill( let fill_bbox = polys_device_bbox(polys); if let Some((ctm, w, h, data)) = rasterize_shading(doc, shobj, &pmat, &HashMap::new(), 0, fill_bbox) { if prims.len() < MAX_PRIMITIVES {- prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });+ prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: alpha_fill, blend }); } } }@@ -1385,12 +1475,31 @@ fn paint_tiling_pattern( count += 1; let translate: Mat = [1.0, 0.0, 0.0, 1.0, i as f64 * xstep, j as f64 * ystep]; let tile_ctm = mat_mul(&translate, pmat);+ // Clip each cell to the pattern /BBox (PDF 8.7.3.1) so content that+ // overflows the cell — or a cell smaller than XStep/YStep — cannot+ // bleed into neighboring cells.+ let bc = [+ transform(&tile_ctm, bbox[0], bbox[1]),+ transform(&tile_ctm, bbox[2], bbox[1]),+ transform(&tile_ctm, bbox[2], bbox[3]),+ transform(&tile_ctm, bbox[0], bbox[3]),+ ];+ let cell_pts: Vec<(f32, f32)> = bc.iter().map(|&(x, y)| (x as f32, y as f32)).collect();+ let cell_po = vec![+ PathOp::Move(bc[0].0 as f32, bc[0].1 as f32),+ PathOp::Line(bc[1].0 as f32, bc[1].1 as f32),+ PathOp::Line(bc[2].0 as f32, bc[2].1 as f32),+ PathOp::Line(bc[3].0 as f32, bc[3].1 as f32),+ PathOp::Close,+ ];+ prims.push(Prim::ClipPush { even_odd: false, pts: cell_pts, path_ops: Some(cell_po) }); let mut tile_gs = GraphicsState { ctm: tile_ctm, ..GraphicsState::default() }; if paint_type == 2 { tile_gs.fill = base_argb; tile_gs.stroke = base_argb; } interpret_content(doc, &content.operations, res.as_ref(), tile_gs, prims, depth + 1, false);+ prims.push(Prim::ClipPop); } } }
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex b52ce2c1ef..72268c71a4 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -35,6 +35,7 @@ mod filters; mod functions; pub(crate) use functions::*; mod cff;+mod afm; mod type1; mod outlines; mod glyphlist;
pdf/src/main/rust/src/model.rs
diff --git a/pdf/src/main/rust/src/model.rs b/pdf/src/main/rust/src/model.rsindex 878d8f619c..adcc81dd69 100644--- a/pdf/src/main/rust/src/model.rs+++ b/pdf/src/main/rust/src/model.rs@@ -66,6 +66,8 @@ pub(crate) enum Prim { data: Vec<u8>, /// Per-image alpha (from SMask or explicit) * alpha_fill, for transparency group compositing. alpha: f32,+ /// Blend mode (from the graphics-state `/BM`) for compositing the image.+ blend: BlendMode, }, ClipPush { even_odd: bool,
pdf/src/main/rust/src/outlines.rs
diff --git a/pdf/src/main/rust/src/outlines.rs b/pdf/src/main/rust/src/outlines.rsindex 7ff184402e..6387a4b875 100644--- a/pdf/src/main/rust/src/outlines.rs+++ b/pdf/src/main/rust/src/outlines.rs@@ -111,7 +111,8 @@ pub(crate) enum GlyphProgram { /// TrueType / OpenType (incl. OpenType-CFF) parsed lazily via ttf-parser. Sfnt { data: Vec<u8>, upm: f64 }, /// Bare CFF (`/Type1C`, `/CIDFontType0C`) parsed via ttf-parser's CFF table.- Cff { data: Vec<u8>, upm: f64 },+ /// `cid_to_gid` is the inverted charset for CID-keyed CFF (else `None`).+ Cff { data: Vec<u8>, upm: f64, cid_to_gid: Option<HashMap<u32, u16>> }, /// Bare Type 1 font, pre-interpreted to name -> contours. Type1(Type1Font), }@@ -159,7 +160,9 @@ pub(crate) fn build_glyph_program( // which are zero for essentially all text fonts. let sx = table.matrix().sx as f64; let upm = if sx.abs() > 1e-9 { 1.0 / sx } else { 1000.0 };- return Some(GlyphProgram::Cff { data, upm });+ // CID-keyed CFF: build the charset CID->GID map so CIDs select glyphs.+ let cid_to_gid = crate::cff::cid_to_gid_map(&data);+ return Some(GlyphProgram::Cff { data, upm, cid_to_gid }); } } // Bare Type 1 (`/FontFile`): eexec-encrypted charstrings.@@ -207,9 +210,9 @@ pub(crate) fn glyph_outline(fi: &FontInfo, code: u32) -> Option<(Vec<Vec<(f64, f } Some((contours, *upm)) }- GlyphProgram::Cff { data, upm } => {+ GlyphProgram::Cff { data, upm, cid_to_gid } => { let table = ttf_parser::cff::Table::parse(data)?;- let gid = resolve_cff_gid(fi, &table, code)?;+ let gid = resolve_cff_gid(fi, &table, code, cid_to_gid.as_ref())?; let mut cb = ContourBuilder::new(); let mut sink = TtfSink(&mut cb); table.outline(gid, &mut sink).ok()?;@@ -222,15 +225,20 @@ pub(crate) fn glyph_outline(fi: &FontInfo, code: u32) -> Option<(Vec<Vec<(f64, f } } -/// Map a content-stream code to a glyph id in a bare CFF table.-fn resolve_cff_gid(fi: &FontInfo, table: &ttf_parser::cff::Table, code: u32) -> Option<ttf_parser::GlyphId> {+/// Map a content-stream code to a glyph id in a bare CFF table. `cff_cid_to_gid`+/// is the font's own charset inversion for CID-keyed CFF.+fn resolve_cff_gid(fi: &FontInfo, table: &ttf_parser::cff::Table, code: u32, cff_cid_to_gid: Option<&HashMap<u32, u16>>) -> Option<ttf_parser::GlyphId> { let n = table.number_of_glyphs(); let as_gid = |g: u32| -> Option<ttf_parser::GlyphId> { if g < n as u32 { Some(ttf_parser::GlyphId(g as u16)) } else { None } }; if fi.two_byte {- // CID-keyed CFF: approximate CID->GID via CIDToGIDMap or identity.- let gid = fi.cid_to_gid.as_ref().and_then(|m| m.get(&code).copied()).unwrap_or(code as u16);+ // Map code -> CID (via /Encoding CMap), then CID -> GID: prefer the PDF+ // /CIDToGIDMap, then the CFF's own charset, then identity.+ let cid = fi.to_cid(code);+ let gid = fi.cid_to_gid.as_ref().and_then(|m| m.get(&cid).copied())+ .or_else(|| cff_cid_to_gid.and_then(|m| m.get(&cid).copied()))+ .unwrap_or(cid as u16); return as_gid(gid as u32); } // Simple CFF: prefer glyph name, then the CFF's own 8-bit encoding.@@ -261,8 +269,10 @@ fn resolve_gid(fi: &FontInfo, face: &ttf_parser::Face, code: u32) -> Option<ttf_ }; if fi.two_byte {- // Type0/CID: CID -> GID via CIDToGIDMap, else identity.- let gid = fi.cid_to_gid.as_ref().and_then(|m| m.get(&code).copied()).unwrap_or(code as u16);+ // Type0/CID: map code -> CID (via /Encoding CMap) then CID -> GID via+ // CIDToGIDMap, else identity.+ let cid = fi.to_cid(code);+ let gid = fi.cid_to_gid.as_ref().and_then(|m| m.get(&cid).copied()).unwrap_or(cid as u16); return as_gid(gid as u32); }
pdf/src/main/rust/src/shading.rs
diff --git a/pdf/src/main/rust/src/shading.rs b/pdf/src/main/rust/src/shading.rsindex 0cf4e17b3c..8180c11f9b 100644--- a/pdf/src/main/rust/src/shading.rs+++ b/pdf/src/main/rust/src/shading.rs@@ -238,7 +238,11 @@ fn parse_type4( ) -> Vec<(Vertex, Vertex, Vertex)> { let mut br = BitReader::new(data); let mut tris = Vec::new();- let (mut va, mut vb, mut vc): (Option<Vertex>, Option<Vertex>, Option<Vertex>) = (None, None, None);+ // `last` holds the most recently completed triangle so flag 1/2 continuation+ // vertices can form strips/fans; `pending` accumulates the three flag-0+ // vertices that begin a new independent triangle (PDF 8.7.4.5.5).+ let mut last: Option<(Vertex, Vertex, Vertex)> = None;+ let mut pending: Vec<Vertex> = Vec::new(); let mut guard = 0usize; while br.remaining_bits() >= (bps_flag + 2 * bps_coord + ncomp as u32 * bps_comp) as usize { guard += 1;@@ -247,42 +251,32 @@ fn parse_type4( let v = match read_vertex(&mut br, bps_coord, bps_comp, ncomp, decode) { Some(v) => v, None => break }; match flag { 0 => {- // Flag 0 = new triangle, but PDF allows long all-zero streams: emit whenever 3 verts accumulated, then reset- if va.is_none() { va = Some(v); }- else if vb.is_none() { vb = Some(v); }- else {- // vb Some, vc will become v -> triangle- vc = Some(v);- if let (Some(a), Some(b), Some(c)) = (&va, &vb, &vc) {- tris.push((a.clone(), b.clone(), c.clone()));- }- // P0 fix #9: Reset for next independent triangle on flag 0, not retain vb/vc (would cause holes)- // Spec streams often emit all flag-0 vertices as independent triangles, not strip. So reset all.- va = None;- vb = None;- vc = None;+ // Start (or continue accumulating) a new independent triangle: its+ // three vertices all carry flag 0.+ pending.push(v);+ if pending.len() == 3 {+ let t = (pending[0].clone(), pending[1].clone(), pending[2].clone());+ tris.push(t.clone());+ last = Some(t);+ pending.clear(); } } 1 => {- // vb, vc, v- if let (Some(b), Some(c)) = (vb.clone(), vc.clone()) {- va = Some(b);- vb = Some(c);- vc = Some(v);- if let (Some(a), Some(b), Some(c)) = (&va, &vb, &vc) {- tris.push((a.clone(), b.clone(), c.clone()));- }+ // Continuation: new triangle = (vb, vc, v) of the previous triangle.+ pending.clear();+ if let Some((_a, b, c)) = last.clone() {+ let t = (b, c, v);+ tris.push(t.clone());+ last = Some(t); } } 2 => {- // va, vc, v- if let (Some(a), Some(c)) = (va.clone(), vc.clone()) {- vb = Some(c);- vc = Some(v);- va = Some(a);- if let (Some(a), Some(b), Some(c)) = (&va, &vb, &vc) {- tris.push((a.clone(), b.clone(), c.clone()));- }+ // Continuation: new triangle = (va, vc, v) of the previous triangle.+ pending.clear();+ if let Some((a, _b, c)) = last.clone() {+ let t = (a, c, v);+ tris.push(t.clone());+ last = Some(t); } } _ => break,@@ -564,19 +558,21 @@ fn parse_type6_7( } /// Select the shared edge (4 control points + 2 corner colors) from the-/// previous patch for a flag-1/2/3 continuation. Best-effort per PDF 7.10.5.7.-/// Fix high #10: shared edge must be reversed (opposite winding) to avoid twisted Coons patches+/// previous patch for a flag-1/2/3 continuation, per ISO 32000 Table 85 (Coons)+/// / Table 86 (tensor). The new patch's first edge (p1..p4, colors c1,c2) is the+/// previous patch's edge in FORWARD order so the patches join without twisting:+/// flag 1 -> prev p4,p5,p6,p7 & colors c2,c3+/// flag 2 -> prev p7,p8,p9,p10 & colors c3,c4+/// flag 3 -> prev p10,p11,p12,p1 & colors c4,c1 fn shared_edge(prev_pts: &[(f64, f64)], prev_cols: &[Vec<f64>], flag: u64) -> ([(f64, f64); 4], Vec<f64>, Vec<f64>) {- // Boundary points p1..p12 = index 0..11; corners at 0,3,6,9.- // Edges per spec Table 7.10.5.7 for flags 1,2,3 — reversed winding for c
Diff truncated.