diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index ee43f81..33217d5 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -17,3 +17,4 @@ getrandom.workspace = true [dev-dependencies] flate2.workspace = true +serde_json.workspace = true diff --git a/crates/pdf/src/edit.rs b/crates/pdf/src/edit.rs index 6354e9c..a40f88f 100644 --- a/crates/pdf/src/edit.rs +++ b/crates/pdf/src/edit.rs @@ -1 +1,969 @@ -//! The edit pipeline (form fill, annotations, stamps, flatten, security). +//! 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, PdfError, PageSpec, Redaction, RedactOptions, 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(); + 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..].chunks_exact(2).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) +} diff --git a/crates/pdf/tests/edit.rs b/crates/pdf/tests/edit.rs new file mode 100644 index 0000000..f263b47 --- /dev/null +++ b/crates/pdf/tests/edit.rs @@ -0,0 +1,274 @@ +//! The edit pipeline: form values, annotations, the signature stamp, flatten, and the password kept. +mod common; +use common::*; +use lopdf::{Document, Object, Stream, StringFormat, dictionary}; +use pictor_pdf::{Annotation, Edits, FieldInput, FieldValue, Security, Shape, Stamp, ViewPoint, ViewRect}; + +fn s(t: &str) -> Object { + Object::String(t.as_bytes().to_vec(), StringFormat::Literal) +} + +/// One A4 page with a text field, a checkbox whose on-state is "Ano", a radio pair (A, B) and a combo box. +fn form_pdf() -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let page_id = doc.new_object_id(); + let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"}); + let zadb = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "ZapfDingbats"}); + let ap = |doc: &mut Document, body: &[u8]| { + doc.add_object(Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 20.into(), 20.into()], + "Resources" => dictionary! {"Font" => dictionary! {"ZaDb" => zadb}}}, + body.to_vec(), + )) + }; + let on = ap(&mut doc, b"q 0 g BT /ZaDb 14 Tf 3 4 Td (4) Tj ET Q"); + let off = ap(&mut doc, b""); + let name = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Tx", "T" => s("name"), "DA" => s("/Helv 12 Tf 0 g"), + "Rect" => vec![100.into(), 700.into(), 400.into(), 724.into()], "F" => 4, "P" => page_id, + }); + let agree = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Btn", "T" => s("agree"), "V" => "Off", "AS" => "Off", + "Rect" => vec![100.into(), 650.into(), 120.into(), 670.into()], "F" => 4, "P" => page_id, + "AP" => dictionary! {"N" => dictionary! {"Ano" => on, "Off" => off}}, + }); + let radio_id = doc.new_object_id(); + let mut kids = Vec::new(); + for (i, st) in ["A", "B"].iter().enumerate() { + let on = ap(&mut doc, b"q 0 g BT /ZaDb 14 Tf 3 4 Td (l) Tj ET Q"); + let off = ap(&mut doc, b""); + let x = 100 + i as i64 * 40; + kids.push(Object::Reference(doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "Parent" => radio_id, "AS" => "Off", "F" => 4, "P" => page_id, + "Rect" => vec![x.into(), 600.into(), (x + 20).into(), 620.into()], + "AP" => dictionary! {"N" => lopdf::Dictionary::from_iter([(st.as_bytes().to_vec(), Object::Reference(on)), (b"Off".to_vec(), Object::Reference(off))])}, + }))); + } + doc.objects.insert( + radio_id, + Object::Dictionary(dictionary! {"FT" => "Btn", "Ff" => 49152, "T" => s("size"), "V" => "Off", "Kids" => kids.clone()}), + ); + let city = doc.add_object(dictionary! { + "Type" => "Annot", "Subtype" => "Widget", "FT" => "Ch", "Ff" => 131072, "T" => s("city"), + "Opt" => vec![s("Brno"), s("Praha")], "DA" => s("/Helv 12 Tf 0 g"), + "Rect" => vec![100.into(), 540.into(), 300.into(), 564.into()], "F" => 4, "P" => page_id, + }); + let content = doc.add_object(Stream::new(dictionary! {}, b"BT /F1 12 Tf 72 780 Td (Form) Tj ET".to_vec())); + let mut annots = vec![name.into(), agree.into(), city.into()]; + annots.extend(kids); + doc.objects.insert(page_id, Object::Dictionary(dictionary! { + "Type" => "Page", "Parent" => pages_id, "Contents" => content, "Annots" => annots, + "Resources" => dictionary! {"Font" => dictionary! {"F1" => helv}}, + })); + doc.objects.insert(pages_id, Object::Dictionary(dictionary! { + "Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], + })); + let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id, + "AcroForm" => dictionary! {"Fields" => vec![name.into(), agree.into(), radio_id.into(), city.into()], + "DA" => s("/Helv 12 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv, "ZaDb" => zadb}}}}); + doc.trailer.set("Root", catalog); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +fn fill() -> Edits { + Edits { + form: vec![ + FieldValue { name: "name".into(), value: FieldInput::Text("Jan Novák Řehoř".into()) }, + FieldValue { name: "agree".into(), value: FieldInput::Check(true) }, + FieldValue { name: "size".into(), value: FieldInput::Choice("B".into()) }, + FieldValue { name: "city".into(), value: FieldInput::Choice("Praha".into()) }, + ], + ..Default::default() + } +} + +fn dark_pixels(img: &image::RgbImage, r: ViewRect, scale: f32) -> usize { + let (x0, y0) = ((r.x * scale) as u32, (r.y * scale) as u32); + let (x1, y1) = (((r.x + r.w) * scale) as u32, ((r.y + r.h) * scale) as u32); + (y0..y1.min(img.height())).flat_map(|y| (x0..x1.min(img.width())).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(x, y).0.iter().map(|&c| c as u32).sum::() < 300).count() +} + +#[test] +fn form_fields_are_listed_and_filled() { + let input = form_pdf(); + let fields = pictor_pdf::form_fields(engine(), &input, None).unwrap(); + let names: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["name", "agree", "size", "city"]); + assert_eq!(fields[2].options, ["A", "B"]); + assert_eq!(fields[3].options, ["Brno", "Praha"]); + assert_eq!(fields[0].page, Some(0)); + let out = pictor_pdf::apply(engine(), &input, None, &fill()).unwrap().bytes; + let after = pictor_pdf::form_fields(engine(), &out, None).unwrap(); + let value = |n: &str| after.iter().find(|f| f.name == n).unwrap().value.clone(); + assert_eq!(value("name"), "Jan Novák Řehoř"); + assert_eq!(value("agree"), "Ano", "the checkbox's own on-state must be used, not \"Yes\""); + assert_eq!(value("size"), "B"); + assert_eq!(value("city"), "Praha"); + // The text value is drawn (pdfium built its appearance). + let img = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8(); + assert!(dark_pixels(&img, after[0].rect.unwrap(), 1.0) > 20, "the filled text is not visible"); +} + +#[test] +fn a_filled_form_flattens_into_page_text() { + let mut edits = fill(); + edits.flatten = true; + let out = pictor_pdf::apply(engine(), &form_pdf(), None, &edits).unwrap().bytes; + let text = pictor_pdf::extract_text(engine(), &out, None).unwrap().concat(); + assert!(text.contains("Jan Novák Řehoř"), "flattened text field value missing: {text:?}"); + assert!(text.contains("Praha"), "flattened choice value missing: {text:?}"); + let doc = Document::load_mem(&out).unwrap(); + assert!(doc.catalog().unwrap().get(b"AcroForm").is_err(), "the form survived flattening"); + let p = page_ids(&doc)[0]; + assert!(doc.get_dictionary(p).unwrap().get(b"Annots").map(|a| a.as_array().map(|a| a.is_empty()).unwrap_or(false)).unwrap_or(true)); +} + +#[test] +fn bad_form_values_are_refused() { + let input = form_pdf(); + for (name, value) in [ + ("nope", FieldInput::Text("x".into())), + ("size", FieldInput::Choice("C".into())), + ("agree", FieldInput::Text("x".into())), + ] { + let edits = Edits { form: vec![FieldValue { name: name.into(), value }], ..Default::default() }; + assert!(pictor_pdf::apply(engine(), &input, None, &edits).is_err(), "{name} accepted a bad value"); + } +} + +fn every_annotation() -> Vec { + let r = |x, y, w, h| ViewRect { x, y, w, h }; + let a = |shape| Annotation { page: 0, shape, color: [1.0, 0.0, 0.0], opacity: 1.0, contents: None }; + vec![ + Annotation { color: [1.0, 0.9, 0.0], opacity: 0.5, ..a(Shape::Highlight { rects: vec![r(60.0, 100.0, 200.0, 30.0)] }) }, + a(Shape::Underline { rects: vec![r(60.0, 150.0, 200.0, 20.0)] }), + a(Shape::Strike { rects: vec![r(60.0, 190.0, 200.0, 20.0)] }), + Annotation { contents: Some("Zkontrolovat čísla".into()), ..a(Shape::Note { at: ViewPoint { x: 400.0, y: 100.0 } }) }, + a(Shape::FreeText { rect: r(60.0, 240.0, 400.0, 60.0), text: "Příliš žluťoučký kůň".into(), size: 18.0 }), + a(Shape::Ink { strokes: vec![vec![ViewPoint { x: 60.0, y: 330.0 }, ViewPoint { x: 160.0, y: 380.0 }, ViewPoint { x: 260.0, y: 330.0 }]], width: 3.0 }), + a(Shape::Rectangle { rect: r(300.0, 330.0, 100.0, 50.0), width: 2.0 }), + a(Shape::Ellipse { rect: r(420.0, 330.0, 100.0, 50.0), width: 2.0 }), + a(Shape::Line { from: ViewPoint { x: 60.0, y: 420.0 }, to: ViewPoint { x: 300.0, y: 460.0 }, width: 3.0, arrow: true }), + ] +} + +#[test] +fn every_annotation_kind_is_written_with_an_appearance_and_shows() { + let input = numbered_pdf(1, "Annotated"); + let before = pictor_pdf::render_page(engine(), &input, None, 0, 595).unwrap().to_rgb8(); + let edits = Edits { annotations: every_annotation(), ..Default::default() }; + let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes; + let doc = Document::load_mem(&out).unwrap(); + let p = page_ids(&doc)[0]; + let annots = doc.get_dictionary(p).unwrap().get(b"Annots").unwrap().as_array().unwrap().clone(); + let subtypes: Vec = annots + .iter() + .map(|a| { + let d = doc.get_dictionary(a.as_reference().unwrap()).unwrap(); + assert!(d.get(b"AP").is_ok(), "an annotation without an appearance"); + String::from_utf8(d.get(b"Subtype").unwrap().as_name().unwrap().to_vec()).unwrap() + }) + .collect(); + assert_eq!(subtypes, ["Highlight", "Underline", "StrikeOut", "Text", "FreeText", "Ink", "Square", "Circle", "Line"]); + let after = pictor_pdf::render_page(engine(), &out, None, 0, 595).unwrap().to_rgb8(); + for a in every_annotation() { + let r = match &a.shape { + Shape::Highlight { rects } | Shape::Underline { rects } | Shape::Strike { rects } => rects[0], + Shape::Note { at } => ViewRect { x: at.x, y: at.y, w: 20.0, h: 20.0 }, + Shape::FreeText { rect, .. } | Shape::Rectangle { rect, .. } | Shape::Ellipse { rect, .. } => *rect, + Shape::Ink { .. } => ViewRect { x: 60.0, y: 330.0, w: 200.0, h: 50.0 }, + Shape::Line { .. } => ViewRect { x: 60.0, y: 420.0, w: 240.0, h: 40.0 }, + }; + let changed = (r.y as u32..(r.y + r.h) as u32) + .flat_map(|y| (r.x as u32..(r.x + r.w) as u32).map(move |x| (x, y))) + .filter(|&(x, y)| before.get_pixel(x, y) != after.get_pixel(x, y)) + .count(); + assert!(changed > 10, "{:?} did not show ({changed} pixels changed)", a.shape); + } + // The free text's Czech letters survive as text once flattened. + let flat = pictor_pdf::flatten(engine(), &out).unwrap(); + let text = pictor_pdf::extract_text(engine(), &flat, None).unwrap().concat(); + assert!(text.contains("Příliš žluťoučký kůň"), "free text lost its letters: {text:?}"); +} + +#[test] +fn a_free_text_on_a_rotated_page_lands_where_it_was_drawn() { + let input = pictor_pdf::reorganise(&numbered_pdf(1, "R"), None, &[pictor_pdf::PageSpec::Existing { index: 0, rotate: 90 }]).unwrap(); + let rect = ViewRect { x: 100.0, y: 300.0, w: 300.0, h: 40.0 }; + let edits = Edits { + annotations: vec![Annotation { + page: 0, + shape: Shape::FreeText { rect, text: "MMMMMMMMMMMM".into(), size: 24.0 }, + color: [0.0, 0.0, 0.0], + opacity: 1.0, + contents: None, + }], + ..Default::default() + }; + let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes; + let img = pictor_pdf::render_page(engine(), &out, None, 0, 842).unwrap().to_rgb8(); + assert!(dark_pixels(&img, rect, 1.0) > 200, "the text is not inside its box on a rotated page"); + // Upright: the ink is spread wide (horizontally), not tall. + let rows_with_ink = (rect.y as u32..(rect.y + rect.h) as u32) + .filter(|&y| (rect.x as u32..(rect.x + rect.w) as u32).any(|x| img.get_pixel(x, y).0[0] < 100)) + .count(); + assert!(rows_with_ink < 40, "the text looks rotated"); +} + +fn signature_png() -> Vec { + let img = image::RgbaImage::from_fn(300, 100, |x, y| { + let on = ((y as i32 - 50) - ((x as f32 / 20.0).sin() * 30.0) as i32).abs() < 4; + if on { image::Rgba([200, 0, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) } + }); + let mut out = Vec::new(); + image::DynamicImage::ImageRgba8(img).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +#[test] +fn a_signature_stamp_is_burned_into_the_page() { + let input = numbered_pdf(2, "Contract"); + let rect = ViewRect { x: 300.0, y: 700.0, w: 200.0, h: 80.0 }; + let edits = Edits { stamps: vec![Stamp { page: 1, rect, image: signature_png() }], ..Default::default() }; + let out = pictor_pdf::apply(engine(), &input, None, &edits).unwrap().bytes; + let img = pictor_pdf::render_page(engine(), &out, None, 1, 595).unwrap().to_rgb8(); + let red = (700..780).flat_map(|y| (300..500).map(move |x| (x, y))).filter(|&(x, y)| { + let p = img.get_pixel(x, y).0; + p[0] > 150 && p[1] < 80 + }).count(); + assert!(red > 100, "the signature is not visible ({red} red pixels)"); + // Transparent parts stay transparent: the page is white just above the signature's line. + assert_eq!(img.get_pixel(305, 702).0, [255, 255, 255]); + // The page's own text is untouched, and the stamp is page content, not an annotation. + assert_eq!(pictor_pdf::extract_text(engine(), &out, None).unwrap()[1].trim(), "Contract page 2"); + let doc = Document::load_mem(&out).unwrap(); + assert!(doc.get_dictionary(page_ids(&doc)[1]).unwrap().get(b"Annots").is_err()); + // A broken image is refused. + let bad = Edits { stamps: vec![Stamp { page: 0, rect, image: b"not a png".to_vec() }], ..Default::default() }; + assert!(pictor_pdf::apply(engine(), &input, None, &bad).is_err()); +} + +#[test] +fn a_protected_document_stays_protected_with_its_password() { + let locked = pictor_pdf::protect(&numbered_pdf(1, "Secret"), None, "pw", None).unwrap(); + let edits = Edits { annotations: vec![every_annotation().remove(0)], ..Default::default() }; + let out = pictor_pdf::apply(engine(), &locked, Some("pw"), &edits).unwrap().bytes; + assert!(pictor_pdf::is_encrypted(&out)); + assert_eq!(pictor_pdf::extract_text(engine(), &out, Some("pw")).unwrap()[0].trim(), "Secret page 1"); + let removed = pictor_pdf::apply(engine(), &locked, Some("pw"), &Edits { security: Security::Remove, ..Default::default() }).unwrap().bytes; + assert!(!pictor_pdf::is_encrypted(&removed)); + assert!(pictor_pdf::apply(engine(), &locked, Some("wrong"), &edits).is_err()); +} + +#[test] +fn edits_serialise_for_the_worker() { + let edits = Edits { annotations: every_annotation(), stamps: vec![Stamp { page: 0, rect: ViewRect { x: 1.0, y: 1.0, w: 2.0, h: 2.0 }, image: vec![0, 1, 2, 250, 255] }], ..Default::default() }; + let json = serde_json::to_string(&edits).unwrap(); + let back: Edits = serde_json::from_str(&json).unwrap(); + assert_eq!(back.annotations.len(), 9); + assert_eq!(back.stamps[0].image, vec![0, 1, 2, 250, 255]); +}