Skip to content

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

Export Data as CSV keeps formula-like cells as text, like the merge report (#2524)

oracola9140c22e3ea58e
diff --git a/crates/xfdf/README.md b/crates/xfdf/README.md
index c137aabd9..d286a457c 100644
--- a/crates/xfdf/README.md
+++ b/crates/xfdf/README.md
@@ -40,7 +40,9 @@ including CDATA and character references. Nested-element and XFA interpretation
CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV
delimiters without changing field identities. Automatic detection of externally authored, ambiguous
-tables remains heuristic.
+tables remains heuristic. Both write a cell that a spreadsheet would run as a formula (`=` or `@`,
+or `+` or `-` when it isn't a plain number) with a leading `'`; CSV import takes off the `'` that
+export added, so exported data imports back unchanged.
Import replaces comments with the same `/NM` (and drops the replaced comment's pop-up), draws
appearances PdfCraft can draw, and sets values through the form's own checks (formats,
diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs
index ba8cb6f7f..dec32c741 100644
--- a/crates/xfdf/src/lib.rs
+++ b/crates/xfdf/src/lib.rs
@@ -112,7 +112,11 @@ pub fn export_data(doc: &Document, format: Format) -> String {
out
}
Format::Csv => {
- let q = |s: &str| if s.contains([',', '"', '\n', '\r', '\t']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s.to_string() };
+ // A formula-like cell gets a leading `'`, as in `merge_csv`; import takes it off again.
+ let q = |s: &str| {
+ let s = if csv_guarded(s) { format!("'{s}") } else { s.to_string() };
+ if s.contains([',', '"', '\n', '\r', '\t']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s }
+ };
format!(
"{}\n{}\n",
fields.iter().map(|f| q(&f.0)).collect::<Vec<_>>().join(","),
@@ -184,15 +188,7 @@ pub fn merge_csv(files: &[Vec<(String, Vec<String>)>]) -> String {
}
}
}
- let literal = |s: &str| {
- let t = s.trim_start();
- let formula = match t.chars().next() {
- Some('=' | '@') => true,
- Some('+' | '-') => !t.parse::<f64>().is_ok_and(f64::is_finite),
- _ => false,
- };
- if formula { format!("'{s}") } else { s.to_string() }
- };
+ let literal = |s: &str| if runs_as_formula(s) { format!("'{s}") } else { s.to_string() };
let q = |s: &str| {
let s = literal(s);
if s.contains([',', '"', '\n', '\r', '\t']) { format!("\"{}\"", s.replace('"', "\"\"")) } else { s }
@@ -207,6 +203,32 @@ pub fn merge_csv(files: &[Vec<(String, Vec<String>)>]) -> String {
out
}
+/// Whether a spreadsheet program runs CSV cell `s` as a formula: after any leading whitespace it
+/// starts with `=` or `@`, or with `+` or `-` and is not a plain number.
+fn runs_as_formula(s: &str) -> bool {
+ let t = s.trim_start();
+ match t.chars().next() {
+ Some('=' | '@') => true,
+ Some('+' | '-') => !t.parse::<f64>().is_ok_and(f64::is_finite),
+ _ => false,
+ }
+}
+
+/// Whether Export Data writes CSV cell `s` with a leading `'`: it runs as a formula, or it already
+/// starts with `'` in front of one. That second case gets one more `'`, so [`csv_text`] can take
+/// exactly one off on import and every value comes back unchanged.
+fn csv_guarded(s: &str) -> bool {
+ runs_as_formula(s.trim_start_matches('\''))
+}
+
+/// A CSV cell's text without the `'` that Export Data added (see [`csv_guarded`]).
+fn csv_text(cell: String) -> String {
+ match cell.strip_prefix('\'') {
+ Some(rest) if csv_guarded(rest) => rest.to_string(),
+ _ => cell,
+ }
+}
+
// Inspect the first logical record: tabs within quoted CSV cells are data. A quote
// in the middle of an unquoted TSV name stays literal, as in the TSV reader.
fn has_tab_delimiter(text: &str) -> bool {
@@ -287,7 +309,11 @@ fn import_table(doc: &mut Document, text: &str) -> Result<Report, DataError> {
let (Some(head), Some(row)) = (records.next(), records.next()) else { return Err(DataError::UnknownFormat) };
// Text exported from a one-field form has no tab to show for it (#1321). CSV quotes a
// value with a comma, so one name over several unquoted cells is that text, not CSV.
- if head.len() == 1 && row.len() > 1 { tab_delimited(t)? } else { head.into_iter().zip(row).map(|(k, v)| (k, vec![v])).collect() }
+ if head.len() == 1 && row.len() > 1 {
+ tab_delimited(t)?
+ } else {
+ head.into_iter().zip(row).map(|(k, v)| (csv_text(k), vec![csv_text(v)])).collect()
+ }
};
apply_values(doc, &values, &mut report);
Ok(report)
diff --git a/crates/xfdf/src/tests.rs b/crates/xfdf/src/tests.rs
index 52a4a5b86..d2110d3da 100644
--- a/crates/xfdf/src/tests.rs
+++ b/crates/xfdf/src/tests.rs
@@ -623,6 +623,45 @@ fn csv_exports_preserve_carriage_returns_in_names_and_values() {
}
}
+/// Export Data as CSV writes a name or value that a spreadsheet would run as a formula with a
+/// leading `'`, by the same rule as Merge Data Files, and Import Data gives it back unchanged.
+#[test]
+fn exported_csv_cells_never_start_a_formula_and_import_back_unchanged() {
+ for (name, value, expected) in [
+ ("Name", "=1+1", "Name\n'=1+1\n"),
+ ("Name", "@SUM(A1:A2)", "Name\n'@SUM(A1:A2)\n"),
+ ("Name", "+1 555 0100", "Name\n'+1 555 0100\n"),
+ ("Name", "-A1", "Name\n'-A1\n"),
+ ("Name", " =1+1", "Name\n' =1+1\n"),
+ ("Name", "\t=1+1", "Name\n\"'\t=1+1\"\n"),
+ ("Name", "\r=1+1", "Name\n\"'\r=1+1\"\n"),
+ ("Name", "=1,2", "Name\n\"'=1,2\"\n"),
+ ("Name", "'=1+1", "Name\n''=1+1\n"),
+ ("Name", "-12.5", "Name\n-12.5\n"),
+ ("Name", "+1", "Name\n+1\n"),
+ ("Name", "'-5", "Name\n'-5\n"),
+ ("Name", "'plain", "Name\n'plain\n"),
+ ("Name", "a=b", "Name\na=b\n"),
+ ("=Name", "Ada", "'=Name\nAda\n"),
+ ] {
+ let mut src = one_field();
+ let field = fields(&src)[0].obj;
+ src.update_dict(field, |d| d.set(b"T".to_vec(), PdfString::text(name))).unwrap();
+ set_value(&mut src, name, &FieldValue::Text(value.into())).unwrap();
+ let source = Arc::new(write_full(&src, &SaveOptions::default()).unwrap());
+ let src = Document::open(source.clone()).unwrap();
+ let csv = export_data(&src, Format::Csv);
+ assert_eq!(csv, expected, "{value:?}");
+
+ let mut dst = Document::open(source).unwrap();
+ set_value(&mut dst, name, &FieldValue::Text("replaced".into())).unwrap();
+ let report = import(&mut dst, csv.as_bytes()).unwrap();
+ assert_eq!(report.fields, 1, "{value:?}");
+ assert!(report.rejected.is_empty(), "{report:?}");
+ assert_eq!(values(&dst), [(name.to_string(), vec![value.to_string()])]);
+ }
+}
+
/// #1321: the text export of a one-field form has no tab to tell it from CSV, so a comma in the
/// value used to split it and only the text before the comma was imported.
#[test]