Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(forms): draw fields the file leaves to the viewer, for display only (#3470)

mtlcl410b661ba4584e5
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 8f39248ab..3caa0c828 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -876,12 +876,13 @@ fn is_placeholder_title(title: &str) -> bool {
address || t == "untitled"
}
-/// The working file plus appearances for comments that have none. Signature artwork
-/// is preserved; validation badges belong to the viewer and never enter these bytes,
-/// which image/text exports and Print as Image also consume.
+/// The working file plus appearances for comments that have none, and for form fields the file
+/// leaves to the viewer (#3470). Signature artwork is preserved; validation badges belong to the
+/// viewer and never enter these bytes, which image/text exports and Print as Image also consume.
fn display_bytes(editor: Option<&mut Editor>, bytes: &Arc<Vec<u8>>) -> Arc<Vec<u8>> {
let Some(e) = editor else { return bytes.clone() };
- let Some(display) = pdfcraft_annot::with_missing_appearances_cached(&e.cos, &mut e.appearances) else {
+ let comments = pdfcraft_annot::with_missing_appearances_cached(&e.cos, &mut e.appearances);
+ let Some(display) = with_field_appearances(comments, &e.cos) else {
return bytes.clone();
};
match write_incremental(&display, &SaveOptions::default()) {
@@ -893,6 +894,12 @@ fn display_bytes(editor: Option<&mut Editor>, bytes: &Arc<Vec<u8>>) -> Arc<Vec<u
}
}
+/// `comments` (the display copy with comment appearances, if it needed any; else the document
+/// itself) with its form fields drawn from their values where the file leaves that to the viewer.
+fn with_field_appearances(comments: Option<pdfcraft_cos::Document>, doc: &pdfcraft_cos::Document) -> Option<pdfcraft_cos::Document> {
+ pdfcraft_forms::with_field_appearances(comments.as_ref().unwrap_or(doc)).or(comments)
+}
+
/// The reader shows the same pages in `a` and `b`: count, displayed size and rotation.
fn same_pages(a: &[pdfcraft_render::PageInfo], b: &[pdfcraft_render::PageInfo]) -> bool {
a.len() == b.len()
@@ -900,14 +907,14 @@ fn same_pages(a: &[pdfcraft_render::PageInfo], b: &[pdfcraft_render::PageInfo])
}
/// The copy PDFCraft displays when opening `bytes`: with appearances drawn, in memory only, for
-/// comments that have none. Render paths outside the app, such as the CLI, use this so their page
+/// comments that have none and form fields the file leaves to the viewer. Render paths outside the app, such as the CLI, use this so their page
/// images agree with the app and independent viewers. It never changes the source document, and an
/// unparseable file, a write failure or a parser panic falls back to the original bytes.
pub fn display_bytes_for(bytes: Arc<Vec<u8>>, password: Option<&str>) -> Arc<Vec<u8>> {
guard(|| {
pdfcraft_cos::Document::open_with_password(bytes.clone(), password)
.ok()
- .and_then(|cos| pdfcraft_annot::with_missing_appearances(&cos))
+ .and_then(|cos| with_field_appearances(pdfcraft_annot::with_missing_appearances(&cos), &cos))
.and_then(|display| write_incremental(&display, &SaveOptions::default()).ok())
.map(Arc::new)
})
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index f125c41da..d199eeb70 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -6106,3 +6106,63 @@ fn undo_never_makes_an_unsaved_document_clean() {
s.undo(new).unwrap();
assert!(!s.get(new).unwrap().dirty, "once saved, undo back to the saved state is clean");
}
+
+/// #3470: a filled form whose writer left the appearances to the viewer (`/NeedAppearances`):
+/// field A has an empty appearance, B none. The page as displayed (and printed) shows both
+/// values, and a comment without an appearance beside them still gets its own; the file itself
+/// is not changed, so saving writes it as it was.
+#[test]
+fn fields_left_to_the_viewer_are_displayed_from_their_values() {
+ let pdf = |need: bool| {
+ let flag = if need { "/NeedAppearances true " } else { "" };
+ format!(
+ "%PDF-1.7\n\
+ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >> endobj\n\
+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 10 0 R] >> endobj\n\
+ 10 0 obj << /Type /Annot /Subtype /Square /Rect [360 20 390 50] /C [1 0 0] /BS << /W 4 >> >> endobj\n\
+ 5 0 obj << /Fields [6 0 R 7 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 8 0 R >> >> >> endobj\n\
+ 6 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (a) /V (MMMMMMMM) /DA (/Helv 12 Tf 0 g) /Rect [50 120 350 140] /F 4 /P 3 0 R /AP << /N 9 0 R >> >> endobj\n\
+ 7 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (b) /V (MMMMMMMM) /DA (/Helv 12 Tf 0 g) /Rect [50 60 350 80] /F 4 /P 3 0 R >> endobj\n\
+ 8 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\
+ 9 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 300 20] /Length 4 >> stream\nq\nQ\nendstream endobj\n\
+ trailer << /Root 1 0 R >>\n%%EOF"
+ )
+ .into_bytes()
+ };
+ let red = |s: &Session, id: DocId| {
+ let doc = s.get(id).unwrap();
+ let mut r = pdfcraft_render::PageRenderer::new(doc.display.clone(), doc.config.clone());
+ let page = r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ page.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] > 200 && p[1] < 80 && p[2] < 80).count()
+ };
+ // Dark pixels inside a field's box (user-space rectangle, page drawn at scale 1).
+ let ink = |s: &Session, id: DocId, y0: u32, y1: u32| {
+ let doc = s.get(id).unwrap();
+ let mut r = pdfcraft_render::PageRenderer::new(doc.display.clone(), doc.config.clone());
+ let page = r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ let (px, _) = page.rgba.as_chunks::<4>();
+ (200 - y1..200 - y0)
+ .flat_map(|y| (55..345).map(move |x| (x, y)))
+ .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(|p| p[0] < 128))
+ .count()
+ };
+ let mut s = Session::new();
+ let id = s.open("form.pdf", None, Arc::new(pdf(true)), None).unwrap();
+ let (a, b) = (ink(&s, id, 122, 138), ink(&s, id, 62, 78));
+ assert!(a > 100 && b > 100, "both values are shown: a {a}, b {b}");
+ assert!(red(&s, id) > 100, "the comment is drawn too");
+ // The file is saved as it was: B still has no appearance, A its empty one.
+ let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();
+ let fields = pdfcraft_forms::fields(&saved);
+ let widget = |name: &str| saved.get(fields.iter().find(|f| f.name == name).unwrap().widgets[0].obj);
+ assert!(widget("b").as_dict().is_some_and(|d| !d.contains(b"AP")), "B has no appearance");
+ let n = widget("a").as_dict().and_then(|d| d.get(b"AP").and_then(|ap| saved.resolve(ap).as_dict().and_then(|ap| ap.reference(b"N")))).unwrap();
+ let pdfcraft_cos::Object::Stream(n) = &*saved.get(n) else { panic!("A's appearance is a stream") };
+ assert_eq!(n.decoded().unwrap().trim_ascii_end(), b"q\nQ", "A keeps its empty appearance");
+
+ // Without the flag, the empty appearance is the file's own, and only B is drawn.
+ let id = s.open("form.pdf", None, Arc::new(pdf(false)), None).unwrap();
+ let (a, b) = (ink(&s, id, 122, 138), ink(&s, id, 62, 78));
+ assert!(a == 0 && b > 100, "a {a}, b {b}");
+}
diff --git a/crates/forms/README.md b/crates/forms/README.md
index 66fb919fe..a05b69b94 100644
--- a/crates/forms/README.md
+++ b/crates/forms/README.md
@@ -42,6 +42,10 @@ delete_field(&mut doc, "email")?;
that have them. Not in a document that declares PDF/A, which forbids that flag (`declares_pdfa`).
`undrawn_fields` lists the marked fields; the engine reports each edit that draws one, and
flattening refuses to make that `?` permanent.
+- Displaying a form that leaves its appearances to the viewer (`/NeedAppearances`, or a text or
+ choice widget with no `/AP /N`): `with_field_appearances` returns a copy with those widgets
+ drawn from their values, as typing them would draw them; the engine shows and prints that copy
+ and saves the file as it was (#3470).
- Check boxes and radio buttons switch `/V` and each widget's `/AS`. Widgets with no appearances
get PdfCraft's own (a drawn check mark or dot; no symbol font needed).
- Values are validated (options, `MaxLen`, single vs multi-select, NoToggleToOff, read-only) and a
diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs
index 1dfa76726..8d78fb899 100644
--- a/crates/forms/src/lib.rs
+++ b/crates/forms/src/lib.rs
@@ -1232,6 +1232,34 @@ pub fn need_appearances(doc: &Document) -> bool {
acroform(doc).is_some_and(|af| matches!(af.get(b"NeedAppearances").map(|o| doc.resolve(o)).as_deref(), Some(Object::Bool(true))))
}
+/// A copy of `doc` in which text and choice fields are drawn from their values, for displaying
+/// the document (`None` when no widget needs it): every such widget when the form sets
+/// `/NeedAppearances` (ISO 32000-2 Table 224: the writer left the appearances to the viewer),
+/// and otherwise each widget without a normal appearance (`/AP /N`). Drawn as typing the value
+/// would draw it (#3470). `doc` is not changed: saving writes the file as it was.
+pub fn with_field_appearances(doc: &Document) -> Option<Document> {
+ let all = need_appearances(doc);
+ let mut copy: Option<Document> = None;
+ for f in fields(doc).iter().filter(|f| matches!(f.kind, FieldKind::Text | FieldKind::Combo | FieldKind::List)) {
+ for w in &f.widgets {
+ let widget = doc.get(w.obj);
+ let drawn = widget.as_dict().and_then(|d| d.get(b"AP")).is_some_and(|ap| doc.resolve(ap).as_dict().is_some_and(|ap| ap.contains(b"N")));
+ if drawn && !all {
+ continue;
+ }
+ let (stream, _) = appearance::field_appearance_drawn(doc, f, w, &f.value, true);
+ let target = copy.get_or_insert_with(|| doc.clone());
+ let ap = target.add(Object::Stream(stream));
+ let mut fresh = Dict::new();
+ fresh.set(b"N".to_vec(), Object::Ref(ap));
+ let apd = merged_appearance(target, w.obj, &fresh);
+ // Fails only when the widget isn't a dictionary; that widget then keeps its own look.
+ target.update_dict(w.obj, |d| d.set(b"AP".to_vec(), Object::Dict(apd))).ok();
+ }
+ }
+ copy
+}
+
/// Whether the document's XMP metadata declares PDF/A conformance (`pdfaid:part`).
pub fn declares_pdfa(doc: &Document) -> bool {
let Some(root) = doc.root() else { return false };
diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs
index fef5bcfbd..987a74f2c 100644
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@ -2277,3 +2277,64 @@ fn document_scripts_read_each_name_tree_node_once() {
]);
assert_eq!(document_scripts_named(&doc), [("init".to_string(), "var ready = true;".to_string())]);
}
+
+/// #3470: a form whose writer left the appearances to the viewer. Field A has an empty one,
+/// B none, C its own (`(old C)`), D is a combo without one, E a check box with states, F a list
+/// box without one, and G only a down appearance (`/D`, no `/N`).
+fn left_to_the_viewer(need_appearances: bool) -> Document {
+ let flag = if need_appearances { "/NeedAppearances true " } else { "" };
+ document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 13 0 R 14 0 R] >>".into(),
+ format!("<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 13 0 R 14 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>"),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (a) /V (Value A) /DA (/Helv 12 Tf 0 g) /Rect [50 700 350 720] /P 3 0 R /AP << /N 11 0 R >> >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (b) /V (Value B) /DA (/Helv 12 Tf 0 g) /Rect [50 650 350 670] /P 3 0 R >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (c) /V (Value C) /DA (/Helv 12 Tf 0 g) /Rect [50 600 350 620] /P 3 0 R /AP << /N 12 0 R >> >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Ch /Ff 131072 /T (d) /Opt [(Red) (Blue)] /V (Blue) /DA (/Helv 12 Tf 0 g) /Rect [50 550 350 570] /P 3 0 R >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T (e) /V /Yes /AS /Yes /Rect [400 700 415 715] /P 3 0 R /AP << /N << /Yes 11 0 R /Off 11 0 R >> >> >>".into(),
+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(),
+ "<< /Length 18 >>\nstream\nBT (old C) Tj ET\nendstream".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Ch /T (f) /Opt [(Green) (Grey)] /V (Green) /DA (/Helv 12 Tf 0 g) /Rect [50 450 350 520] /P 3 0 R >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (g) /V (Value G) /DA (/Helv 12 Tf 0 g) /Rect [50 400 350 420] /P 3 0 R /AP << /D 11 0 R >> >>".into(),
+ ])
+}
+
+/// #3470: with `/NeedAppearances`, every text and choice widget of the display copy is drawn
+/// from its value, its own appearance or not; buttons keep their states, and the document
+/// itself is untouched.
+#[test]
+fn need_appearances_draws_every_text_and_choice_field_in_the_display_copy() {
+ let doc = left_to_the_viewer(true);
+ let copy = with_field_appearances(&doc).expect("fields to draw");
+ let all = fields(&copy);
+ for (name, value) in
+ [("a", "(Value A) Tj"), ("b", "(Value B) Tj"), ("c", "(Value C) Tj"), ("d", "(Blue) Tj"), ("f", "(Green) Tj"), ("g", "(Value G) Tj")]
+ {
+ let shown = ap(&copy, &field(&all, name).widgets[0]);
+ assert!(shown.contains(value), "{name}: {shown}");
+ }
+ let e = |d: &Document| d.get(field(&fields(d), "e").widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());
+ assert_eq!(e(&copy), e(&doc), "the check box keeps its states");
+ let original = fields(&doc);
+ assert_eq!(ap(&doc, &field(&original, "a").widgets[0]).trim_end(), "q\nQ", "the document keeps its own appearances");
+ assert!(doc.get(field(&original, "b").widgets[0].obj).as_dict().is_some_and(|w| !w.contains(b"AP")));
+}
+
+/// #3470: without `/NeedAppearances`, only widgets with no normal appearance are drawn; an
+/// appearance the file has, even an empty one, is the file's. A form with all of them needs no
+/// copy.
+#[test]
+fn without_need_appearances_only_missing_appearances_are_drawn() {
+ let doc = left_to_the_viewer(false);
+ let copy = with_field_appearances(&doc).expect("b, d, f and g have none");
+ let all = fields(&copy);
+ assert_eq!(ap(&copy, &field(&all, "a").widgets[0]).trim_end(), "q\nQ");
+ assert!(ap(&copy, &field(&all, "b").widgets[0]).contains("(Value B) Tj"));
+ assert_eq!(ap(&copy, &field(&all, "c").widgets[0]).trim_end(), "BT (old C) Tj ET");
+ assert!(ap(&copy, &field(&all, "d").widgets[0]).contains("(Blue) Tj"));
+ assert!(ap(&copy, &field(&all, "f").widgets[0]).contains("(Green) Tj"));
+ assert!(ap(&copy, &field(&all, "g").widgets[0]).contains("(Value G) Tj"), "a down appearance alone is no normal one");
+ assert!(with_field_appearances(&copy).is_none(), "every widget has one now");
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index e19efb0a0..35812170b 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -806,8 +806,8 @@ milestone = "M2"
status = "shipped"
commands = []
tools = []
-evidence = ["crates/render/src/raster.rs::widget_appearance_states", "crates/render/src/raster.rs::highlights_without_an_appearance_are_drawn", "crates/engine/src/tests.rs::comments_without_appearances_are_drawn_but_not_saved", "crates/engine/src/tests.rs::cli_display_adds_missing_appearances_without_changing_the_source"]
-notes = "comments without /AP (FreeText, Ink, notes, stamps, shapes, markup) are drawn from their dictionaries in the page view, page_render and page images, including the CLI render command, never saved (a read-only document still gets the renderer's Highlight fallback only); Link borders without /AP and printing are not covered yet"
+evidence = ["crates/render/src/raster.rs::widget_appearance_states", "crates/render/src/raster.rs::highlights_without_an_appearance_are_drawn", "crates/engine/src/tests.rs::comments_without_appearances_are_drawn_but_not_saved", "crates/engine/src/tests.rs::cli_display_adds_missing_appearances_without_changing_the_source", "crates/engine/src/tests.rs::fields_left_to_the_viewer_are_displayed_from_their_values", "crates/forms/src/tests.rs::need_appearances_draws_every_text_and_choice_field_in_the_display_copy"]
+notes = "comments without /AP (FreeText, Ink, notes, stamps, shapes, markup) are drawn from their dictionaries in the page view, page_render and page images, including the CLI render command, never saved; text and choice fields are drawn from their values when the form sets /NeedAppearances (every one) or a widget has no /N (#3470), also display-only. Not cached: a form with 1000 such fields adds about 80 ms to each refresh (a read-only document still gets the renderer's Highlight fallback only); Link borders without /AP and printing are not covered yet"
[[feature]]
id = "view.render-error-isolation"