Files
Pictor-public/crates/pdf/tests/edit.rs
T

334 lines
16 KiB
Rust

//! 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<u8> {
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::<u32>() < 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<Annotation> {
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<String> = 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<u8> {
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]);
}