//! The edit pipeline, in this order: pages → form values → annotations and stamps → flatten → redaction → //! password. Page indices in every edit refer to the page order *after* the page step. //! //! - Form values (lopdf): `/V` on the field, the checkbox and radio states through `/AS`; text and choice fields //! get `NeedAppearances` and pdfium then builds their appearance when the document is loaded with its form //! (which `flatten` relies on; see the forms test). //! - Annotations and stamps (lopdf): every annotation is written with its own appearance stream, so it looks the //! same in every viewer; a stamp (the visual signature) goes into the page content itself. //! - Flatten (pdfium `FPDFPage_Flatten`), then lopdf drops the form and every orphaned object. use crate::geometry::{PageFrame, ViewPoint, ViewRect, normalise_rotate}; use crate::{Engine, PageSpec, PdfError, RedactOptions, Redaction, lopdf_load, lopdf_save}; use image::DynamicImage; use lopdf::{Dictionary, Document, Object, ObjectId, Stream, StringFormat, dictionary}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Edits { #[serde(default)] pub pages: Option>, #[serde(default)] pub form: Vec, #[serde(default)] pub annotations: Vec, #[serde(default)] pub stamps: Vec, #[serde(default)] pub flatten: bool, #[serde(default)] pub redactions: Vec, #[serde(default)] pub security: Security, } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Security { /// A protected document stays protected with the password it was opened with. #[default] Keep, Remove, Set { password: String, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FieldValue { /// The fully qualified field name ("parent.child"). pub name: String, pub value: FieldInput, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "kind", content = "value", rename_all = "snake_case")] pub enum FieldInput { Text(String), Check(bool), /// A radio button's or a list's chosen option. Choice(String), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Annotation { pub page: usize, #[serde(flatten)] pub shape: Shape, /// RGB, 0..1. #[serde(default = "default_color")] pub color: [f32; 3], #[serde(default = "one")] pub opacity: f32, #[serde(default)] pub contents: Option, } fn default_color() -> [f32; 3] { [1.0, 0.85, 0.0] } fn one() -> f32 { 1.0 } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum Shape { Highlight { rects: Vec, }, Underline { rects: Vec, }, Strike { rects: Vec, }, /// A sticky note at a point; its text is `contents`. Note { at: ViewPoint, }, FreeText { rect: ViewRect, text: String, size: f32, }, Ink { strokes: Vec>, width: f32, }, Rectangle { rect: ViewRect, width: f32, }, Ellipse { rect: ViewRect, width: f32, }, Line { from: ViewPoint, to: ViewPoint, width: f32, arrow: bool, }, } /// An image burned into a page (the visual signature): PNG or JPEG bytes, placed upright in `rect`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Stamp { pub page: usize, pub rect: ViewRect, #[serde(with = "b64")] pub image: Vec, } mod b64 { use serde::{Deserialize, Deserializer, Serializer}; const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; pub fn serialize(v: &[u8], s: S) -> Result { let mut out = String::with_capacity(v.len().div_ceil(3) * 4); for c in v.chunks(3) { let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32; for i in 0..4 { if i <= c.len() { out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char); } else { out.push('='); } } } s.serialize_str(&out) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { let s = String::deserialize(d)?; let mut out = Vec::with_capacity(s.len() / 4 * 3); let (mut acc, mut bits) = (0u32, 0); for ch in s.bytes().filter(|b| !b.is_ascii_whitespace() && *b != b'=') { let v = T.iter().position(|&t| t == ch).ok_or_else(|| serde::de::Error::custom("bad base64"))? as u32; acc = acc << 6 | v; bits += 6; if bits >= 8 { bits -= 8; out.push((acc >> bits) as u8); } } Ok(out) } } #[derive(Debug, Clone)] pub struct Applied { pub bytes: Vec, pub warnings: Vec, } /// Applies `edits` to the document and returns the new file. pub fn apply(engine: &Engine, bytes: &[u8], password: Option<&str>, edits: &Edits) -> Result { let mut warnings = Vec::new(); let mut cur: Vec = match password { Some(p) => crate::unlock(bytes, p)?, None => bytes.to_vec(), }; if let Some(specs) = &edits.pages { cur = crate::reorganise(&cur, None, specs)?; } if !edits.form.is_empty() { cur = fill_form(engine, &cur, &edits.form)?; } if !edits.annotations.is_empty() || !edits.stamps.is_empty() { let mut doc = lopdf_load(&cur, None)?; let pages: Vec = doc.get_pages().values().copied().collect(); if pages.is_empty() { return Err(PdfError::Damaged("its page tree is damaged, so Pictor cannot add to its pages safely".into())); } for a in &edits.annotations { let &page = pages.get(a.page).ok_or(PdfError::NoSuchPage(a.page + 1))?; add_annotation(&mut doc, page, a)?; } for (i, s) in edits.stamps.iter().enumerate() { let &page = pages.get(s.page).ok_or(PdfError::NoSuchPage(s.page + 1))?; add_stamp(&mut doc, page, s, i)?; } cur = lopdf_save(&mut doc)?; } if edits.flatten { cur = flatten(engine, &cur)?; } if !edits.redactions.is_empty() { let r = crate::redact(engine, &cur, None, &edits.redactions, &RedactOptions::default())?; warnings.extend(r.warnings); cur = r.bytes; } match (&edits.security, password) { (Security::Set { password }, _) => cur = crate::protect(&cur, None, password, None)?, (Security::Keep, Some(p)) => { cur = crate::protect(&cur, None, p, None)?; } _ => {} } Ok(Applied { bytes: cur, warnings }) } // --------------------------------------------------------------------------------------------------------------- // Geometry from lopdf (boxes and rotation, inherited ones included). fn inherited<'a>(doc: &'a Document, page: ObjectId, key: &[u8]) -> Option<&'a Object> { let mut id = page; for _ in 0..64 { let d = doc.get_dictionary(id).ok()?; if let Ok(v) = d.get(key) { return Some(match v { Object::Reference(r) => doc.get_object(*r).ok()?, v => v, }); } id = d.get(b"Parent").ok()?.as_reference().ok()?; } None } fn number(o: &Object) -> Option { match o { Object::Integer(i) => Some(*i as f32), Object::Real(r) => Some(*r), _ => None, } } fn rect_of(o: Option<&Object>) -> Option<[f32; 4]> { let a = o?.as_array().ok()?; if a.len() != 4 { return None; } let v: Vec = a.iter().filter_map(number).collect(); (v.len() == 4).then(|| [v[0].min(v[2]), v[1].min(v[3]), v[0].max(v[2]), v[1].max(v[3])]) } pub(crate) fn lopdf_frame(doc: &Document, page: ObjectId) -> PageFrame { let media = rect_of(inherited(doc, page, b"MediaBox")).unwrap_or([0.0, 0.0, 612.0, 792.0]); let crop = rect_of(inherited(doc, page, b"CropBox")) .map(|c| [c[0].max(media[0]), c[1].max(media[1]), c[2].min(media[2]), c[3].min(media[3])]) .filter(|c| c[2] > c[0] && c[3] > c[1]) .unwrap_or(media); let rotate = inherited(doc, page, b"Rotate").and_then(|o| o.as_i64().ok()).map(normalise_rotate).unwrap_or(0); PageFrame { crop, rotate } } /// The matrix that draws a unit-less upright box (origin bottom-left, x right, y up, in points) at the view /// rectangle `r`, whatever the page's rotation: [a b c d e f]. fn upright_matrix(frame: &PageFrame, r: ViewRect) -> [f32; 6] { let o = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h }); let xr = frame.to_user(ViewPoint { x: r.x + 1.0, y: r.y + r.h }); let yu = frame.to_user(ViewPoint { x: r.x, y: r.y + r.h - 1.0 }); [xr.0 - o.0, xr.1 - o.1, yu.0 - o.0, yu.1 - o.1, o.0, o.1] } fn fmt(v: f32) -> String { let s = format!("{v:.3}"); let s = s.trim_end_matches('0').trim_end_matches('.'); if s == "-0" { "0".into() } else { s.into() } } fn arr(v: &[f32]) -> Object { Object::Array(v.iter().map(|&x| Object::Real(x)).collect()) } /// A PDF text string: PDFDocEncoding when it is plain ASCII, else UTF-16BE with a BOM. pub(crate) fn text_string(s: &str) -> Object { if s.chars().all(|c| (' '..='~').contains(&c) || c == '\n') { Object::String(s.as_bytes().to_vec(), StringFormat::Literal) } else { let mut v = vec![0xFE, 0xFF]; for u in s.encode_utf16() { v.extend_from_slice(&u.to_be_bytes()); } Object::String(v, StringFormat::Hexadecimal) } } fn add_to_annots(doc: &mut Document, page: ObjectId, annot: ObjectId) -> Result<(), PdfError> { let existing = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Annots") { Ok(Object::Array(a)) => a.clone(), Ok(Object::Reference(r)) => doc.get_object(*r).and_then(Object::as_array).cloned().unwrap_or_default(), _ => Vec::new(), }; let mut list = existing; list.push(Object::Reference(annot)); doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?.set("Annots", list); Ok(()) } // --------------------------------------------------------------------------------------------------------------- // Annotations. /// Helvetica with WinAnsi plus the Czech and other Central European letters WinAnsi lacks (mapped into the unused /// codes 1..31 through /Differences). Characters outside both become "?". struct Latin2Font { codes: Vec<(char, u8, &'static str)>, } const EXTRA_GLYPHS: &[(char, &str)] = &[ ('Á', "Aacute"), ('Č', "Ccaron"), ('č', "ccaron"), ('Ď', "Dcaron"), ('ď', "dcaron"), ('Ě', "Ecaron"), ('ě', "ecaron"), ('Ň', "Ncaron"), ('ň', "ncaron"), ('Ř', "Rcaron"), ('ř', "rcaron"), ('Ť', "Tcaron"), ('ť', "tcaron"), ('Ů', "Uring"), ('ů', "uring"), ('Ľ', "Lcaron"), ('ľ', "lcaron"), ('Ĺ', "Lacute"), ('ĺ', "lacute"), ('Ŕ', "Racute"), ('ŕ', "racute"), ('Ą', "Aogonek"), ('ą', "aogonek"), ('Ę', "Eogonek"), ('ę', "eogonek"), ('Ł', "Lslash"), ('ł', "lslash"), ('Ś', "Sacute"), ('ś', "sacute"), ('Ź', "Zacute"), ('ź', "zacute"), ('Ż', "Zdotaccent"), ('ż', "zdotaccent"), ('Ć', "Cacute"), ('ć', "cacute"), ('Ń', "Nacute"), ('ń', "nacute"), ('Ő', "Ohungarumlaut"), ('ő', "ohungarumlaut"), ('Ű', "Uhungarumlaut"), ('ű', "uhungarumlaut"), ]; fn winansi(c: char) -> Option { let u = c as u32; if (0x20..0x7F).contains(&u) || (0xA0..=0xFF).contains(&u) { return Some(u as u8); } const HIGH: &[(char, u8)] = &[ ('€', 0x80), ('‚', 0x82), ('ƒ', 0x83), ('„', 0x84), ('…', 0x85), ('†', 0x86), ('‡', 0x87), ('ˆ', 0x88), ('‰', 0x89), ('Š', 0x8A), ('‹', 0x8B), ('Œ', 0x8C), ('Ž', 0x8E), ('‘', 0x91), ('’', 0x92), ('“', 0x93), ('”', 0x94), ('•', 0x95), ('–', 0x96), ('—', 0x97), ('˜', 0x98), ('™', 0x99), ('š', 0x9A), ('›', 0x9B), ('œ', 0x9C), ('ž', 0x9E), ('Ÿ', 0x9F), ]; HIGH.iter().find(|(h, _)| *h == c).map(|(_, b)| *b) } impl Latin2Font { fn for_text(text: &str) -> Latin2Font { let mut codes = Vec::new(); let mut next = 1u8; for c in text.chars() { if winansi(c).is_some() || codes.iter().any(|(x, _, _)| *x == c) || next > 31 { continue; } if let Some((_, name)) = EXTRA_GLYPHS.iter().find(|(g, _)| *g == c) { codes.push((c, next, *name)); next += 1; } } Latin2Font { codes } } fn encode(&self, text: &str) -> Vec { text.chars() .map(|c| { winansi(c).or_else(|| self.codes.iter().find(|(x, _, _)| *x == c).map(|(_, b, _)| *b)).unwrap_or(b'?') }) .collect() } fn dict(&self) -> Dictionary { let mut enc = dictionary! {"Type" => "Encoding", "BaseEncoding" => "WinAnsiEncoding"}; if !self.codes.is_empty() { let mut diffs = Vec::new(); for (_, code, name) in &self.codes { diffs.push(Object::Integer(*code as i64)); diffs.push(Object::Name(name.as_bytes().to_vec())); } enc.set("Differences", diffs); } dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => enc} } } fn pdf_string_bytes(b: &[u8]) -> String { let mut s = String::from("("); for &c in b { match c { b'(' | b')' | b'\\' => { s.push('\\'); s.push(c as char); } 32..=126 => s.push(c as char), _ => s.push_str(&format!("\\{c:03o}")), } } s.push(')'); s } /// Approximate Helvetica advance widths (per 1000 em) for wrapping free text. fn helvetica_width(c: char) -> f32 { match c { 'i' | 'j' | 'l' | '\'' | '.' | ',' | ':' | ';' | '!' | '|' => 260.0, 'f' | 't' | 'r' | 'I' | ' ' | '(' | ')' | '[' | ']' | '-' => 320.0, 'm' | 'w' | 'M' | 'W' => 850.0, 'A'..='Z' | 'Č' | 'Ř' | 'Š' | 'Ž' | 'Ů' | 'Ď' | 'Ť' | 'Ň' | 'Ě' => 680.0, _ => 556.0, } } fn wrap(text: &str, size: f32, width: f32) -> Vec { let mut lines = Vec::new(); for para in text.split('\n') { let mut line = String::new(); let mut w = 0.0; for word in para.split(' ') { let ww: f32 = word.chars().map(helvetica_width).sum::() * size / 1000.0; let space = if line.is_empty() { 0.0 } else { 320.0 * size / 1000.0 }; if !line.is_empty() && w + space + ww > width { lines.push(std::mem::take(&mut line)); w = 0.0; } else if !line.is_empty() { line.push(' '); w += space; } line.push_str(word); w += ww; } lines.push(line); } lines } fn check_view_rect(r: &ViewRect) -> Result<(), PdfError> { if r.is_empty() || r.w > 1.0e5 || r.h > 1.0e5 { return Err(PdfError::Invalid("An annotation has no size.".into())); } Ok(()) } fn add_annotation(doc: &mut Document, page: ObjectId, a: &Annotation) -> Result<(), PdfError> { let frame = lopdf_frame(doc, page); let [r, g, b] = a.color.map(|c| c.clamp(0.0, 1.0)); let opacity = a.opacity.clamp(0.05, 1.0); let rgb = format!("{} {} {}", fmt(r), fmt(g), fmt(b)); let mut gs = dictionary! {"Type" => "ExtGState", "CA" => Object::Real(opacity), "ca" => Object::Real(opacity)}; let (subtype, rect, content, extra): (&str, [f32; 4], String, Dictionary) = match &a.shape { Shape::Highlight { rects } | Shape::Underline { rects } | Shape::Strike { rects } => { if rects.is_empty() { return Err(PdfError::Invalid("Mark some text first.".into())); } let mut quads = Vec::new(); let mut ops = String::new(); let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; for vr in rects { check_view_rect(vr)?; // QuadPoints order: top-left, top-right, bottom-left, bottom-right (as the eye sees the text). let tl = frame.to_user(ViewPoint { x: vr.x, y: vr.y }); let tr = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y }); let bl = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h }); let br = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h }); for p in [tl, tr, bl, br] { quads.push(p.0); quads.push(p.1); bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; } match &a.shape { Shape::Highlight { .. } => ops.push_str(&format!( "{} {} m {} {} l {} {} l {} {} l h f\n", fmt(tl.0), fmt(tl.1), fmt(tr.0), fmt(tr.1), fmt(br.0), fmt(br.1), fmt(bl.0), fmt(bl.1) )), _ => { let t = if matches!(a.shape, Shape::Underline { .. }) { 0.93 } else { 0.55 }; let lw = (vr.h * 0.07).max(0.8); let p0 = frame.to_user(ViewPoint { x: vr.x, y: vr.y + vr.h * t }); let p1 = frame.to_user(ViewPoint { x: vr.x + vr.w, y: vr.y + vr.h * t }); ops.push_str(&format!( "{} w {} {} m {} {} l S\n", fmt(lw), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1) )); } } } let (sub, content) = match &a.shape { Shape::Highlight { .. } => { gs.set("BM", "Multiply"); ("Highlight", format!("/GS0 gs {rgb} rg\n{ops}")) } Shape::Underline { .. } => ("Underline", format!("/GS0 gs {rgb} RG\n{ops}")), _ => ("StrikeOut", format!("/GS0 gs {rgb} RG\n{ops}")), }; (sub, bounds, content, dictionary! {"QuadPoints" => arr(&quads)}) } Shape::Note { at } => { let p = frame.to_user(*at); let rect = [p.0, p.1 - 20.0, p.0 + 20.0, p.1]; let [x, y] = [rect[0], rect[1]]; let content = format!( "/GS0 gs {rgb} rg 0.25 0.2 0.1 RG 1 w {x0} {y0} 18 18 re B\n0.25 0.2 0.1 RG 1 w {lx} {l1} m {rx} {l1} l {lx} {l2} m {rx} {l2} l {lx} {l3} m {rx2} {l3} l S\n", x0 = fmt(x + 1.0), y0 = fmt(y + 1.0), lx = fmt(x + 4.0), rx = fmt(x + 16.0), rx2 = fmt(x + 12.0), l1 = fmt(y + 14.0), l2 = fmt(y + 10.0), l3 = fmt(y + 6.0) ); ("Text", rect, content, dictionary! {"Name" => "Comment", "Open" => false}) } Shape::FreeText { rect: vr, text, size } => { check_view_rect(vr)?; let size = size.clamp(4.0, 144.0); let font = Latin2Font::for_text(text); let m = upright_matrix(&frame, *vr); let mut ops = format!( "/GS0 gs q {} {} {} {} {} {} cm BT /Helv {} Tf {rgb} rg {} TL\n", fmt(m[0]), fmt(m[1]), fmt(m[2]), fmt(m[3]), fmt(m[4]), fmt(m[5]), fmt(size), fmt(size * 1.2) ); ops.push_str(&format!("2 {} Td\n", fmt(vr.h - size))); for (i, line) in wrap(text, size, vr.w - 4.0).iter().enumerate() { if (i as f32 + 1.0) * size * 1.2 > vr.h + size { break; } if i > 0 { ops.push_str("T*\n"); } ops.push_str(&pdf_string_bytes(&font.encode(line))); ops.push_str(" Tj\n"); } ops.push_str("ET Q\n"); let user = frame.rect_to_user(*vr); let extra = dictionary! { "DA" => Object::String(format!("/Helv {} Tf {rgb} rg", fmt(size)).into_bytes(), StringFormat::Literal), "Contents" => text_string(text), "PictorFont" => font.dict(), }; ("FreeText", user, ops, extra) } Shape::Ink { strokes, width } => { let w = width.clamp(0.25, 72.0); let mut ink = Vec::new(); let mut ops = format!("/GS0 gs {rgb} RG {} w 1 J 1 j\n", fmt(w)); let mut bounds = [f32::MAX, f32::MAX, f32::MIN, f32::MIN]; for stroke in strokes.iter().filter(|s| !s.is_empty()).take(2000) { let pts: Vec<(f32, f32)> = stroke.iter().take(20_000).map(|p| frame.to_user(*p)).collect(); let mut flat = Vec::new(); for (i, p) in pts.iter().enumerate() { flat.push(p.0); flat.push(p.1); bounds = [bounds[0].min(p.0), bounds[1].min(p.1), bounds[2].max(p.0), bounds[3].max(p.1)]; ops.push_str(&format!("{} {} {}\n", fmt(p.0), fmt(p.1), if i == 0 { "m" } else { "l" })); } if pts.len() == 1 { ops.push_str(&format!("{} {} l\n", fmt(pts[0].0 + 0.01), fmt(pts[0].1))); } ops.push_str("S\n"); ink.push(arr(&flat)); } if ink.is_empty() { return Err(PdfError::Invalid("Draw something first.".into())); } let pad = w; let rect = [bounds[0] - pad, bounds[1] - pad, bounds[2] + pad, bounds[3] + pad]; ( "Ink", rect, ops, dictionary! {"InkList" => Object::Array(ink), "BS" => dictionary! {"W" => Object::Real(w)}}, ) } Shape::Rectangle { rect: vr, width } | Shape::Ellipse { rect: vr, width } => { check_view_rect(vr)?; let w = width.clamp(0.25, 72.0); let u = frame.rect_to_user(*vr); let [x0, y0, x1, y1] = [u[0] + w / 2.0, u[1] + w / 2.0, u[2] - w / 2.0, u[3] - w / 2.0]; let path = if matches!(a.shape, Shape::Rectangle { .. }) { format!("{} {} {} {} re S\n", fmt(x0), fmt(y0), fmt(x1 - x0), fmt(y1 - y0)) } else { let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0) / 2.0, (y1 - y0) / 2.0); let k = 0.552_284_8; format!( "{} {} m {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c {} {} {} {} {} {} c S\n", fmt(cx + rx), fmt(cy), fmt(cx + rx), fmt(cy + k * ry), fmt(cx + k * rx), fmt(cy + ry), fmt(cx), fmt(cy + ry), fmt(cx - k * rx), fmt(cy + ry), fmt(cx - rx), fmt(cy + k * ry), fmt(cx - rx), fmt(cy), fmt(cx - rx), fmt(cy - k * ry), fmt(cx - k * rx), fmt(cy - ry), fmt(cx), fmt(cy - ry), fmt(cx + k * rx), fmt(cy - ry), fmt(cx + rx), fmt(cy - k * ry), fmt(cx + rx), fmt(cy) ) }; let sub = if matches!(a.shape, Shape::Rectangle { .. }) { "Square" } else { "Circle" }; ( sub, u, format!("/GS0 gs {rgb} RG {} w\n{path}", fmt(w)), dictionary! {"BS" => dictionary! {"W" => Object::Real(w)}}, ) } Shape::Line { from, to, width, arrow } => { let w = width.clamp(0.25, 72.0); let p0 = frame.to_user(*from); let p1 = frame.to_user(*to); let mut ops = format!( "/GS0 gs {rgb} RG {rgb} rg {} w 1 J\n{} {} m {} {} l S\n", fmt(w), fmt(p0.0), fmt(p0.1), fmt(p1.0), fmt(p1.1) ); let head = (w * 4.0).max(8.0); if *arrow { let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1); let len = (dx * dx + dy * dy).sqrt().max(0.001); let (ux, uy) = (dx / len, dy / len); let (bx, by) = (p1.0 - ux * head, p1.1 - uy * head); let (px, py) = (-uy * head * 0.5, ux * head * 0.5); ops.push_str(&format!( "{} {} m {} {} l {} {} l h f\n", fmt(p1.0), fmt(p1.1), fmt(bx + px), fmt(by + py), fmt(bx - px), fmt(by - py) )); } let pad = head + w; let rect = [p0.0.min(p1.0) - pad, p0.1.min(p1.1) - pad, p0.0.max(p1.0) + pad, p0.1.max(p1.1) + pad]; let mut extra = dictionary! {"L" => arr(&[p0.0, p0.1, p1.0, p1.1]), "BS" => dictionary! {"W" => Object::Real(w)}}; if *arrow { extra.set("LE", vec![Object::Name(b"None".to_vec()), Object::Name(b"OpenArrow".to_vec())]); } ("Line", rect, ops, extra) } }; if !rect.iter().all(|v| v.is_finite()) { return Err(PdfError::Invalid("An annotation lies outside the page.".into())); } let mut resources = dictionary! {"ExtGState" => dictionary! {"GS0" => gs}}; let mut extra = extra; if let Some(Object::Dictionary(font)) = extra.remove(b"PictorFont") { resources.set("Font", dictionary! {"Helv" => font}); } let ap = doc.add_object(Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => arr(&rect), "Resources" => resources}, content.into_bytes(), )); let mut annot = dictionary! { "Type" => "Annot", "Subtype" => subtype, "Rect" => arr(&rect), "C" => arr(&[r, g, b]), "F" => if subtype == "Text" { 28 } else { 4 }, "P" => page, "AP" => dictionary! {"N" => ap}, "NM" => Object::String(format!("pictor-{}", doc.max_id + 1).into_bytes(), StringFormat::Literal), "T" => Object::String(b"Pictor".to_vec(), StringFormat::Literal), }; if let Some(c) = &a.contents { annot.set("Contents", text_string(c)); } for (k, v) in extra.into_iter() { annot.set(k, v); } let id = doc.add_object(annot); add_to_annots(doc, page, id) } // --------------------------------------------------------------------------------------------------------------- // Stamps (the visual signature): an image drawn into the page content. fn add_stamp(doc: &mut Document, page: ObjectId, s: &Stamp, n: usize) -> Result<(), PdfError> { check_view_rect(&s.rect)?; if s.image.len() > 32 << 20 { return Err(PdfError::TooLarge("the signature image is over 32 MB".into())); } let img: DynamicImage = image::load_from_memory(&s.image) .map_err(|_| PdfError::Invalid("The signature image could not be read.".into()))?; if (img.width() as u64) * (img.height() as u64) > 25_000_000 { return Err(PdfError::TooLarge("the signature image is too large".into())); } let rgba = img.to_rgba8(); let (w, h) = rgba.dimensions(); let rgb: Vec = rgba.pixels().flat_map(|p| [p.0[0], p.0[1], p.0[2]]).collect(); let alpha: Vec = rgba.pixels().map(|p| p.0[3]).collect(); let mut smask = Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8}, alpha, ); let _ = smask.compress(); let smask = doc.add_object(smask); let mut im = Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => w as i64, "Height" => h as i64, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "SMask" => smask}, rgb, ); let _ = im.compress(); let im = doc.add_object(im); // Fit the image into the box, keeping its aspect ratio, centred. let scale = (s.rect.w / w as f32).min(s.rect.h / h as f32); let (dw, dh) = (w as f32 * scale, h as f32 * scale); let r = ViewRect { x: s.rect.x + (s.rect.w - dw) / 2.0, y: s.rect.y + (s.rect.h - dh) / 2.0, w: dw, h: dh }; let frame = lopdf_frame(doc, page); let m = upright_matrix(&frame, r); let name = format!("PictorStamp{n}"); let ops = format!( "q {} {} {} {} {} {} cm /{name} Do Q\n", fmt(m[0] * dw), fmt(m[1] * dw), fmt(m[2] * dh), fmt(m[3] * dh), fmt(m[4]), fmt(m[5]) ); // Resources: a page-local copy (it may have been shared or inherited), with the image added. let resources = match inherited(doc, page, b"Resources") { Some(Object::Dictionary(d)) => d.clone(), _ => Dictionary::new(), }; let mut resources = resources; let mut xobjects = match resources.get(b"XObject") { Ok(Object::Dictionary(d)) => d.clone(), Ok(Object::Reference(r)) => doc.get_dictionary(*r).cloned().unwrap_or_default(), _ => Dictionary::new(), }; xobjects.set(name.as_bytes(), im); resources.set("XObject", xobjects); // Contents: the old content wrapped in q … Q so its graphics state cannot leak into the stamp. let old = match doc.get_dictionary(page).map_err(|e| PdfError::Damaged(e.to_string()))?.get(b"Contents") { Ok(Object::Array(a)) => a.clone(), Ok(Object::Reference(r)) => match doc.get_object(*r) { Ok(Object::Array(a)) => a.clone(), _ => vec![Object::Reference(*r)], }, _ => Vec::new(), }; let open = doc.add_object(Stream::new(dictionary! {}, b"q\n".to_vec())); let close = doc.add_object(Stream::new(dictionary! {}, format!("\nQ\n{ops}").into_bytes())); let mut contents = vec![Object::Reference(open)]; contents.extend(old); contents.push(Object::Reference(close)); let d = doc.get_dictionary_mut(page).map_err(|e| PdfError::Damaged(e.to_string()))?; d.set("Resources", resources); d.set("Contents", contents); Ok(()) } // --------------------------------------------------------------------------------------------------------------- // Forms. #[derive(Debug, Clone, Serialize)] pub struct FormField { pub name: String, /// "text", "checkbox", "radio", "choice", "signature" or "button". pub kind: String, pub value: String, pub options: Vec, pub page: Option, pub rect: Option, pub read_only: bool, pub multiline: bool, } struct Terminal { name: String, id: ObjectId, widgets: Vec, } fn field_tree(doc: &Document) -> Vec { let Some(fields) = doc .catalog() .ok() .and_then(|c| c.get(b"AcroForm").ok()) .and_then(|f| match f { Object::Reference(r) => doc.get_dictionary(*r).ok(), Object::Dictionary(d) => Some(d), _ => None, }) .and_then(|f| f.get(b"Fields").ok()) .and_then(|f| match f { Object::Reference(r) => doc.get_object(*r).ok().and_then(|o| o.as_array().ok()), Object::Array(a) => Some(a), _ => None, }) else { return Vec::new(); }; let mut out = Vec::new(); let mut seen = std::collections::HashSet::new(); fn walk( doc: &Document, id: ObjectId, prefix: &str, out: &mut Vec, seen: &mut std::collections::HashSet, depth: u32, ) { if depth > 32 || !seen.insert(id) || out.len() > 10_000 { return; } let Ok(d) = doc.get_dictionary(id) else { return }; let own = d.get(b"T").ok().and_then(|t| t.as_str().ok()).map(decode_text); let name = match (&own, prefix.is_empty()) { (Some(t), true) => t.clone(), (Some(t), false) => format!("{prefix}.{t}"), (None, _) => prefix.to_string(), }; let kids: Vec = match d.get(b"Kids") { Ok(Object::Array(a)) => a.iter().filter_map(|k| k.as_reference().ok()).collect(), _ => Vec::new(), }; // Kids with their own /T are fields; kids without are this field's widgets. let (fields, widgets): (Vec, Vec) = kids.iter().partition(|k| doc.get_dictionary(**k).map(|d| d.has(b"T")).unwrap_or(false)); if fields.is_empty() { let widgets = if widgets.is_empty() { vec![id] } else { widgets }; out.push(Terminal { name, id, widgets }); } else { for f in fields { walk(doc, f, &name, out, seen, depth + 1); } } } for f in fields.iter().filter_map(|f| f.as_reference().ok()) { walk(doc, f, "", &mut out, &mut seen, 0); } out } pub(crate) fn decode_text(b: &[u8]) -> String { if b.starts_with(&[0xFE, 0xFF]) { let u: Vec = b[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); String::from_utf16_lossy(&u) } else { b.iter().map(|&c| c as char).collect() } } fn field_attr<'a>(doc: &'a Document, id: ObjectId, key: &[u8]) -> Option<&'a Object> { inherited(doc, id, key) } fn on_state(doc: &Document, widget: ObjectId) -> Option> { let ap = doc.get_dictionary(widget).ok()?.get(b"AP").ok()?; let ap = match ap { Object::Reference(r) => doc.get_dictionary(*r).ok()?, Object::Dictionary(d) => d, _ => return None, }; let n = match ap.get(b"N").ok()? { Object::Reference(r) => doc.get_dictionary(*r).ok()?, Object::Dictionary(d) => d, _ => return None, }; n.iter().map(|(k, _)| k.clone()).find(|k| k != b"Off") } /// The fields of the document's form, for the UI's form panel. pub fn form_fields(engine: &Engine, bytes: &[u8], password: Option<&str>) -> Result, PdfError> { let doc = lopdf_load(bytes, password)?; let pages: Vec = doc.get_pages().values().copied().collect(); let mut out = Vec::new(); for t in field_tree(&doc) { let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b""); let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); let kind = match ft { b"Tx" => "text", b"Btn" if flags & (1 << 16) != 0 => "button", b"Btn" if flags & (1 << 15) != 0 => "radio", b"Btn" => "checkbox", b"Ch" => "choice", b"Sig" => "signature", _ => continue, }; let value = match field_attr(&doc, t.id, b"V") { Some(Object::String(s, _)) => decode_text(s), Some(Object::Name(n)) => String::from_utf8_lossy(n).into_owned(), _ => String::new(), }; let mut options = Vec::new(); if kind == "choice" && let Some(Object::Array(opts)) = field_attr(&doc, t.id, b"Opt") { for o in opts.iter().take(1000) { let o = match o { Object::Array(pair) => pair.get(1).cloned().unwrap_or(Object::Null), o => o.clone(), }; if let Object::String(s, _) = o { options.push(decode_text(&s)); } } } if kind == "radio" { for w in &t.widgets { if let Some(s) = on_state(&doc, *w) { options.push(String::from_utf8_lossy(&s).into_owned()); } } } let first = t.widgets.first().copied(); let page = first.and_then(|w| { let p = doc.get_dictionary(w).ok()?.get(b"P").ok()?.as_reference().ok()?; pages.iter().position(|x| *x == p) }); let page = page.or_else(|| { first.and_then(|w| { pages.iter().position(|p| match doc.get_dictionary(*p).ok().and_then(|d| d.get(b"Annots").ok()) { Some(Object::Array(a)) => a.iter().any(|x| x.as_reference().ok() == Some(w)), _ => false, }) }) }); let rect = match (page, first) { (Some(p), Some(w)) => rect_of(doc.get_dictionary(w).ok().and_then(|d| d.get(b"Rect").ok())).map(|r| { let f = lopdf_frame(&doc, pages[p]); let pr = pdfium_render::prelude::PdfRect::new_from_values(r[1], r[0], r[3], r[2]); f.user_to_view(pr) }), _ => None, }; out.push(FormField { name: t.name, kind: kind.into(), value, options, page, rect, read_only: flags & 1 != 0, multiline: kind == "text" && flags & (1 << 12) != 0, }); } let _ = engine; Ok(out) } fn fill_form(engine: &Engine, bytes: &[u8], values: &[FieldValue]) -> Result, PdfError> { let mut doc = lopdf_load(bytes, None)?; let tree = field_tree(&doc); let mut needs_appearances = false; for v in values { let t = tree .iter() .find(|t| t.name == v.name) .ok_or_else(|| PdfError::Invalid(format!("This PDF has no field named \"{}\".", v.name)))?; let ft = field_attr(&doc, t.id, b"FT").and_then(|o| o.as_name().ok()).unwrap_or(b"").to_vec(); let flags = field_attr(&doc, t.id, b"Ff").and_then(|o| o.as_i64().ok()).unwrap_or(0); if flags & 1 != 0 { return Err(PdfError::Invalid(format!("The field \"{}\" is read-only.", v.name))); } let set = |doc: &mut Document, id: ObjectId, key: &str, val: Object| { if let Ok(d) = doc.get_dictionary_mut(id) { d.set(key, val); } }; match (&ft[..], &v.value) { (b"Tx", FieldInput::Text(s)) | (b"Ch", FieldInput::Choice(s)) | (b"Ch", FieldInput::Text(s)) => { set(&mut doc, t.id, "V", text_string(s)); for w in &t.widgets { if let Ok(d) = doc.get_dictionary_mut(*w) { d.remove(b"AP"); } } needs_appearances = true; } (b"Btn", FieldInput::Check(on)) if flags & (3 << 15) == 0 => { for w in &t.widgets { let state = if *on { on_state(&doc, *w).unwrap_or_else(|| b"Yes".to_vec()) } else { b"Off".to_vec() }; set(&mut doc, *w, "AS", Object::Name(state.clone())); set(&mut doc, t.id, "V", Object::Name(state)); } } (b"Btn", FieldInput::Choice(choice)) if flags & (1 << 15) != 0 => { let mut found = false; for w in &t.widgets { let on = on_state(&doc, *w); let this = on.as_deref() == Some(choice.as_bytes()); found |= this; set( &mut doc, *w, "AS", Object::Name(if this { choice.as_bytes().to_vec() } else { b"Off".to_vec() }), ); } if !found { return Err(PdfError::Invalid(format!("\"{choice}\" is not an option of \"{}\".", v.name))); } set(&mut doc, t.id, "V", Object::Name(choice.as_bytes().to_vec())); } _ => return Err(PdfError::Invalid(format!("That value does not fit the field \"{}\".", v.name))), } } if needs_appearances { let catalog_id = doc.trailer.get(b"Root").and_then(Object::as_reference).map_err(|e| PdfError::Damaged(e.to_string()))?; let form = doc.get_dictionary(catalog_id).ok().and_then(|c| c.get(b"AcroForm").ok()).cloned(); match form { Some(Object::Reference(r)) => { if let Ok(d) = doc.get_dictionary_mut(r) { d.set("NeedAppearances", true); } } Some(Object::Dictionary(mut d)) => { d.set("NeedAppearances", true); if let Ok(c) = doc.get_dictionary_mut(catalog_id) { c.set("AcroForm", d); } } _ => {} } } let plain = lopdf_save(&mut doc)?; if !needs_appearances { return Ok(plain); } // Let pdfium build the missing appearances (it does so when it loads a form with NeedAppearances), so viewers // that ignore the flag show the values too. regenerate_appearances(engine, &plain) } fn regenerate_appearances(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { let doc = engine.open(bytes, None)?; for page in doc.pages().iter() { // Rendering with the form draws every widget, which makes pdfium create its appearance stream. let cfg = pdfium_render::prelude::PdfRenderConfig::new().set_target_width(64).render_form_data(true); let _ = page.render_with_config(&cfg); } crate::engine::pdfium_save(&doc) } /// Flattens annotations and form fields into the page content, then drops the form and every orphaned object. pub fn flatten(engine: &Engine, bytes: &[u8]) -> Result, PdfError> { let mut doc = engine.open(bytes, None)?; let n = doc.pages().len(); for i in 0..n { let mut page = doc.pages_mut().get(i).map_err(PdfError::from_pdfium)?; page.flatten().map_err(PdfError::from_pdfium)?; } let flat = crate::engine::pdfium_save(&doc)?; drop(doc); let mut doc = lopdf_load(&flat, None)?; if let Ok(catalog_id) = doc.trailer.get(b"Root").and_then(Object::as_reference) && let Ok(c) = doc.get_dictionary_mut(catalog_id) { c.remove(b"AcroForm"); } doc.prune_objects(); lopdf_save(&mut doc) }