Skip to content

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

M5.6/M6.7: Comment and form data exchange: new xfdf crate (L4): XFDF (ISO 19444-1) export/import of comments (replies, pop-ups, ink, quads, line ends, flags, colours) and nested field values; FDF both ways; form data as Acrobat XML, CSV and tab-delimited text. Import replaces comments with the same name and sets values through formats/validation (read-only fields take data). Import/Export commands; doc_export_data/doc_import_data tools (69 tools)

Brandon Thomas22a869147548
diff --git a/Cargo.lock b/Cargo.lock
index a59d8d2e9..6d55eff00 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3130,6 +3130,7 @@ version = "0.1.0"
dependencies = [
"hayro-syntax",
"printcraft-annot",
+ "printcraft-content",
"printcraft-cos",
"printcraft-fonts",
"printcraft-model",
@@ -3153,6 +3154,7 @@ dependencies = [
"printcraft-print",
"printcraft-redact",
"printcraft-render",
+ "printcraft-xfdf",
"thiserror 2.0.21",
]
@@ -3275,6 +3277,18 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "printcraft-xfdf"
+version = "0.1.0"
+dependencies = [
+ "printcraft-annot",
+ "printcraft-cos",
+ "printcraft-forms",
+ "printcraft-model",
+ "roxmltree",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
diff --git a/Cargo.toml b/Cargo.toml
index 4d43991b5..c32e89539 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,6 +24,7 @@ printcraft-model = { path = "crates/model", version = "0.1.0" }
printcraft-content = { path = "crates/content", version = "0.1.0" }
printcraft-redact = { path = "crates/redact", version = "0.1.0" }
printcraft-print = { path = "crates/print", version = "0.1.0" }
+printcraft-xfdf = { path = "crates/xfdf", version = "0.1.0" }
printcraft-edit = { path = "crates/edit", version = "0.1.0" }
printcraft-create = { path = "crates/create", version = "0.1.0" }
printcraft-forms = { path = "crates/forms", version = "0.1.0" }
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs
index 9f81059fe..e47aefc2c 100644
--- a/crates/annot/src/lib.rs
+++ b/crates/annot/src/lib.rs
@@ -590,7 +590,8 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> R
}
/// (Re)generate `/AP /N` for the annotation `r` from its dictionary.
-fn set_appearance(doc: &mut Document, r: ObjRef) -> Result<(), AnnotError> {
+/// Regenerate an annotation's normal appearance from its dictionary.
+pub fn set_appearance(doc: &mut Document, r: ObjRef) -> Result<(), AnnotError> {
let d = annot_dict(doc, r);
let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
let Some(stream) = appearance::build(&d) else { return Err(AnnotError::Unsupported(subtype)) };
diff --git a/crates/automation/src/forms.rs b/crates/automation/src/forms.rs
index 0c8e5e775..c01b438fc 100644
--- a/crates/automation/src/forms.rs
+++ b/crates/automation/src/forms.rs
@@ -387,4 +387,36 @@ impl Automation {
}
self.apply(a, Edit::DeleteField { name })
}
+
+ pub(crate) fn doc_export_data(&mut self, a: &Args) -> Result<Value> {
+ let id = self.doc(a)?.id;
+ let path = self.resolve(a.str("path")?, true)?;
+ let ext = path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();
+ let format =
+ printcraft_engine::DataFormat::from_extension(&ext).ok_or_else(|| bad("the path must end in .xfdf, .fdf, .xml, .csv or .txt"))?;
+ let (comments, fields) = match a.opt_str("what")?.unwrap_or("all") {
+ "all" => (true, true),
+ "comments" => (true, false),
+ "fields" => (false, true),
+ w => return Err(bad(format!("unknown what {w:?} (all, comments, fields)"))),
+ };
+ if comments && !matches!(format, printcraft_engine::DataFormat::Xfdf | printcraft_engine::DataFormat::Fdf) {
+ return Err(bad("comments travel as .xfdf or .fdf; .xml, .csv and .txt hold form data (use what: fields)"));
+ }
+ let bytes = self.session.export_data(id, format, comments, fields).map_err(failed)?;
+ crate::write_atomic(&path, &bytes)?;
+ Ok(json!({ "path": path.to_string_lossy(), "bytes": bytes.len() }))
+ }
+
+ pub(crate) fn doc_import_data(&mut self, a: &Args) -> Result<Value> {
+ let path = self.resolve(a.str("path")?, false)?;
+ let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?;
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ let before = (self.doc(a)?.info.annotations.len(), self.doc(a)?.form.iter().filter(|f| !f.value.is_empty()).count());
+ let mut out = self.apply(a, Edit::ImportData { name, bytes: std::sync::Arc::new(bytes) })?;
+ let doc = self.doc(a)?;
+ out["comments"] = json!(doc.info.annotations.len() as i64 - before.0 as i64);
+ out["filled_fields"] = json!(doc.form.iter().filter(|f| !f.value.is_empty()).count());
+ Ok(out)
+ }
}
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index c38ec673a..889a35252 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -260,6 +260,8 @@ impl Automation {
"form_set_props" => self.form_set_props(&a)?,
"form_delete_field" => self.form_delete_field(&a)?,
"form_tab_order" => self.form_tab_order(&a)?,
+ "doc_export_data" => self.doc_export_data(&a)?,
+ "doc_import_data" => self.doc_import_data(&a)?,
"redact_mark" => self.redact_mark(&a)?,
"redact_apply" => self.redact_apply(&a)?,
"redact_clear" => self.redact_clear(&a)?,
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 522c171f1..85b5d99d2 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -260,6 +260,11 @@ pub fn tools() -> Vec<ToolDef> {
)),
t("form_tab_order", "Set the tab order", "Set the tab order of pages (default all): row (top to bottom, left to right), column, structure, or annotations (unspecified). Returns the resulting order of fields. Undoable.")
.with(schema(json!({ "doc": doc(), "order": { "type": "string", "enum": ["row", "column", "structure", "annotations"] }, "pages": pages("to set (default: all)") }), &["doc", "order"])),
+ t("doc_export_data", "Export comments or form data", "Write comments and/or form data to path; the extension picks the format: .xfdf or .fdf (comments and/or fields), .xml, .csv or .txt (form data). what: all (default), comments, fields.")
+ .ro()
+ .with(schema(json!({ "doc": doc(), "path": { "type": "string" }, "what": { "type": "string", "enum": ["all", "comments", "fields"] } }), &["doc", "path"])),
+ t("doc_import_data", "Import comments or form data", "Import comments and/or field values from an XFDF, FDF, XML, CSV or tab-delimited text file (detected from its content). Comments with the same name are replaced; values go through the form's formats and validation. Undoable.")
+ .with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
t("form_delete_field", "Delete a field", "Delete a form field and all its widgets. Undoable.")
.destructive()
.with(schema(json!({ "doc": doc(), "field": { "type": "string" } }), &["doc", "field"])),
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 5f9c71e56..59a9df7de 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -780,3 +780,26 @@ fn tab_order_and_field_appearance_through_tools() {
Err(ToolError::InvalidArgs(_))
));
}
+
+#[test]
+fn comments_and_form_data_travel_as_xfdf_fdf_and_text() {
+ let dir = workdir("xfdf");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "note", "at": [30, 30], "contents": "Please review", "author": "Ada" }));
+ ok(&mut a, "form_add_field", json!({ "doc": doc, "page": 1, "type": "text", "rect": [20, 20, 180, 42], "name": "City" }));
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "City": "Paris" } }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "reviewed.pdf" }));
+ ok(&mut a, "doc_export_data", json!({ "doc": doc, "path": "all.xfdf" }));
+ ok(&mut a, "doc_export_data", json!({ "doc": doc, "path": "data.txt", "what": "fields" }));
+ assert_eq!(std::fs::read_to_string(dir.join("data.txt")).unwrap(), "City\nParis\n");
+ assert!(matches!(a.call("doc_export_data", &json!({ "doc": doc, "path": "c.csv", "what": "comments" })), Err(ToolError::InvalidArgs(_))));
+ // A copy without the comment and with the field empty takes both back.
+ ok(&mut a, "comment_delete", json!({ "doc": doc, "page": 2, "index": 1 }));
+ ok(&mut a, "form_reset", json!({ "doc": doc }));
+ let r = ok(&mut a, "doc_import_data", json!({ "doc": doc, "path": "all.xfdf" }));
+ assert_eq!(r["filled_fields"], 1);
+ let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
+ assert_eq!(list["comments"][0]["contents"], "Please review", "{list}");
+ assert_eq!(r["undo"], "Import all.xfdf");
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 7802445a7..65464ca39 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -18,6 +18,7 @@ printcraft-forms = { workspace = true }
printcraft-edit = { workspace = true }
printcraft-redact = { workspace = true }
printcraft-print = { workspace = true }
+printcraft-xfdf = { workspace = true }
printcraft-create = { workspace = true }
printcraft-model = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs
index 14ad7eb22..52a69d1d6 100644
--- a/crates/engine/src/catalog.rs
+++ b/crates/engine/src/catalog.rs
@@ -323,6 +323,8 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
item("Tab order by rows", "rows-3", "form.tab_order.row", Ready),
item("Tab order by columns", "columns-3", "form.tab_order.column", Ready),
item("Flatten form fields", "layers", "form.flatten", Ready),
+ item("Import data", "file-input", "form.import_data", Ready),
+ item("Export data", "file-output", "form.export_data", Ready),
],
},
ToolSection {
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index ba9bf3c7b..1aa601e85 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -178,6 +178,10 @@ pub const COMMANDS: &[CommandSpec] = &[
c("form.fields", "Form fields panel", VIEW, None, Document, "list"),
c("form.clear", "Clear form", EDIT, None, FillForms, "eraser"),
c("comment.flatten", "Flatten comments", None, None, HasComments, "layers"),
+ c("comment.import", "Import comments…", None, None, Modification, "file-input"),
+ c("comment.export", "Export all comments to data file…", None, None, HasComments, "file-output"),
+ c("form.import_data", "Import form data…", None, None, HasFields, "file-input"),
+ c("form.export_data", "Export form data…", None, None, HasFields, "file-output"),
c("form.flatten", "Flatten form fields", None, None, HasFields, "layers"),
c("form.prepare", "Prepare a form", None, None, Modification, "text-cursor-input"),
c("form.tab_order.row", "Tab order: by rows", None, None, HasFields, "rows-3"),
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index cd3497061..b7016f98f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -35,6 +35,7 @@ pub use printcraft_annot::{FillMark, Markup, NewAnnotation, NoteIcon, Props as C
pub use printcraft_print as print;
pub use printcraft_redact::patterns::{PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern};
pub use printcraft_redact::sanitize::{HIDDEN, Hidden};
+pub use printcraft_xfdf::Format as DataFormat;
pub type SplitPart = (usize, usize, Arc<Vec<u8>>);
@@ -608,6 +609,11 @@ pub enum Edit {
},
/// Remove redaction marks without applying them.
ClearRedactions,
+ /// Import comments and/or form data (XFDF, FDF, XML, CSV, tab-delimited text).
+ ImportData {
+ name: String,
+ bytes: Arc<Vec<u8>>,
+ },
/// Remove Hidden Information: the chosen categories.
RemoveHidden {
which: Vec<Hidden>,
@@ -681,6 +687,7 @@ impl Edit {
Edit::ApplyRedactions { .. } => "Apply redactions".into(),
Edit::ClearRedactions => "Remove redaction marks".into(),
Edit::RemoveHidden { .. } => "Remove hidden information".into(),
+ Edit::ImportData { name, .. } => format!("Import {name}"),
Edit::Sanitize => "Sanitize document".into(),
Edit::Flatten { comments: true, fields: false } => "Flatten comments".into(),
Edit::Flatten { comments: false, fields: true } => "Flatten form fields".into(),
@@ -790,6 +797,7 @@ fn check_permission(edit: &Edit, p: &printcraft_cos::Permissions) -> Result<(),
| Edit::ReplaceImage { .. }
| Edit::ClearRedactions
| Edit::RemoveHidden { .. }
+ | Edit::ImportData { .. }
| Edit::Sanitize
| Edit::SetFieldProps { .. }
| Edit::DeleteField { .. }
@@ -975,6 +983,9 @@ fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -
Edit::ClearRedactions => {
printcraft_redact::clear_marks(doc, None)?;
}
+ Edit::ImportData { bytes, .. } => {
+ printcraft_xfdf::import(doc, bytes)?;
+ }
Edit::RemoveHidden { which } => {
printcraft_redact::sanitize::remove_hidden(doc, which)?;
}
@@ -1102,6 +1113,8 @@ pub enum EditError {
Redact(#[from] printcraft_redact::RedactError),
#[error("{0}")]
Print(String),
+ #[error(transparent)]
+ Data(#[from] printcraft_xfdf::DataError),
#[error("{0}")]
Edit(#[from] printcraft_edit::EditError),
#[error("{0}")]
@@ -1451,6 +1464,22 @@ impl Session {
Ok((Arc::new(bytes), merged))
}
+ /// Export comments and/or form data: XFDF and FDF carry either or both; XML, CSV and text
+ /// are form data only.
+ pub fn export_data(&self, id: DocId, format: DataFormat, comments: bool, fields: bool) -> Result<Vec<u8>, EditError> {
+ let doc = self.get(id).ok_or(EditError::NoDocument)?;
+ let cos = match doc.editor.as_ref() {
+ Some(e) => e.cos.clone(),
+ None => printcraft_cos::Document::open_with_password(doc.bytes.clone(), doc.password.as_deref())
+ .map_err(|e| EditError::Write(e.to_string()))?,
+ };
+ Ok(match format {
+ DataFormat::Xfdf => printcraft_xfdf::export_xfdf(&cos, comments, fields, &doc.name).into_bytes(),
+ DataFormat::Fdf => printcraft_xfdf::export_fdf(&cos, comments, fields, &doc.name),
+ other => printcraft_xfdf::export_data(&cos, other).into_bytes(),
+ })
+ }
+
/// The print-ready PDF for `settings` (sheets laid out for the paper; see `printcraft-print`).
pub fn print_pdf(&self, id: DocId, settings: &print::Settings) -> Result<Vec<u8>, EditError> {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index ed8340808..e9cd97ac6 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -277,6 +277,9 @@ impl PrintCraftApp {
let n = active.and_then(|i| self.session.get(self.views[i].id)).map_or(0, |d| d.info.pages.len());
self.apply_edit(Edit::SetTabOrder { pages: (0..n).collect(), order });
}
+ "comment.import" | "form.import_data" => self.import_data_dialog(),
+ "comment.export" => self.export_data_dialog(true, false),
+ "form.export_data" => self.export_data_dialog(false, true),
"form.prepare" => {
self.left = crate::LeftPanel::Tool("form");
self.left_open = true;
diff --git a/crates/ui-egui/src/files.rs b/crates/ui-egui/src/files.rs
index 3d801155a..e3d7f54f2 100644
--- a/crates/ui-egui/src/files.rs
+++ b/crates/ui-egui/src/files.rs
@@ -232,3 +232,75 @@ impl PrintCraftApp {
fn strip_pdf(name: &str) -> &str {
name.strip_suffix(".pdf").or_else(|| name.strip_suffix(".PDF")).unwrap_or(name)
}
+
+impl PrintCraftApp {
+ /// Comments ▸ Import comments / Prepare a form ▸ Import data: XFDF, FDF, XML, CSV or text.
+ pub fn import_data_dialog(&mut self) {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let picked = match self.save_override.clone() {
+ Some(p) if [".xfdf", ".fdf", ".xml", ".csv", ".txt"].iter().any(|e| p.ends_with(e)) => Some(std::path::PathBuf::from(p)),
+ Some(_) => None,
+ None => rfd::FileDialog::new()
+ .add_filter("Comment and form data", &["xfdf", "fdf", "xml", "csv", "txt"])
+ .set_title("Import data")
+ .pick_file(),
+ };
+ let Some(path) = picked else { return };
+ match std::fs::read(&path) {
+ Ok(bytes) => {
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ self.apply_edit(printcraft_engine::Edit::ImportData { name, bytes: std::sync::Arc::new(bytes) });
+ }
+ Err(e) => self.notify(format!("Couldn't read {}: {e}", path.display())),
+ }
+ }
+ #[cfg(target_arch = "wasm32")]
+ self.notify("Importing data arrives on the web with file pickers for data files");
+ }
+
+ /// Export all comments / form data: the format follows the file name's extension.
+ pub fn export_data_dialog(&mut self, comments: bool, fields: bool) {
+ let Some((_, id)) = self.active_ids() else { return };
+ let Some(doc) = self.session.get(id) else { return };
+ let stem = doc.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string();
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let path = match self.save_override.clone() {
+ Some(p) => Some(std::path::PathBuf::from(p)),
+ None => {
+ let d = rfd::FileDialog::new()
+ .set_title(if comments { "Export comments" } else { "Export form data" })
+ .set_file_name(format!("{stem}.xfdf"));
+ let d = if comments {
+ d.add_filter("XFDF", &["xfdf"]).add_filter("FDF", &["fdf"])
+ } else {
+ d.add_filter("XFDF", &["xfdf"])
+ .add_filter("FDF", &["fdf"])
+ .add_filter("XML", &["xml"])
+ .add_filter("CSV", &["csv"])
+ .add_filter("Text", &["txt"])
+ };
+ d.save_file()
+ }
+ };
+ let Some(path) = path else { return };
+ let ext = path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();
+ let format = printcraft_engine::DataFormat::from_extension(&ext).unwrap_or(printcraft_engine::DataFormat::Xfdf);
+ match self.session.export_data(id, format, comments, fields) {
+ Ok(bytes) => match crate::editing::write_atomically(&path.to_string_lossy(), &bytes) {
+ Ok(()) => self.notify(format!("Exported to {}", path.display())),
+ Err(e) => self.notify(format!("Couldn't write {}: {e}", path.display())),
+ },
+ Err(e) => self.notify(e.to_string()),
+ }
+ }
+ #[cfg(target_arch = "wasm32")]
+ match self.session.export_data(id, printcraft_engine::DataFormat::Xfdf, comments, fields) {
+ Ok(bytes) => {
+ let _ = crate::editing::download(&format!("{stem}.xfdf"), &bytes);
+ }
+ Err(e) => self.notify(e.to_string()),
+ }
+ }
+}
diff --git a/crates/ui-egui/tests/commands.rs b/crates/ui-egui/tests/commands.rs
index 02fce260f..26de39a77 100644
--- a/crates/ui-egui/tests/commands.rs
+++ b/crates/ui-egui/tests/commands.rs
@@ -70,7 +70,7 @@ fn every_registered_command_is_implemented() {
app.apply_edit(Edit::AddWatermark { pages: vec![0], settings: Watermark { text: "x".into(), ..Watermark::default() }, replace: false });
app.apply_edit(Edit::AddBackground { pages: vec![0], settings: Background { color: [1.0; 3], opacity: 1.0 }, replace: false });
}
- if spec.id == "comment.flatten" {
+ if spec.id == "comment.flatten" || spec.id == "comment.export" {
use printcraft_engine::{Edit, NewAnnotation, Shape, Style};
let shape = Shape::Rectangle { rect: [10.0, 10.0, 50.0, 50.0] };
app.apply_edit(Edit::AddAnnotation(NewAnnotation {
diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml
new file mode 100644
index 000000000..e6ff01de1
--- /dev/null
+++ b/crates/xfdf/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "printcraft-xfdf"
+description = "Comment and form data exchange: XFDF (ISO 19444-1) and FDF import/export, form data as XML, CSV and tab-delimited text"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+printcraft-cos = { workspace = true }
+printcraft-annot = { workspace = true }
+printcraft-forms = { workspace = true }
+printcraft-model = { workspace = true }
+roxmltree = "0.20"
+thiserror = { workspace = true }
diff --git a/crates/xfdf/README.md b/crates/xfdf/README.md
new file mode 100644
index 000000000..ef02e1b18
--- /dev/null
+++ b/crates/xfdf/README.md
@@ -0,0 +1,22 @@
+# printcraft-xfdf
+
+Layer L4: comment and form data exchange (execution plan M5.6, M6.7).
+
+```rust
+let xml = export_xfdf(&doc, true, true, "form.pdf"); // comments and/or field values
+let fdf = export_fdf(&doc, false, true, "form.pdf");
+let txt = export_data(&doc, Format::Txt); // or Xml, Csv
+let report = import(&mut doc, &bytes)?; // XFDF, FDF, XML, CSV or text, detected
+```
+
+- **XFDF** (ISO 19444-1): every comment type PrintCraft knows (text, free text, line, square,
+ circle, polygon, polyline, markup, stamp, caret, ink, attachments, sound, redact) with rect,
+ name, author, subject, dates, flags, colours, opacity, width, icon, quads, line ends, ink,
+ default appearance, pop-ups and reply threads (`inreplyto`); field values nested by name.
+- **FDF**: fields (with `/Kids` hierarchies) and comments as direct objects.
+- **Form data**: Acrobat's XML (`xfdf:original` keeps names that aren't XML names), CSV and
+ tab-delimited text (a row of names, a row of values).
+
+Import replaces comments with the same `/NM`, draws appearances PrintCraft can draw, and sets
+values through the form's own checks (formats, validation, recalculation); read-only fields take
+imported values, as in Acrobat. XML is read with `roxmltree`.
diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs
new file mode 100644
index 000000000..81d6be7b2
--- /dev/null
+++ b/crates/xfdf/src/lib.rs
@@ -0,0 +1,836 @@
+//! Comment and form data exchange (execution plan M5.6, M6.7). Layer L4.
+//!
+//! - **XFDF** (ISO 19444-1, Acrobat's "Export all to data file" / "Import comments", and form
+//! data): comments with their geometry, colours, flags, authors, dates, replies, pop-ups,
+//! ink, quadrilaterals and line ends; field values, nested by name.
+//! - **FDF** (ISO 32000-2 §12.7.8): fields and comments in PDF syntax.
+//! - Form data as **XML**, **CSV** and **tab-delimited text** (Acrobat's Export data formats).
+//!
+//! Import merges: a comment whose name (`/NM`) already exists on its page replaces it; field
+//! values go through the form's own checks (formats, validation) and recalculate.
+
+use std::collections::HashMap;
+use std::fmt::Write as _;
+
+use printcraft_cos::{Dict, Document, ObjRef, Object, PdfString};
+use printcraft_forms::{FieldKind, FieldValue};
+
+#[cfg(test)]
+mod tests;
+
+#[derive(Debug, thiserror::Error, PartialEq)]
+pub enum DataError {
+ #[error("this file isn't XFDF, FDF, XML or text form data")]
+ UnknownFormat,
+ #[error("the file can't be read: {0}")]
+ Malformed(String),
+ #[error("nothing in the file matches this document")]
+ NothingImported,
+ #[error(transparent)]
+ Cos(#[from] printcraft_cos::CosError),
+}
+
+/// What export writes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Format {
+ Xfdf,
+ Fdf,
+ Xml,
+ Csv,
+ Txt,
+}
+
+impl Format {
+ pub fn from_extension(ext: &str) -> Option<Format> {
+ Some(match ext.to_ascii_lowercase().as_str() {
+ "xfdf" => Format::Xfdf,
+ "fdf" => Format::Fdf,
+ "xml" => Format::Xml,
+ "csv" => Format::Csv,
+ "txt" | "tab" | "tsv" => Format::Txt,
+ _ => return None,
+ })
+ }
+}
+
+/// What import did.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Report {
+ pub comments: usize,
+ pub fields: usize,
+ /// Field values the form refused (format, validation, unknown options).
+ pub rejected: Vec<String>,
+}
+
+// ── names ───────────────────────────────────────────────────────────────────────────────────
+
+const SUBTYPES: [(&str, &str); 17] = [
+ ("Text", "text"),
+ ("FreeText", "freetext"),
+ ("Line", "line"),
+ ("Square", "square"),
+ ("Circle", "circle"),
+ ("Polygon", "polygon"),
+ ("PolyLine", "polyline"),
+ ("Highlight", "highlight"),
+ ("Underline", "underline"),
+ ("Squiggly", "squiggly"),
+ ("StrikeOut", "strikeout"),
+ ("Stamp", "stamp"),
+ ("Caret", "caret"),
+ ("Ink", "ink"),
+ ("FileAttachment", "fileattachment"),
+ ("Sound", "sound"),
+ ("Redact", "redact"),
+];
+
+const FLAGS: [(i64, &str); 9] = [
+ (1, "invisible"),
+ (2, "hidden"),
+ (4, "print"),
+ (8, "nozoom"),
+ (16, "norotate"),
+ (32, "noview"),
+ (64, "readonly"),
+ (128, "locked"),
+ (256, "togglenoview"),
+];
+
+fn esc(s: &str) -> String {
+ let mut o = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => o.push_str("&amp;"),
+ '<' => o.push_str("&lt;"),
+ '>' => o.push_str("&gt;"),
+ '"' => o.push_str("&quot;"),
+ '\r' => o.push_str("&#13;"),
+ c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}
+ c => o.push(c),
+ }
+ }
+ o
+}
+
+fn n(v: f64) -> String {
+ let s = format!("{v:.4}");
+ let s = s.trim_end_matches('0').trim_end_matches('.');
+ if s == "-0" { "0".into() } else { s.into() }
+}
+
+fn hex(c: &[f64]) -> Option<String> {
+ let rgb = match c.len() {
+ 1 => [c[0]; 3],
+ 3 => [c[0], c[1], c[2]],
+ 4 => [(1.0 - c[0]) * (1.0 - c[3]), (1.0 - c[1]) * (1.0 - c[3]), (1.0 - c[2]) * (1.0 - c[3])],
+ _ => return None,
+ };
+ Some(format!(
+ "#{:02X}{:02X}{:02X}",
+ (rgb[0].clamp(0.0, 1.0) * 255.0).round() as u8,
+ (rgb[1].clamp(0.0, 1.0) * 255.0).round() as u8,
+ (rgb[2].clamp(0.0, 1.0) * 255.0).round() as u8
+ ))
+}
+
+fn parse_hex(s: &str) -> Option<[f64; 3]> {
+ let h = s.trim().trim_start_matches('#');
+ if h.len() != 6 {
+ return None;
+ }
+ let p = |i: usize| u8::from_str_radix(&h[i..i + 2], 16).ok().map(|v| f64::from(v) / 255.0);
+ Some([p(0)?, p(2)?, p(4)?])
+}
+
+fn nums_of(doc: &Document, o: Option<&Object>) -> Vec<f64> {
+ o.map(|o| doc.resolve(o)).and_then(|a| a.as_array().map(|a| a.iter().filter_map(|x| doc.resolve(x).as_f64()).collect())).unwrap_or_default()
+}
+
+fn text_of(doc: &Document, d: &Dict, k: &[u8]) -> Option<String> {
+ d.get(k).and_then(|o| match &*doc.resolve(o) {
+ Object::String(s) => Some(s.to_text()),
+ Object::Name(n) => Some(String::from_utf8_lossy(n).into_owned()),
+ _ => None,
+ })
+}
+
+fn csv(list: &str) -> Vec<f64> {
+ list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect()
+}
+
+fn arr(v: &[f64]) -> Object {
+ Object::Array(v.iter().map(|x| Object::Real(*x)).collect())
+}
+
+// ── export ──────────────────────────────────────────────────────────────────────────────────
+
+/// Every comment as an XFDF element (one line per comment, replies included).
+fn xfdf_annots(doc: &Document, out: &mut String) {
+ let pages = printcraft_model::pages(doc);
+ // NM of every annotation, for inreplyto.
+ let mut names: HashMap<ObjRef, String> = HashMap::new();
+ for p in &pages {
+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {
+ if let Some(r) = a.as_ref()
+ && let Some(nm) = doc.get(r).as_dict().and_then(|d| text_of(doc, d, b"NM"))
+ {
+ names.insert(r, nm);
+ }
+ }
+ }
+ for (pi, p) in pages.iter().enumerate() {
+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {
+ let Some(d) = doc.resolve(&a).as_dict().cloned() else { continue };
+ let Some(sub) = d.name(b"Subtype") else { continue };
+ let Some((_, tag)) = SUBTYPES.iter().find(|(s, _)| s.as_bytes() == sub) else { continue };
+ let mut attrs = format!(" page=\"{pi}\"");
+ let rect = nums_of(doc, d.get(b"Rect"));
+ if rect.len() == 4 {
+ let _ = write!(
+ attrs,
+ " rect=\"{},{},{},{}\"",
+ n(rect[0].min(rect[2])),
+ n(rect[1].min(rect[3])),
+ n(rect[0].max(rect[2])),
+ n(rect[1].max(rect[3]))
+ );
+ }
+ for (key, attr) in [
+ (&b"NM"[..], "name"),
+ (b"T", "title"),
+ (b"Subj", "subject"),
+ (b"M", "date"),
+ (b"CreationDate", "creationdate"),
+ (b"RT", "replyType"),
+ (b"State", "state"),
+ (b"StateModel", "statemodel"),
+ (b"Name", "icon"),
+ ] {
+ if let Some(v) = text_of(doc, &d, key) {
+ let _ = write!(attrs, " {attr}=\"{}\"", esc(&v));
+ }
+ }
+ let flags = d.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);
+ let fl: Vec<&str> = FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect();
+ if !fl.is_empty() {
+ let _ = write!(attrs, " flags=\"{}\"", fl.join(","));
+ }
+ if let Some(c) = hex(&nums_of(doc, d.get(b"C"))) {
+ let _ = write!(attrs, " color=\"{c}\"");
+ }
+ if let Some(c) = hex(&nums_of(doc, d.get(b"IC"))) {
+ let _ = write!(attrs, " interior-color=\"{c}\"");
+ }
+ if let Some(o) = d.get(b"CA").and_then(|o| doc.resolve(o).as_f64()) {
+ let _ = write!(attrs, " opacity=\"{}\"", n(o));
+ }
+ if let Some(w) = d.get(b"BS").and_then(|b| doc.resolve(b).as_dict().and_then(|b| b.get(b"W").and_then(Object::as_f64))) {
+ let _ = write!(attrs, " width=\"{}\"", n(w));
+ }
+ let quads = nums_of(doc, d.get(b"QuadPoints"));
+ if !quads.is_empty() {
+ let _ = write!(attrs, " coords=\"{}\"", quads.iter().map(|v| n(*v)).collect::<Vec<_>>().join(","));
+ }
+ let l = nums_of(doc, d.get(b"L"));
+ if l.len() == 4 {
+ let _ = write!(attrs, " start=\"{},{}\" end=\"{},{}\"", n(l[0]), n(l[1]), n(l[2]), n(l[3]));
+ }
+ if let Some(le) = d.get(b"LE").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned())
+ && le.len() == 2
+ {
+ let name = |o: &Object| o.as_name().map(|x| String::from_utf8_lossy(x).into_owned()).unwrap_or_else(|| "None".into());
+ let _ = write!(attrs, " head=\"{}\" tail=\"{}\"", name(&le[0]), name(&le[1]));
+ }
+ if let Some(irt) = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| names.get(&r)) {
+ let _ = write!(attrs, " inreplyto=\"{}\"", esc(irt));
+ }
+ let _ = write!(out, "<{tag}{attrs}>");
+ if let Some(c) = text_of(doc, &d, b"Contents") {
+ let _ = write!(out, "<contents>{}</contents>", esc(&c));
+ }
+ if let Some(da) = text_of(doc, &d, b"DA") {
+ let _ = write!(out, "<defaultappearance>{}</defaultappearance>", esc(&da));
+ }
+ let ink = d.get(b"InkList").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ if !ink.is_empty() {
+ out.push_str("<inklist>");
+ for g in ink {
+ let v = nums_of(doc, Some(&g));
+ let pts: Vec<String> = v.chunks_exact(2).map(|p| format!("{},{}", n(p[0]), n(p[1]))).collect();
+ let _ = write!(out, "<gesture>{}</gesture>", pts.join(";"));
+ }
+ out.push_str("</inklist>");
+ }
+ if let Some(pd) = d.get(b"Popup").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()) {
+ let r = nums_of(doc, pd.get(b"Rect"));
+ if r.len() == 4 {
+ let open = matches!(pd.get(b"Open"), Some(Object::Bool(true)));
+ let _ = write!(
+ out,
+ "<popup page=\"{pi}\" rect=\"{},{},{},{}\" open=\"{}\"/>",
+ n(r[0]),
+ n(r[1]),
+ n(r[2]),
+ n(r[3]),
+ if open { "yes" } else { "no" }
+ );
+ }
+ }
+ let _ = writeln!(out, "</{tag}>");
+ }
+ }
+}
+
+/// Field values as nested XFDF `<field>` elements.
+fn xfdf_fields(doc: &Document, out: &mut String) {
+ #[derive(Default)]
+ struct Node {
+ values: Vec<String>,
+ kids: Vec<(String, Node)>,
+ }
+ let mut root = Node::default();
+ for f in printcraft_forms::fields(doc) {
+ if matches!(f.kind, FieldKind::PushButton | FieldKind::Signature) {
+ continue;
+ }
+ let mut node = &mut root;
+ for part in f.name.split('.') {
+ let i = match node.kids.iter().position(|(k, _)| k == part) {
+ Some(i) => i,
+ None => {
+ node.kids.push((part.to_string(), Node::default()));
+ node.kids.len() - 1
+ }
+ };
+ node = &mut node.kids[i].1;
+ }
+ node.values = match f.kind {
+ FieldKind::CheckBox | FieldKind::Radio if f.value.is_empty() => vec!["Off".into()],
+ _ => f.value.clone(),
+ };
+ }
+ fn write_node(name: &str, node: &Node, out: &mut String) {
+ let _ = write!(out, "<field name=\"{}\">", esc(name));
+ for v in &node.values {
+ let _ = write!(out, "<value>{}</value>", esc(v));
+ }
+ for (k, kid) in &node.kids {
+ write_node(k, kid, out);
+ }
+ out.push_str("</field>\n");
+ }
+ for (k, kid) in &root.kids {
+ write_node(k, kid, out);
+ }
+}
+
+/// XFDF with the document's comments and/or field values.
+pub fn export_xfdf(doc: &Document, comments: bool, fields: bool, file: &str) -> String {
+ let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\">\n");
+ if comments {
+ out.push_str("<annots>\n");
+ xfdf_annots(doc, &mut out);
+ out.push_str("</annots>\n");
+ }
+ if fields {
+ out.push_str("<fields>\n");
+ xfdf_fields(doc, &mut out);
+ out.push_str("</fields>\n");
+ }
+ let _ = writeln!(out, "<f href=\"{}\"/>", esc(file));
+ out.push_str("</xfdf>\n");
+ out
+}
+
+fn pdf_string(s: &str) -> Vec<u8> {
+ let mut v = Vec::new();
+ printcraft_cos::serialize(&Object::String(PdfString::text(s)), &mut v);
+ v
+}
+
+/// FDF with field values and/or comments (direct objects only; appearances are not carried).
+pub fn export_fdf(doc: &Document, comments: bool, fields: bool, file: &str) -> Vec<u8> {
+ let mut body: Vec<u8> = b"<< /FDF << ".to_vec();
+ if fields {
+ body.extend_from_slice(b"/Fields [");
+ for f in printcraft_forms::fields(doc) {
+ if matches!(f.kind, FieldKind::PushButton | FieldKind::Signature) {
+ continue;
+ }
+ body.extend_from_slice(b"<< /T ");
+ body.extend(pdf_string(&f.name));
+ body.extend_from_slice(b" /V ");
+ match f.kind {
+ FieldKind::CheckBox | FieldKind::Radio => {
+ let v = f.value.first().cloned().unwrap_or_else(|| "Off".into());
+ printcraft_cos::serialize(&Object::Name(v.into_bytes()), &mut body);
+ }
+ FieldKind::List if f.value.len() > 1 => {
+ printcraft_cos::serialize(&Object::Array(f.value.iter().map(|v| Object::String(PdfString::text(v))).collect()), &mut body);
+ }
+ _ => body.extend(pdf_string(f.value.first().map(String::as_str).unwrap_or(""))),
+ }
+ body.extend_from_slice(b" >> ");
+ }
+ body.extend_from_slice(b"] ");
+ }
+ if comments {
+ body.extend_from_slice(b"/Annots [");
+ for (pi, p) in printcraft_model::pages(doc).iter().enumerate() {
+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {
+ let Some(mut d) = doc.resolve(&a).as_dict().cloned() else { continue };
+ let Some(sub) = d.name(b"Subtype") else { continue };
+ if !SUBTYPES.iter().any(|(s, _)| s.as_bytes() == sub) {
+ continue;
+ }
+ // Only direct values travel: references into this file would dangle.
+ for k in [&b"P"[..], b"AP", b"Popup", b"IRT", b"Parent", b"FS", b"Sound"] {
+ d.remove(k);
+ }
+ let keys: Vec<Vec<u8>> = d.iter().filter(|(_, v)| matches!(v, Object::Ref(_))).map(|(k, _)| k.clone()).collect();
+ for k in keys {
+ let v = (*doc.resolve(d.get(&k).expect("listed"))).clone();
+ if matches!(v, Object::Stream(_)) {
+ d.remove(&k);
+ } else {
+ d.set(k, v);
+ }
+ }
+ d.set(b"Page".to_vec(), Object::Int(pi as i64));
+ printcraft_cos::serialize(&Object::Dict(d), &mut body);
+ body.push(b' ');
+ }
+ }
+ body.extend_from_slice(b"] ");
+ }
+ body.extend_from_slice(b"/F ");
+ body.extend(pdf_string(file));
+ body.extend_from_slice(b" >> >>");
+ let mut out = b"%FDF-1.2\n%\xE2\xE3\xCF\xD3\n1 0 obj\n".to_vec();
+ out.extend(body);
+ out.extend_from_slice(b"\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n");
+ out
+}
+
+/// The XML element name for a field name (letters, digits, `_`, `-`, `.`).
+fn xml_name(name: &str) -> String {
+ let mut s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '_' | '-' | '.') { c } else { '_' }).collect();
+ if !s.chars().next().is_some_and(|c| c.is_alphabetic() || c == '_') {
+ s.insert(0, '_');
+ }
+ s
+}
+
+/// Form data as XML, CSV or tab-delimited text (Acrobat's Export data formats).
+pub fn export_data(doc: &Document, format: Format) -> String {
+ let fields: Vec<(String, String)> = printcraft_forms::fields(doc)
+ .into_iter()
+ .filter(|f| !matches!(f.kind, FieldKind::PushButton | FieldKind::Signature))
+ .map(|f| {
+ let v = match f.kind {
+ FieldKind::CheckBox | FieldKind::Radio if f.value.is_empty() => "Off".to_string(),
+ _ => f.value.join(", "),
+ };
+ (f.name, v)
+ })
+ .collect();
+ match format {
+ Format::Xml => {
+ let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<fields xmlns:xfdf=\"http://ns.adobe.com/xfdf-transition/\">\n");
+ for (k, v) in &fields {
+ let tag = xml_name(k);
+ let orig = if tag == *k { String::new() } else { format!(" xfdf:original=\"{}\"", esc(k)) };
+ let _ = writeln!(out, "<{tag}{orig}>{}</{tag}>", esc(v));
+ }
+ out.push_str("</fields>\n");
+ out
+ }
+ Format::Csv => {
+ let q = |s: &str| if s.contains([',', '"', '\n']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() };
+ format!(
+ "{}\n{}\n",
+ fields.iter().map(|f| q(&f.0)).collect::<Vec<_>>().join(","),
+ fields.iter().map(|f| q(&f.1)).collect::<Vec<_>>().join(",")
+ )
+ }
+ _ => {
+ let clean = |s: &str| s.replace(['\t', '\n', '\r'], " ");
+ format!(
+ "{}\n{}\n",
+ fields.iter().map(|f| clean(&f.0)).collect::<Vec<_>>().join("\t"),
+ fields.iter().map(|f| clean(&f.1)).collect::<Vec<_>>().join("\t")
+ )
+ }
+ }
+}
+
+// ── import ──────────────────────────────────────────────────────────────────────────────────
+
+/// Set the values of fields named in `values` (full names), counting what took.
+fn apply_values(doc: &mut Document, values: &[(String, Vec<String>)], report: &mut Report) {
+ let all = printcraft_forms::fields(doc);
+ for (name, vals) in values {
+ let Some(f) = all.iter().find(|f| &f.name == name) else { continue };
+ let first = vals.first().cloned().unwrap_or_default();
+ let v = match f.kind {
+ FieldKind::Text => FieldValue::Text(first),
+ FieldKind::CheckBox => FieldValue::Check(!first.is_empty() && first != "Off"),
+ FieldKind::Radio => FieldValue::Radio((!first.is_empty() && first != "Off").then_some(first)),
+ FieldKind::Combo | FieldKind::List => FieldValue::Choice(vals.iter().filter(|v| !v.is_empty()).cloned().collect()),
+ FieldKind::PushButton | FieldKind::Signature => continue,
+ };
+ // Read-only fields still take imported data, as in Acrobat.
+ let ro = f.read_only();
+ if ro {
+ let _ = doc.update_dict(f.obj, |d| d.set(b"Ff".to_vec(), Object::Int((f.flags & !printcraft_forms::flags::READ_ONLY) as i64)));
+ }
+ match printcraft_forms::set_value(doc, name, &v) {
+ Ok(()) => report.fields += 1,
+ Err(_) => report.rejected.push(name.clone()),
+ }
+ if ro {
+ let _ = doc.update_dict(f.obj, |d| d.set(b"Ff".to_vec(), Object::Int(f.flags as i64)));
+ }
+ }
+}
+
+/// A new annotation dictionary from an XFDF element.
+fn annot_from_xml(node: roxmltree::Node, subtype: &str, page_ref: ObjRef) -> Option<Dict> {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name(subtype));
+ d.set(b"P".to_vec(), Object::Ref(page_ref));
+ let rect = csv(node.attribute("rect")?);
+ if rect.len() != 4 {
+ return None;
+ }
+ d.set(b"Rect".to_vec(), arr(&rect));
+ for (attr, key) in [
+ ("name", &b"NM"[..]),
+ ("title", b"T"),
+ ("subject", b"Subj"),
+ ("date", b"M"),
+ ("creationdate", b"CreationDate"),
+ ("state", b"State"),
+ ("statemodel", b"StateModel"),
+ ] {
+ if let Some(v) = node.attribute(attr) {
+ d.set(key.to_vec(), PdfString::text(v));
+ }
+ }
+ if let Some(v) = node.attribute("replyType") {
+ d.set(b"RT".to_vec(), Object::name(if v.eq_ignore_ascii_case("group") { "Group" } else { "R" }));
+ }
+ if let Some(v) = node.attribute("icon") {
+ d.set(b"Name".to_vec(), Object::name(v));
+ }
+ let flags: i64 = node
+ .attribute("flags")
+ .unwrap_or("print")
+ .split(',')
+ .filter_map(|f| FLAGS.iter().find(|(_, s)| s.eq_ignore_ascii_case(f.trim())).map(|x| x.0))
+ .sum();
+ d.set(b"F".to_vec(), Object::Int(flags));
+ if let Some(c) = node.attribute("color").and_then(parse_hex) {
+ d.set(b"C".to_vec(), arr(&c));
+ }
+ if let Some(c) = node.attribute("interior-color").and_then(parse_hex) {
+ d.set(b"IC".to_vec(), arr(&c));
+ }
+ if let Some(o) = node.attribute("opacity").and_then(|o| o.parse::<f64>().ok()) {
+ d.set(b"CA".to_vec(), Object::Real(o.clamp(0.0, 1.0)));
+ }
+ if let Some(w) = node.attribute("width").and_then(|w| w.parse::<f64>().ok()) {
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Real(w.max(0.0)));
+ bs.set(b"S".to_vec(), Object::name("S"));
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ }
+ if let Some(q) = node.attribute("coords") {
+ d.set(b"QuadPoints".to_vec(), arr(&csv(q)));
+ }
+ if let (Some(s), Some(e)) = (node.attribute("start"), node.attribute("end")) {
+ let (s, e) = (csv(s), csv(e));
+ if s.len() == 2 && e.len() == 2 {
+ d.set(b"L".to_vec(), arr(&[s[0], s[1], e[0], e[1]]));
+ }
+ }
+ if node.attribute("head").is_some() || node.attribute("tail").is_some() {
+ d.set(
+ b"LE".to_vec(),
+ Object::Array(vec![Object::name(node.attribute("head").unwrap_or("None")), Object::name(node.attribute("tail").unwrap_or("None"))]),
+ );
+ }
+ for child in node.children().filter(|c| c.is_element()) {
+ match child.tag_name().name() {
+ "contents" => {
+ d.set(b"Contents".to_vec(), PdfString::text(&child.text().unwrap_or("").replace("\r\n", "\r").replace('\n', "\r")));
+ }
+ "defaultappearance" => {
+ d.set(b"DA".to_vec(), PdfString::literal(child.text().unwrap_or("").as_bytes().to_vec()));
+ }
+ "inklist" => {
+ let list: Vec<Object> = child
+ .children()
+ .filter(|g| g.has_tag_name("gesture"))
+ .map(|g| arr(&g.text().unwrap_or("").split(';').flat_map(|p| csv(p).into_iter()).collect::<Vec<_>>()))
+ .collect();
+ d.set(b"InkList".to_vec(), Object::Array(list));
+ }
+ _ => {}
+ }
+ }
+ Some(d)
+}
+
+/// Put an annotation dictionary on a page, replacing one with the same `/NM`. Returns its
+/// reference.
+fn place(doc: &mut Document, page_ref: ObjRef, d: Dict) -> Result<ObjRef, DataError> {
+ let nm = d.get(b"NM").and_then(|n| n.as_string().map(|s| s.to_text()));
+ let annots: Vec<Object> = doc
+ .get(page_ref)
+ .as_dict()
+ .and_then(|p| p.get(b"Annots").cloned())
+ .map(|a| doc.resolve(&a))
+ .and_then(|a| a.as_array().cloned())
+ .unwrap_or_default();
+ let mut kept = Vec::new();
+ for a in annots {
+ let same = nm.is_some()
+ && a.as_ref().and_then(|r| doc.get(r).as_dict().and_then(|x| x.get(b"NM").and_then(|n| n.as_string().map(|s| s.to_text())))) == nm;
+ if !same {
+ kept.push(a);
+ }
+ }
+ let r = doc.add(Object::Dict(d));
+ // Our own appearance where we can draw one; others keep none (viewers draw a default).
+ let _ = printcraft_annot::set_appearance(doc, r);
+ kept.push(Object::Ref(r));
+ doc.update_dict(page_ref, |p| p.set(b"Annots".to_vec(), Object::Array(kept)))?;
+ Ok(r)
+}
+
+fn import_xfdf(doc: &mut Document, text: &str) -> Result<Report, DataError> {
+ let xml = roxmltree::Document::parse(text).map_err(|e| DataError::Malformed(e.to_string()))?;
+ let root = xml.root_element();
+ if root.tag_name().name() != "xfdf" {
+ return Err(DataError::UnknownFormat);
+ }
+ let mut report = Report::default();
+ let pages: Vec<ObjRef> = printcraft_model::pages(doc).iter().map(|p| p.obj).collect();
+ // Comments: parents first, then replies (whose /IRT needs the parent's reference).
+ let mut by_name: HashMap<String, ObjRef> = HashMap::new();
+ let mut later: Vec<(ObjRef, String)> = Vec::new();
+ if let Some(annots) = root.children().find(|c| c.has_tag_name("annots")) {
+ for node in annots.children().filter(|c| c.is_element()) {
+ let tag = node.tag_name().name().to_ascii_lowercase();
+ let Some((subtype, _)) = SUBTYPES.iter().find(|(_, t)| *t == tag) else { continue };
+ let Some(page) = node.attribute("page").and_then(|p| p.parse::<usize>().ok()).and_then(|p| pages.get(p).copied()) else { continue };
+ let Some(d) = annot_from_xml(node, subtype, page) else { continue };
+ let r = place(doc, page, d)?;
+ if let Some(nm) = node.attribute("name") {
+ by_name.insert(nm.to_string(), r);
+ }
+ if let Some(irt) = node.attribute("inreplyto") {
+ later.push((r, irt.to_string()));
+ }
+ // A pop-up window.
+ if let Some(pop) = node.children().find(|c| c.has_tag_name("popup"))
+ && let Some(rect) = pop.attribute("rect").map(csv).filter(|r| r.len() == 4)
+ {
+ let mut p = Dict::new();
+ p.set(b"Type".to_vec(), Object::name("Annot"));
+ p.set(b"Subtype".to_vec(), Object::name("Popup"));
+ p.set(b"Rect".to_vec(), arr(&rect));
+ p.set(b"Parent".to_vec(), Object::Ref(r));
+ p.set(b"Open".to_vec(), Object::Bool(pop.attribute("open") == Some("yes")));
+ let pr = doc.add(Object::Dict(p));
+ doc.update_dict(r, |d| d.set(b"Popup".to_vec(), Object::Ref(pr)))?;
+ doc.update_dict(page, |pd| {
+ if let Some(Object::Array(a)) = pd.get_mut(b"Annots") {
+ a.push(Object::Ref(pr));
+ }
+ })?;
+ }
+ report.comments += 1;
+ }
+ }
+ for (r, irt) in later {
+ if let Some(parent) = by_name.get(&irt).copied().or_else(|| find_by_name(doc, &irt)) {
+ doc.update_dict(r, |d| d.set(b"IRT".to_vec(), Object::Ref(parent)))?;
+ }
+ }
+ // Fields.
+ if let Some(fields) = root.children().find(|c| c.has_tag_name("fields")) {
+ let mut values = Vec::new();
+ fn walk(node: roxmltree::Node, prefix: &str, out: &mut Vec<(String, Vec<String>)>) {
+ for f in node.children().filter(|c| c.has_tag_name("field")) {
+ let Some(name) = f.attribute("name") else { continue };
+ let full = if prefix.is_empty() { name.to_string() } else { format!("{prefix}.{name}") };
+ let vals: Vec<String> = f.children().filter(|c| c.has_tag_name("value")).map(|v| v.text().unwrap_or("").to_string()).collect();
+ if !vals.is_empty() {
+ out.push((full.clone(), vals));
+ }
+ walk(f, &full, out);
+ }
+ }
+ walk(fields, "", &mut values);
+ apply_values(doc, &values, &mut report);
+ }
+ Ok(report)
+}
+
+fn find_by_name(doc: &Document, nm: &str) -> Option<ObjRef> {
+ for p in printcraft_model::pages(doc) {
+ for a in p.dict.get(b"Annots").map(|a| doc.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {
+ if let Some(r) = a.as_ref()
+ && doc.get(r).as_dict().and_then(|d| text_of(doc, d, b"NM")).as_deref() == Some(nm)
+ {
+ return Some(r);
+ }
+ }
+ }
+ None
+}
+
+/// Copy an object out of another document, resolving references (FDF objects are small).
+fn deep(src: &Document, o: &Object, depth: usize) -> Object {
+ if depth > 16 {
+ return Object::Null;
+ }
+ match o {
+ Object::Ref(r) => deep(src, &src.get(*r), depth + 1),
+ Object::Array(a) => Object::Array(a.iter().map(|x| deep(src, x, depth + 1)).collect()),
+ Object::Dict(d) => Object::Dict(d.iter().map(|(k, v)| (k.clone(), deep(src, v, depth + 1))).collect()),
+ Object::Stream(_) => Object::Null,
+ other => other.clone(),
+ }
+}
+
+fn import_fdf(doc: &mut Document, bytes: &[u8]) -> Result<Report, DataError> {
+ let fdf = Document::open(std::sync::Arc::new(bytes.to_vec())).map_err(|e| DataError::Malformed(e.to_string()))?;
+ let root = fdf.root().ok_or_else(|| DataError::Malformed("no /Root".into()))?;
+ let body = fdf
+ .get(root)
+ .as_dict()
+ .and_then(|d| d.get(b"FDF").cloned())
+ .map(|f| fdf.resolve(&f))
+ .and_then(|f| f.as_dict().cloned())
+ .ok_or(DataError::UnknownFormat)?;
+ let mut report = Report::default();
+ // Fields (with /Kids for hierarchical names).
+ let mut values = Vec::new();
+ fn walk(fdf: &Document, list: &[Object], prefix: &str, out: &mut Vec<(String, Vec<String>)>, depth: usize) {
+ if depth > 32 {
+ return;
+ }
+ for f in list {
+ let Some(d) = fdf.resolve(f).as_dict().cloned() else { continue };
+ let Some(t) = d.get(b"T").and_then(|t| fdf.resolve(t).as_string().map(|s| s.to_text())) else { continue };
+ let full = if prefix.is_empty() { t } else { format!("{prefix}.{t}") };
+ if let Some(v) = d.get(b"V").map(|v| fdf.resolve(v)) {
+ let vals: Vec<String> = match &*v {
+ Object::String(s) => vec![s.to_text()],
+ Object::Name(n) => vec![String::from_utf8_lossy(n).into_owned()],
+ Object::Array(a) => a.iter().filter_map(|x| fdf.resolve(x).as_string().map(|s| s.to_text())).collect(),
+ _ => Vec::new(),
+ };
+ out.push((full.clone(), vals));
+ }
+ if let Some(kids) = d.get(b"Kids").map(|k| fdf.resolve(k)).and_then(|k| k.as_array().cloned()) {
+ walk(fdf, &kids, &full, out, depth + 1);
+ }
+ }
+ }
+ if let Some(list) = body.get(b"Fields").map(|f| fdf.resolve(f)).and_then(|f| f.as_array().cloned()) {
+ walk(&fdf, &list, "", &mut values, 0);
+ }
+ // Comments.
+ let pages: Vec<ObjRef> = printcraft_model::pages(doc).iter().map(|p| p.obj).collect();
+ for a in body.get(b"Annots").map(|a| fdf.resolve(a)).and_then(|a| a.as_array().cloned()).unwrap_or_default() {
+ let Object::Dict(mut d) = deep(&fdf, &a, 0) else { continue };
+ let Some(page) = d.get(b"Page").and_then(Object::as_int).and_then(|p| usize::try_from(p).ok()).and_then(|p| pages.get(p).copied()) else {
+ continue;
+ };
+ if !d.name(b"Subtype").is_some_and(|s| SUBTYPES.iter().any(|(x, _)| x.as_bytes() == s)) {
+ continue;
+ }
+ d.remove(b"Page");
+ d.set(b"P".to_vec(), Object::Ref(page));
+ place(doc, page, d)?;
+ report.comments += 1;
+ }
+ apply_values(doc, &values, &mut report);
+ Ok(report)
+}
+
+/// Form data from XML, CSV or tab-delimited text.
+fn import_table(doc: &mut Document, text: &str) -> Result<Report, DataError> {
+ let mut report = Report::default();
+ let t = text.trim_start_matches('\u{feff}');
+ let values: Vec<(String, Vec<String>)> = if t.trim_start().starts_with('<') {
+ let xml = roxmltree::Document::parse(t).map_err(|e| DataError::Malformed(e.to_string()))?;
+ xml.root_element()
+ .children()
+ .filter(|c| c.is_element())
+ .map(|c| {
+ let name =
+ c.attributes().find(|a| a.name() == "original").map(|a| a.value().to_string()).unwrap_or_else(|| c.tag_name().name().to_string());
+ (name, vec![c.text().unwrap_or("").to_string()])
+ })
+ .collect()
+ } else {
+ let mut lines = t.lines();
+ let (Some(head), Some(row)) = (lines.next(), lines.next()) else { return Err(DataError::UnknownFormat) };
+ let split = |l: &str| -> Vec<String> {
+ if l.contains('\t') {
+ l.split('\t').map(str::to_string).collect()
+ } else {
+ // CSV with quotes.
+ let mut out = Vec::new();
+ let mut cur = String::new();
+ let mut quoted = false;
+ let mut chars = l.chars().peekable();
+ while let Some(c) = chars.next() {
+ match c {
+ '"' if quoted && chars.peek() == Some(&'"') => {
+ cur.push('"');
+ chars.next();
+ }
+ '"' => quoted = !quoted,
+ ',' if !quoted => out.push(std::mem::take(&mut cur)),
+ c => cur.push(c),
+ }
+ }
+ out.push(cur);
+ out
+ }
+ };
+ split(head).into_iter().zip(split(row)).map(|(k, v)| (k, vec![v])).collect()
+ };
+ apply_values(doc, &values, &mut report);
+ Ok(report)
+}
+
+/// Import comments and/or field values from XFDF, FDF, XML, CSV or tab-delimited text
+/// (detected from the content).
+pub fn import(doc: &mut Document, bytes: &[u8]) -> Result<Report, DataError> {
+ let report = if bytes.starts_with(b"%FDF") {
+ import_fdf(doc, bytes)?
+ } else {
+ let text = String::from_utf8_lossy(bytes);
+ let t = text.trim_start_matches('\u{feff}').trim_start();
+ if t.starts_with("<?xml") || t.starts_with("<xfdf") || t.starts_with('<') {
+ match import_xfdf(doc, t) {
+ Err(DataError::UnknownFormat) => import_table(doc, t)?,
+ other => other?,
+ }
+ } else {
+ import_table(doc, &text)?
+ }
+ };
+ if report.comments == 0 && report.fields == 0 && report.rejected.is_empty() {
+ return Err(DataError::NothingImported);
+ }
+ Ok(report)
+}
diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs
new file mode 100644
index 000000000..5223459c5
--- /dev/null
+++ b/crates/xfdf/src/tests.rs
@@ -0,0 +1,162 @@
+use std::sync::Arc;
+
+use printcraft_annot::{Markup, Meta, NewAnnotation, Shape, Style, add_annotation, add_reply, summaries};
+use printcraft_cos::{SaveOptions, write_full};
+use printcraft_forms::{NewField, add_field, fields, set_value};
+
+use super::*;
+
+/// Two blank pages with three fields (text, check box, list).
+fn blank() -> Document {
+ let mut doc = Document::new_empty();
+ let pages = doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap();
+ let mut kids = Vec::new();
+ for _ in 0..2 {
+ let mut p = Dict::new();
+ p.set(b"Type".to_vec(), Object::name("Page"));
+ p.set(b"Parent".to_vec(), Object::Ref(pages));
+ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 600.into(), 800.into()]));
+ kids.push(Object::Ref(doc.add(p)));
+ }
+ doc.update_dict(pages, |d| {
+ d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));
+ d.set(b"Kids".to_vec(), Object::Array(kids));
+ })
+ .unwrap();
+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &NewField::Text { multiline: false }, Some("Name")).unwrap();
+ add_field(&mut doc, 0, [50.0, 650.0, 64.0, 664.0], &NewField::CheckBox, Some("Agree")).unwrap();
+ add_field(
+ &mut doc,
+ 1,
+ [50.0, 600.0, 250.0, 660.0],
+ &NewField::List { options: vec!["A".into(), "B".into(), "C".into()], multi: true },
+ Some("Pick"),
+ )
+ .unwrap();
+ Document::open(Arc::new(write_full(&doc, &SaveOptions::default()).unwrap())).unwrap()
+}
+
+/// The blank document with comments and values.
+fn filled() -> Document {
+ let mut doc = blank();
+ let meta = |id: &str| Meta { date: Some("D:20261002120000Z".into()), id: id.into() };
+ let note = Shape::Note { at: [100.0, 500.0], icon: printcraft_annot::NoteIcon::Comment };
+ add_annotation(
+ &mut doc,
+ &NewAnnotation {
+ page: 0,
+ style: Style::default_for(&note),
+ shape: note,
+ contents: "Check this <now> & \"later\"".into(),
+ author: "Ada".into(),
+ },
+ &meta("n1"),
+ )
+ .unwrap();
+ let hl = Shape::TextMarkup { kind: Markup::Highlight, quads: vec![[10.0, 110.0, 90.0, 110.0, 10.0, 100.0, 90.0, 100.0]] };
+ add_annotation(
+ &mut doc,
+ &NewAnnotation { page: 1, style: Style::default_for(&hl), shape: hl, contents: String::new(), author: "Bob".into() },
+ &meta("h1"),
+ )
+ .unwrap();
+ let ink = Shape::Ink { strokes: vec![vec![[10.0, 10.0], [20.0, 30.0], [40.0, 20.0]]] };
+ add_annotation(
+ &mut doc,
+ &NewAnnotation { page: 1, style: Style::default_for(&ink), shape: ink, contents: "scribble".into(), author: "Bob".into() },
+ &meta("i1"),
+ )
+ .unwrap();
+ let note_index = summaries(&doc).iter().find(|s| s.subtype == "Text").map(|s| s.index).unwrap();
+ add_reply(&mut doc, 0, note_index, "Agreed", "Bob", &meta("r1")).unwrap();
+ set_value(&mut doc, "Name", &FieldValue::Text("Ada Lovelace".into())).unwrap();
+ set_value(&mut doc, "Agree", &FieldValue::Check(true)).unwrap();
+ set_value(&mut doc, "Pick", &FieldValue::Choice(vec!["A".into(), "C".into()])).unwrap();
+ doc
+}
+
+fn comment_view(doc: &Document) -> Vec<String> {
+ summaries(doc)
+ .iter()
+ .map(|s| {
+ format!(
+ "{} p{} {:?} by {:?}: {:?} reply_to={:?}",
+ s.subtype,
+ s.page,
+ s.rect.map(|v| v.round()),
+ s.author,
+ s.contents,
+ s.in_reply_to.is_some()
+ )
+ })
+ .collect()
+}
+
+fn values(doc: &Document) -> Vec<(String, Vec<String>)> {
+ fields(doc).into_iter().map(|f| (f.name, f.value)).collect()
+}
+
+#[test]
+fn xfdf_round_trips_comments_and_values() {
+ let src = filled();
+ let xfdf = export_xfdf(&src, true, true, "form.pdf");
+ assert!(xfdf.contains("<text page=\"0\"") && xfdf.contains("&lt;now&gt; &amp; &quot;later&quot;"), "{xfdf}");
+ assert!(xfdf.contains("<highlight page=\"1\"") && xfdf.contains("coords=\"10,110,90,110,10,100,90,100\""));
+ assert!(xfdf.contains("<gesture>10,10;20,30;40,20</gesture>"));
+ assert!(xfdf.contains("inreplyto=\""), "replies keep their thread");
+ assert!(xfdf.contains("<field name=\"Pick\"><value>A</value><value>C</value></field>"));
+ let mut dst = blank();
+ let r = import(&mut dst, xfdf.as_bytes()).unwrap();
+ assert_eq!((r.comments, r.fields), (4, 3), "{r:?}");
+ assert_eq!(comment_view(&dst), comment_view(&src));
+ assert_eq!(values(&dst), values(&src));
+ // Importing again replaces (same names) instead of duplicating.
+ import(&mut dst, xfdf.as_bytes()).unwrap();
+ assert_eq!(summaries(&dst).len(), summaries(&src).len());
+ // Comments only.
+ let only = export_xfdf(&src, true, false, "form.pdf");
+ assert!(!only.contains("<fields>"));
+}
+
+#[test]
+fn fdf_round_trips_values_and_comments() {
+ let src = filled();
+ let fdf = export_fdf(&src, true, true, "form.pdf");
+ assert!(fdf.starts_with(b"%FDF-1.2"));
+ let mut dst = blank();
+ let r = import(&mut dst, &fdf).unwrap();
+ assert_eq!(r.fields, 3);
+ assert_eq!(values(&dst), values(&src));
+ assert!(r.comments >= 3, "{r:?}");
+ assert!(summaries(&dst).iter().any(|s| s.contents.as_deref() == Some("scribble")));
+}
+
+#[test]
+fn form_data_as_xml_csv_and_text() {
+ let src = filled();
+ let xml = export_data(&src, Format::Xml);
+ assert!(xml.contains("<Name>Ada Lovelace</Name>") && xml.contains("<Agree>Yes</Agree>"), "{xml}");
+ let txt = export_data(&src, Format::Txt);
+ assert_eq!(txt, "Name\tAgree\tPick\nAda Lovelace\tYes\tA, C\n");
+ let csv_text = export_data(&src, Format::Csv);
+ assert_eq!(csv_text, "Name,Agree,Pick\nAda Lovelace,Yes,\"A, C\"\n");
+ for data in [xml, txt] {
+ let mut dst = blank();
+ let r = import(&mut dst, data.as_bytes()).unwrap();
+ assert!(r.fields >= 2, "{r:?}");
+ assert_eq!(values(&dst)[0].1, ["Ada Lovelace"]);
+ assert_eq!(values(&dst)[1].1, ["Yes"]);
+ }
+ let mut dst = blank();
+ import(&mut dst, b"Name,Agree\n\"Lovelace, Ada\",Off\n").unwrap();
+ assert_eq!(values(&dst)[0].1, ["Lovelace, Ada"]);
+}
+
+#[test]
+fn bad_data_is_refused_with_a_reason() {
+ let mut dst = blank();
+ assert!(matches!(import(&mut dst, b"<xfdf><annots>"), Err(DataError::Malformed(_))));
+ assert_eq!(import(&mut dst, b"Unknown\nvalue\n"), Err(DataError::NothingImported));
+ assert_eq!(Format::from_extension("XFDF"), Some(Format::Xfdf));
+ assert_eq!(Format::from_extension("docx"), None);
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 91154b020..f5189e975 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -4031,11 +4031,11 @@ title = "Import comments from FDF/XFDF"
area = "E"
tier = "P1"
milestone = "M5"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["comment.import"]
+tools = ["doc_import_data"]
+evidence = ["crates/xfdf/src/tests.rs::xfdf_round_trips_comments_and_values", "crates/xfdf/src/tests.rs::fdf_round_trips_values_and_comments", "crates/automation/tests/automation.rs::comments_and_form_data_travel_as_xfdf_fdf_and_text"]
+notes = "replies, pop-ups, ink, quads, line ends; same /NM replaces"
[[feature]]
id = "comment.export-fdf-xfdf"
@@ -4043,10 +4043,10 @@ title = "Export all comments to FDF/XFDF"
area = "E"
tier = "P1"
milestone = "M5"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["comment.export"]
+tools = ["doc_export_data"]
+evidence = ["crates/xfdf/src/tests.rs::xfdf_round_trips_comments_and_values", "crates/xfdf/src/tests.rs::fdf_round_trips_values_and_comments", "crates/automation/tests/automation.rs::comments_and_form_data_travel_as_xfdf_fdf_and_text"]
notes = ""
[[feature]]
@@ -4563,11 +4563,11 @@ title = "Import form data (FDF, XFDF)"
area = "F"
tier = "P1"
milestone = "M6"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["form.import_data"]
+tools = ["doc_import_data"]
+evidence = ["crates/xfdf/src/tests.rs::xfdf_round_trips_comments_and_values", "crates/xfdf/src/tests.rs::fdf_round_trips_values_and_comments", "crates/automation/tests/automation.rs::comments_and_form_data_travel_as_xfdf_fdf_and_text"]
+notes = "XFDF, FDF; values go through formats and validation; read-only fields take data"
[[feature]]
id = "form.export-data"
@@ -4575,11 +4575,11 @@ title = "Export form data (FDF, XFDF)"
area = "F"
tier = "P1"
milestone = "M6"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["form.export_data"]
+tools = ["doc_export_data"]
+evidence = ["crates/xfdf/src/tests.rs::xfdf_round_trips_comments_and_values", "crates/automation/tests/automation.rs::comments_and_form_data_travel_as_xfdf_fdf_and_text"]
+notes = "XFDF, FDF"
[[feature]]
id = "form.data-xml-csv-txt"
@@ -4587,11 +4587,11 @@ title = "Form data as XML, CSV or tab-delimited text"
area = "F"
tier = "P1"
milestone = "M6"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["form.export_data", "form.import_data"]
+tools = ["doc_export_data", "doc_import_data"]
+evidence = ["crates/xfdf/src/tests.rs::form_data_as_xml_csv_and_text", "crates/automation/tests/automation.rs::comments_and_form_data_travel_as_xfdf_fdf_and_text"]
+notes = "Acrobat's XML (xfdf:original), CSV, tab-delimited"
[[feature]]
id = "form.merge-to-spreadsheet"
diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs
index c5780d74b..a999f377a 100644
--- a/xtask/src/layers.rs
+++ b/xtask/src/layers.rs
@@ -55,6 +55,7 @@ pub const TABLE: &[(&str, Class)] = &[
("organize", Class::Layer(4)),
("security", Class::Layer(4)),
("redact", Class::Layer(4)),
+ ("xfdf", Class::Layer(4)),
("sign", Class::Layer(4)),
("ocr", Class::Layer(4)),
("create", Class::Layer(4)),