Skip to content

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

automation: report effective validated PDF version in doc_optimize (#3090)

jonathanwxh-cell2714f9e54f4b
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index eb320da76..ee0dc4cd7 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -1127,7 +1127,17 @@ impl Automation {
};
let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
write_atomic(&path, &bytes)?;
- let pdf_version = std::str::from_utf8(bytes.get(5..8).unwrap_or_default()).unwrap_or_default();
+ let valid_version = |v: &[u8]| matches!(v, [b'1'..=b'9', b'.', b'0'..=b'9']).then(|| std::str::from_utf8(v).ok()).flatten();
+ let catalog_version = (settings.compatibility == Compatibility::Retain)
+ .then(|| {
+ let pw = self.doc(a).ok().and_then(|d| d.password.as_deref());
+ let doc = pdfcraft_cos::Document::open_with_password(bytes.clone(), pw).ok()?;
+ let root = doc.root()?;
+ doc.get(root).as_dict()?.name(b"Version").and_then(valid_version).map(str::to_owned)
+ })
+ .flatten();
+ let header_version = bytes.strip_prefix(b"%PDF-").and_then(|b| b.get(..3)).and_then(valid_version);
+ let pdf_version = catalog_version.as_deref().or(header_version);
let o = &r.optimize;
Ok(json!({
"path": path.to_string_lossy(),
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index b69a6b207..55b08f6ba 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -4637,6 +4637,16 @@ fn optimizing_through_tools() {
assert_eq!((v20["pdf_version"].as_str(), v20["object_streams"].as_bool()), (Some("2.0"), Some(false)), "{v20}");
assert!(std::fs::read(dir.join("v20.pdf")).unwrap().starts_with(b"%PDF-2.0\n"));
+ // In retain mode, a catalog /Version override is reported as the effective PDF version.
+ let mut cos14 = pdfcraft_cos::Document::open(std::sync::Arc::new(v14_bytes)).unwrap();
+ let root = cos14.root().unwrap();
+ cos14.update_dict(root, |c| c.set(b"Version".to_vec(), pdfcraft_cos::Object::name("1.6"))).unwrap();
+ let cat16 = pdfcraft_cos::write_full(&cos14, &pdfcraft_cos::SaveOptions { object_streams: false, ..Default::default() }).unwrap();
+ std::fs::write(dir.join("cat16.pdf"), &cat16).unwrap();
+ let cat_doc = ok(&mut a, "doc_open", json!({ "path": "cat16.pdf" }))["doc"].as_u64().unwrap();
+ let retained = ok(&mut a, "doc_optimize", json!({ "doc": cat_doc, "path": "retained.pdf", "compatibility": "retain", "object_streams": false }));
+ assert_eq!(retained["pdf_version"].as_str(), Some("1.6"), "{retained}");
+
assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "compatibility": "1.3" })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(
a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "color": { "compression": "gif" } })),