pdf: improve shape and color handling #
- Commit
5f9d566060ee2ee9b7df7c62b90bd7d701730306- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-25 03:23 UTC (4 months ago)
- Parents
258d619
Diff
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 7f9dec1af6..eb71f6c569 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -83,16 +83,20 @@ pub(crate) fn parse_cs_kind(doc: &Document, cs_obj: Option<&Object>, cs_resource let obj = cs_obj?; // If Name, check if it's a resource reference if let Object::Name(name) = obj {- // Check resources+ // A named colorspace from the resource dictionary. The resolved object is+ // normally an Array (e.g. [/ICCBased ...], [/Separation ...]); it may also+ // be an indirect reference to one. (The previous `get_dictionary` check+ // rejected arrays outright, silently dropping the colorspace to gray.) if let Some(&id) = cs_resources.get(name) {- if let Ok(d) = doc.get_dictionary(id) {- // Should be an array?- // For simplicity, try to parse from dict that may contain colorspace array? Actually colorspace resource can be array directly stored as indirect object- // So we need to get object id's object- if let Ok(Object::Array(arr)) = doc.get_object(id) {- return parse_cs_array(doc, &arr, cs_resources);+ if let Ok(resolved) = doc.get_object(id) {+ match resolved {+ Object::Array(arr) => return parse_cs_array(doc, arr, cs_resources),+ // Guard against a name that resolves to itself.+ Object::Name(n2) if n2 != name => {+ return parse_cs_kind(doc, Some(resolved), cs_resources);+ }+ _ => {} }- // fallback: try array from dict? Not } } // Builtin names@@ -114,6 +118,39 @@ pub(crate) fn parse_cs_kind(doc: &Document, cs_obj: Option<&Object>, cs_resource None } +/// Resolve a colorspace operand for the `cs`/`CS` operators. Named entries in+/// the page `/Resources /ColorSpace` dict are honored whether they are stored as+/// a direct array (e.g. `/Cs0 [/ICCBased 5 0 R]`) or an indirect reference — the+/// pre-built id map only captures the reference form, so a direct array would+/// otherwise fall through to the DeviceGray default and render colors as gray.+pub(crate) fn parse_named_cs(+ doc: &Document,+ cs_obj: &Object,+ resources: Option<&lopdf::Dictionary>,+ cs_resources: &HashMap<Vec<u8>, ObjectId>,+) -> Option<CsKind> {+ if let Object::Name(name) = cs_obj {+ // Device builtins take precedence and never live in the resource dict.+ match name.as_slice() {+ b"DeviceRGB" | b"RGB" => return Some(CsKind::DeviceRGB),+ b"DeviceCMYK" | b"CMYK" => return Some(CsKind::DeviceCMYK),+ b"DeviceGray" | b"Gray" | b"G" => return Some(CsKind::DeviceGray),+ b"Pattern" => return Some(CsKind::Pattern),+ _ => {}+ }+ if let Some(res) = resources {+ if let Some(Object::Dictionary(csd)) = res.get(b"ColorSpace").ok().and_then(|o| deref(doc, o)) {+ if let Ok(entry) = csd.get(name) {+ if let Some(k) = parse_cs_kind(doc, Some(entry), cs_resources) {+ return Some(k);+ }+ }+ }+ }+ }+ parse_cs_kind(doc, Some(cs_obj), cs_resources)+}+ pub(crate) fn parse_cs_array(doc: &Document, arr: &[Object], cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<CsKind> { // arr head is name let head = arr.first().and_then(|o| o.as_name().ok()).unwrap_or(b"");@@ -534,4 +571,47 @@ mod tests { let r = (half >> 16) & 0xFF; assert!(r > 100 && r < 160, "half tint red channel ~128, got {r}"); }++ // A named ICCBased colorspace stored as an INDIRECT array in the resource id+ // map must resolve to RGB — not collapse to DeviceGray (the old+ // get_dictionary check rejected arrays, turning colors gray).+ #[test]+ fn named_iccbased_array_resolves_to_rgb_not_gray() {+ use lopdf::{dictionary, Object, Stream};+ let mut doc = Document::with_version("1.7");+ let icc_id = doc.add_object(Stream::new(dictionary! { "N" => 3 }, vec![0u8; 4]));+ let cs_id = doc.add_object(Object::Array(vec![+ Object::Name(b"ICCBased".to_vec()),+ Object::Reference(icc_id),+ ]));+ let mut res = HashMap::new();+ res.insert(b"CS0".to_vec(), cs_id);+ let kind = parse_cs_kind(&doc, Some(&Object::Name(b"CS0".to_vec())), &res)+ .expect("named ICCBased should resolve");+ let argb = eval_cs_to_rgb(&doc, &kind, &[0.0, 1.0, 0.0], &res).unwrap();+ assert_eq!(argb & 0x00FF_FFFF, 0x0000_FF00, "ICCBased/RGB green must stay green");+ }++ // A named colorspace stored as a DIRECT array (not an indirect reference) is+ // not in the pre-built id map, so it must be resolved via the raw resource+ // ColorSpace dict by parse_named_cs.+ #[test]+ fn direct_array_colorspace_resolves_via_resources() {+ use lopdf::{dictionary, Object, Stream};+ let mut doc = Document::with_version("1.7");+ let icc_id = doc.add_object(Stream::new(dictionary! { "N" => 3 }, vec![0u8; 4]));+ let resources = dictionary! {+ "ColorSpace" => dictionary! {+ "CS0" => Object::Array(vec![+ Object::Name(b"ICCBased".to_vec()),+ Object::Reference(icc_id),+ ])+ }+ };+ let empty = HashMap::new();+ let kind = parse_named_cs(&doc, &Object::Name(b"CS0".to_vec()), Some(&resources), &empty)+ .expect("direct-array colorspace should resolve");+ let argb = eval_cs_to_rgb(&doc, &kind, &[1.0, 0.0, 0.0], &empty).unwrap();+ assert_eq!(argb & 0x00FF_FFFF, 0x00FF_0000, "direct-array ICCBased red must stay red");+ } }
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 be251e5c75..8ac261bd01 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -61,15 +61,16 @@ pub(crate) fn emit_stroke(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], g pub(crate) fn emit_fill(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], argb: u32, even_odd: bool, alpha_fill: f64, blend: BlendMode) { let argb = apply_alpha_to_argb(argb, alpha_fill);- for sp in subpaths {- if sp.len() >= 3 {- prims.push(Prim::Fill {- argb,- even_odd,- pts: sp.iter().map(|&(x, y)| (x as f32, y as f32)).collect(),- blend,- });- }+ // All subpaths of the path form ONE fill region so interior contours (glyph+ // counters / holes) are cut out by the winding rule, instead of being filled+ // in as separate solid polygons.+ let contours: Vec<Vec<(f32, f32)>> = subpaths+ .iter()+ .filter(|sp| sp.len() >= 3)+ .map(|sp| sp.iter().map(|&(x, y)| (x as f32, y as f32)).collect())+ .collect();+ if !contours.is_empty() {+ prims.push(Prim::Fill { argb, even_odd, contours, blend }); } }
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 00f0a68474..ea206fa33c 100644--- a/pdf/src/main/rust/src/interpret.rs+++ b/pdf/src/main/rust/src/interpret.rs@@ -694,7 +694,7 @@ pub(crate) fn interpret_content( } "CS" => { if let Some(cs_name) = o.first() {- if let Some(kind) = parse_cs_kind(doc, Some(cs_name), &colorspaces) {+ if let Some(kind) = parse_named_cs(doc, cs_name, resources, &colorspaces) { gs.stroke_cs = kind; } gs.stroke_pattern = None;@@ -702,7 +702,7 @@ pub(crate) fn interpret_content( } "cs" => { if let Some(cs_name) = o.first() {- if let Some(kind) = parse_cs_kind(doc, Some(cs_name), &colorspaces) {+ if let Some(kind) = parse_named_cs(doc, cs_name, resources, &colorspaces) { gs.non_stroke_cs = kind; } gs.fill_pattern = None;
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 2ebdf77324..8fa2f29a7f 100644--- a/pdf/src/main/rust/src/model.rs+++ b/pdf/src/main/rust/src/model.rs@@ -22,7 +22,10 @@ pub(crate) enum Prim { Fill { argb: u32, even_odd: bool,- pts: Vec<(f32, f32)>,+ /// One or more closed contours making up a single fill region. Interior+ /// contours (glyph counters / holes) are cut out by the even-odd or+ /// nonzero winding rule when all contours are filled as one path.+ contours: Vec<Vec<(f32, f32)>>, /// Blend mode (from the graphics-state `/BM`). Serialized in v5. blend: BlendMode, },
pdf/src/main/rust/src/tests.rs
diff --git a/pdf/src/main/rust/src/tests.rs b/pdf/src/main/rust/src/tests.rsindex 6914330762..d5de7fdff1 100644--- a/pdf/src/main/rust/src/tests.rs+++ b/pdf/src/main/rust/src/tests.rs@@ -64,8 +64,10 @@ use crate::*; .filter(|p| matches!(p, Prim::Fill { .. })) .collect(); assert_eq!(fills.len(), 1, "expected one filled rectangle");- if let Prim::Fill { argb, pts, .. } = fills[0] {+ if let Prim::Fill { argb, contours, .. } = fills[0] { assert_eq!(*argb, 0xFFFF0000, "fill should be red");+ assert_eq!(contours.len(), 1, "rectangle is a single contour");+ let pts = &contours[0]; assert!(pts.len() >= 4, "rectangle should have >=4 points"); assert_eq!(pts[0], (100.0, 100.0)); }@@ -88,6 +90,24 @@ use crate::*; } } + /// A path with an inner subpath (a hole, e.g. a glyph counter) must emit a+ /// SINGLE fill primitive carrying both contours, so the winding rule cuts the+ /// hole out instead of filling it in as a second solid polygon.+ #[test]+ fn fill_with_hole_is_single_multicontour_prim() {+ let mut prims: Vec<Prim> = Vec::new();+ let outer = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];+ let hole = vec![(3.0, 3.0), (7.0, 3.0), (7.0, 7.0), (3.0, 7.0)];+ emit_fill(&mut prims, &[outer, hole], 0xFF000000, false, 1.0, BlendMode::Normal);+ assert_eq!(prims.len(), 1, "a path with a hole is one fill primitive");+ match &prims[0] {+ Prim::Fill { contours, .. } => {+ assert_eq!(contours.len(), 2, "outer + hole contours preserved");+ }+ _ => panic!("expected a Fill primitive"),+ }+ }+ /// Two consecutive `Tj` runs on one line must not stack at the same x: the /// second run is offset by the first run's glyph-width advance. #[test]
pdf/src/main/rust/src/wire.rs
diff --git a/pdf/src/main/rust/src/wire.rs b/pdf/src/main/rust/src/wire.rsindex 30a301cf3c..0d21fab11d 100644--- a/pdf/src/main/rust/src/wire.rs+++ b/pdf/src/main/rust/src/wire.rs@@ -1,7 +1,7 @@ use crate::*; const WIRE_MAGIC: u32 = 0x50444657; // 'PDFW'- const WIRE_VERSION: u32 = 5;+ const WIRE_VERSION: u32 = 6; #[allow(dead_code)] const WIRE_VERSION_V2: u32 = 2; const TAG_TEXT: u8 = 1;@@ -22,13 +22,13 @@ use crate::*; const PATHOP_CUBIC: u8 = 2; const PATHOP_CLOSE: u8 = 3; - /// Serialize a page into a compact little-endian buffer v5:+ /// Serialize a page into a compact little-endian buffer v6: /// /// ```text- /// header: u32 MAGIC=0x50444657, u32 VERSION=5, f32 pageWidth, f32 pageHeight, u32 primitiveCount+ /// header: u32 MAGIC=0x50444657, u32 VERSION=6, f32 pageWidth, f32 pageHeight, u32 primitiveCount /// per primitive: u8 tag, then payload /// 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5)- /// 2 Fill: u32 argb, u8 evenOdd, u16 nPts, [f32 x, f32 y]..., u8 blend (v5)+ /// 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, f32 y]..., u8 blend (v5) /// 4 Image: 6×f32 ctm, u32 w, u32 h, u8 format, u32 len, [bytes] (format 0=RGBA8888, 1=JPEG) /// 5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]..., u16 nPathOps, [u8 kind, coords]... (path-ops section is v4)@@ -73,11 +73,15 @@ use crate::*; buf.push(*render_mode); // v4 buf.push(*blend as u8); // v5 }- Prim::Fill { argb, even_odd, pts, blend } => {+ Prim::Fill { argb, even_odd, contours, blend } => { buf.push(TAG_FILL); buf.extend_from_slice(&argb.to_le_bytes()); buf.push(if *even_odd { 1 } else { 0 });- write_points(&mut buf, pts);+ let nc = contours.len().min(u16::MAX as usize);+ buf.extend_from_slice(&(nc as u16).to_le_bytes()); // v6+ for c in &contours[..nc] {+ write_points(&mut buf, c);+ } buf.push(*blend as u8); // v5 } Prim::Stroke { argb, width, dash, dash_phase, cap, join, miter, pts, blend } => {@@ -243,7 +247,10 @@ use crate::*; Prim::Fill { argb: 0xFFAABBCC, even_odd: true,- pts: vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)],+ contours: vec![+ vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)],+ vec![(0.25, 0.25), (0.5, 0.25), (0.5, 0.5)],+ ], blend: BlendMode::Screen, }, Prim::Stroke {@@ -299,7 +306,10 @@ use crate::*; assert_eq!(r.u8(), TAG_FILL); assert_eq!(r.u32(), 0xFFAABBCC); assert_eq!(r.u8(), 1); // even-odd- assert_eq!(r.u16(), 3);+ assert_eq!(r.u16(), 2); // nContours (v6)+ assert_eq!(r.u16(), 3); // contour 0 nPts+ r.pos += 3 * 8;+ assert_eq!(r.u16(), 3); // contour 1 nPts r.pos += 3 * 8; assert_eq!(r.u8(), BlendMode::Screen as u8); // blend (v5)