use crate::page_tree_rebuild::RebuildResult;
use crate::{Object, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};
pub const DEFAULT_MAX_ACROFORM_DEPTH: usize = 100;
pub fn prune_acroform_after_subset<R: Read + Seek>(
pdf: &mut Pdf<R>,
result: &RebuildResult,
) -> Result<()> {
prune_acroform_after_subset_with_max_depth(pdf, result, DEFAULT_MAX_ACROFORM_DEPTH)
}
pub fn prune_acroform_after_subset_with_max_depth<R: Read + Seek>(
pdf: &mut Pdf<R>,
result: &RebuildResult,
max_depth: usize,
) -> Result<()> {
let mut widget_to_page: BTreeMap<ObjectRef, ObjectRef> = BTreeMap::new();
for (&_old_page, new_refs) in &result.ref_map {
let Some(&new_page) = new_refs.first() else {
continue;
};
collect_page_widgets(pdf, new_page, &mut widget_to_page)?;
}
let catalog_ref = match pdf.root_ref() {
Some(r) => r,
None => return Ok(()), };
let catalog_obj = pdf.resolve(catalog_ref)?;
let Some(catalog) = catalog_obj.into_dict() else {
return Ok(());
};
let (acroform_ref, acroform_dict) = match catalog.get("AcroForm").cloned() {
Some(Object::Reference(r)) => match pdf.resolve(r)? {
Object::Dictionary(d) => (Some(r), d),
_ => return Ok(()),
},
Some(Object::Dictionary(d)) => (None, d),
_ => return Ok(()), };
let fields_val = match acroform_dict.get("Fields").cloned() {
Some(v) => v,
None => return Ok(()), };
let fields_arr: Vec<Object> = match fields_val {
Object::Array(arr) => arr,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Array(arr) => arr,
_ => return Ok(()),
},
_ => return Ok(()),
};
let mut kept_fields: Vec<Object> = Vec::new();
for field_val in &fields_arr {
let field_ref = match field_val {
Object::Reference(r) => *r,
_ => continue, };
let has_widget = field_has_retained_widget(
pdf,
field_ref,
&widget_to_page,
&mut BTreeSet::new(),
0,
max_depth,
)?;
if has_widget {
kept_fields.push(Object::Reference(field_ref));
}
}
for (&widget_ref, &new_page_ref) in &widget_to_page {
update_widget_page_ref(pdf, widget_ref, new_page_ref)?;
}
for field_val in &kept_fields {
let field_ref = match field_val {
Object::Reference(r) => *r,
_ => continue,
};
strip_dropped_widget_p_refs(
pdf,
field_ref,
&widget_to_page,
&mut BTreeSet::new(),
0,
max_depth,
)?;
}
if kept_fields.is_empty() {
let catalog_obj2 = pdf.resolve(catalog_ref)?;
if let Some(mut cat) = catalog_obj2.into_dict() {
cat.remove("AcroForm");
pdf.set_object(catalog_ref, Object::Dictionary(cat));
}
} else {
let mut new_acroform = acroform_dict;
new_acroform.insert("Fields", Object::Array(kept_fields));
match acroform_ref {
Some(r) => {
pdf.set_object(r, Object::Dictionary(new_acroform));
}
None => {
let catalog_obj2 = pdf.resolve(catalog_ref)?;
if let Some(mut cat) = catalog_obj2.into_dict() {
cat.insert("AcroForm", Object::Dictionary(new_acroform));
pdf.set_object(catalog_ref, Object::Dictionary(cat));
}
}
}
}
Ok(())
}
fn collect_page_widgets<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
widget_to_page: &mut BTreeMap<ObjectRef, ObjectRef>,
) -> Result<()> {
let page_obj = pdf.resolve(page_ref)?;
let Some(page_dict) = page_obj.into_dict() else {
return Ok(());
};
let annots_val = match page_dict.get("Annots").cloned() {
Some(v) => v,
None => return Ok(()),
};
let annots_arr: Vec<Object> = match annots_val {
Object::Array(arr) => arr,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Array(arr) => arr,
_ => return Ok(()),
},
_ => return Ok(()),
};
for annot_val in &annots_arr {
let annot_ref = match annot_val {
Object::Reference(r) => *r,
_ => continue,
};
let annot_obj = pdf.resolve(annot_ref)?;
let Some(annot_dict) = annot_obj.into_dict() else {
continue;
};
let is_widget = matches!(
annot_dict.get("Subtype"),
Some(Object::Name(n)) if n.as_slice() == b"Widget"
);
if is_widget {
widget_to_page.entry(annot_ref).or_insert(page_ref);
}
}
Ok(())
}
fn field_has_retained_widget<R: Read + Seek>(
pdf: &mut Pdf<R>,
field_ref: ObjectRef,
widget_to_page: &BTreeMap<ObjectRef, ObjectRef>,
visited: &mut BTreeSet<ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<bool> {
if depth > max_depth {
return Err(crate::Error::Unsupported(format!(
"acroform_field_prune: field-tree depth limit {max_depth} exceeded at {field_ref}"
)));
}
if !visited.insert(field_ref) {
return Ok(false);
}
if widget_to_page.contains_key(&field_ref) {
return Ok(true);
}
let field_obj = pdf.resolve(field_ref)?;
let Some(field_dict) = field_obj.into_dict() else {
return Ok(false);
};
let kids_val = match field_dict.get("Kids").cloned() {
Some(v) => v,
None => return Ok(false),
};
let kids_arr: Vec<Object> = match kids_val {
Object::Array(arr) => arr,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Array(arr) => arr,
_ => return Ok(false),
},
_ => return Ok(false),
};
for kid_val in &kids_arr {
let kid_ref = match kid_val {
Object::Reference(r) => *r,
_ => continue,
};
if widget_to_page.contains_key(&kid_ref) {
return Ok(true);
}
if field_has_retained_widget(pdf, kid_ref, widget_to_page, visited, depth + 1, max_depth)? {
return Ok(true);
}
}
Ok(false)
}
fn update_widget_page_ref<R: Read + Seek>(
pdf: &mut Pdf<R>,
widget_ref: ObjectRef,
new_page_ref: ObjectRef,
) -> Result<()> {
let widget_obj = pdf.resolve(widget_ref)?;
if let Some(mut dict) = widget_obj.into_dict() {
dict.insert("P", Object::Reference(new_page_ref));
pdf.set_object(widget_ref, Object::Dictionary(dict));
}
Ok(())
}
fn strip_dropped_widget_p_refs<R: Read + Seek>(
pdf: &mut Pdf<R>,
field_ref: ObjectRef,
widget_to_page: &BTreeMap<ObjectRef, ObjectRef>,
visited: &mut BTreeSet<ObjectRef>,
depth: usize,
max_depth: usize,
) -> Result<()> {
if depth > max_depth {
return Err(crate::Error::Unsupported(format!(
"acroform_field_prune: field-tree depth limit {max_depth} exceeded at {field_ref}"
)));
}
if !visited.insert(field_ref) {
return Ok(()); }
let field_obj = pdf.resolve(field_ref)?;
let Some(field_dict) = field_obj.into_dict() else {
return Ok(());
};
let kids_val = match field_dict.get("Kids").cloned() {
Some(v) => v,
None => {
return Ok(());
}
};
let kids_arr: Vec<Object> = match kids_val {
Object::Array(arr) => arr,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Array(arr) => arr,
_ => return Ok(()),
},
_ => return Ok(()),
};
for kid_val in &kids_arr {
let kid_ref = match kid_val {
Object::Reference(r) => *r,
_ => continue,
};
let kid_obj = pdf.resolve(kid_ref)?;
let Some(kid_dict) = kid_obj.into_dict() else {
continue;
};
let is_widget = matches!(
kid_dict.get("Subtype"),
Some(Object::Name(n)) if n.as_slice() == b"Widget"
);
if is_widget {
if !widget_to_page.contains_key(&kid_ref) {
let kid_obj2 = pdf.resolve(kid_ref)?;
if let Some(mut d) = kid_obj2.into_dict() {
d.remove("P");
pdf.set_object(kid_ref, Object::Dictionary(d));
}
}
} else {
strip_dropped_widget_p_refs(
pdf,
kid_ref,
widget_to_page,
visited,
depth + 1,
max_depth,
)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::check::check_reader;
use crate::page_tree_rebuild::rebuild_page_tree;
use crate::pages::page_refs;
use crate::writer::write_pdf;
use crate::Pdf;
use std::collections::BTreeMap;
use std::io::Cursor;
fn build_acroform_pdf() -> Vec<u8> {
let objects: Vec<(u32, &[u8])> =
vec![
(1, b"<< /Type /Catalog /Pages 2 0 R /AcroForm 6 0 R >>"),
(
2,
b"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 612 792] >>",
),
(3, b"<< /Type /Page /Parent 2 0 R /Annots [7 0 R] >>"),
(4, b"<< /Type /Page /Parent 2 0 R /Annots [9 0 R] >>"),
(5, b"<< /Type /Page /Parent 2 0 R /Annots [10 0 R 11 0 R] >>"),
(
6,
b"<< /Fields [7 0 R 8 0 R 11 0 R] /DA (/Helvetica 12 Tf 0 g) >>",
),
(
7,
b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (FieldA) /V (hello) \
/P 3 0 R /Rect [10 700 200 720] >>",
),
(8, b"<< /FT /Tx /T (FieldB) /Kids [9 0 R 10 0 R] >>"),
(
9,
b"<< /Type /Annot /Subtype /Widget /Parent 8 0 R /P 4 0 R \
/Rect [10 600 200 620] >>",
),
(
10,
b"<< /Type /Annot /Subtype /Widget /Parent 8 0 R /P 5 0 R \
/Rect [10 500 200 520] >>",
),
(
11,
b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (FieldC) /V (world) \
/P 5 0 R /Rect [10 400 200 420] >>",
),
];
build_pdf(&objects)
}
fn build_all_on_page1_pdf() -> Vec<u8> {
let objects: Vec<(u32, &[u8])> = vec![
(1, b"<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>"),
(
2,
b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>",
),
(3, b"<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>"),
(4, b"<< /Type /Page /Parent 2 0 R >>"),
(5, b"<< /Fields [6 0 R] /DA (/Helvetica 12 Tf 0 g) >>"),
(
6,
b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (FieldA) \
/P 3 0 R /Rect [10 700 200 720] >>",
),
];
build_pdf(&objects)
}
fn build_no_acroform_pdf() -> Vec<u8> {
let objects: Vec<(u32, &[u8])> = vec![
(1, b"<< /Type /Catalog /Pages 2 0 R >>"),
(
2,
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
),
(3, b"<< /Type /Page /Parent 2 0 R >>"),
];
build_pdf(&objects)
}
fn build_pdf(objects: &[(u32, &[u8])]) -> Vec<u8> {
let mut out = b"%PDF-1.6\n".to_vec();
let mut offsets: BTreeMap<u32, u64> = BTreeMap::new();
for &(num, bytes) in objects {
offsets.insert(num, out.len() as u64);
out.extend_from_slice(format!("{num} 0 obj\n").as_bytes());
out.extend_from_slice(bytes);
out.extend_from_slice(b"\nendobj\n");
}
let xref_pos = out.len() as u64;
let max_num = objects.iter().map(|&(n, _)| n).max().unwrap_or(0);
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", max_num + 1).as_bytes());
for i in 1..=max_num {
match offsets.get(&i) {
Some(&off) => {
out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
}
None => {
out.extend_from_slice(b"0000000000 00001 f \n");
}
}
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",
max_num + 1
)
.as_bytes(),
);
out
}
fn open(bytes: Vec<u8>) -> Pdf<Cursor<Vec<u8>>> {
Pdf::open(Cursor::new(bytes)).expect("PDF should parse")
}
fn dict_of(pdf: &mut Pdf<Cursor<Vec<u8>>>, r: ObjectRef) -> crate::Dictionary {
match pdf.resolve(r).unwrap() {
Object::Dictionary(d) => d,
other => panic!("{r} is not a dictionary: {other:?}"),
}
}
fn acroform_fields(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> Vec<ObjectRef> {
let cat_ref = pdf.root_ref().expect("root");
let cat = dict_of(pdf, cat_ref);
let acro_val = match cat.get("AcroForm").cloned() {
None => return vec![],
Some(v) => v,
};
let acro_dict = match acro_val {
Object::Dictionary(d) => d,
Object::Reference(r) => match pdf.resolve(r).unwrap() {
Object::Dictionary(d) => d,
_ => return vec![],
},
_ => return vec![],
};
match acro_dict.get("Fields").cloned() {
Some(Object::Array(arr)) => arr.iter().filter_map(Object::as_ref_id).collect(),
_ => vec![],
}
}
#[test]
fn no_acroform_is_noop() {
let mut pdf = open(build_no_acroform_pdf());
let pages = page_refs(&mut pdf).unwrap();
let result = rebuild_page_tree(&mut pdf, &pages).unwrap();
assert!(prune_acroform_after_subset(&mut pdf, &result).is_ok());
}
#[test]
fn retained_page_widget_keeps_field() {
let mut pdf = open(build_acroform_pdf());
let sel = [ObjectRef::new(3, 0), ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let fields = acroform_fields(&mut pdf);
assert!(
fields.contains(&ObjectRef::new(7, 0)),
"FieldA should be retained; fields={fields:?}"
);
assert!(
fields.contains(&ObjectRef::new(8, 0)),
"FieldB should be retained (B1 on page 2); fields={fields:?}"
);
assert!(
!fields.contains(&ObjectRef::new(11, 0)),
"FieldC should be removed; fields={fields:?}"
);
}
#[test]
fn all_widgets_dropped_removes_field() {
let mut pdf = open(build_acroform_pdf());
let sel = [ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let fields = acroform_fields(&mut pdf);
assert!(
!fields.contains(&ObjectRef::new(7, 0)),
"FieldA should be removed (page 1 dropped)"
);
assert!(
fields.contains(&ObjectRef::new(8, 0)),
"FieldB should be retained (B1 on retained page 2)"
);
assert!(
!fields.contains(&ObjectRef::new(11, 0)),
"FieldC should be removed (page 3 dropped)"
);
}
#[test]
fn widget_p_updated_to_new_page_ref() {
let mut pdf = open(build_acroform_pdf());
for &r in &[ObjectRef::new(7, 0), ObjectRef::new(9, 0)] {
let Object::Dictionary(mut d) = pdf.resolve(r).unwrap() else {
panic!("expected dict for {r}");
};
d.remove("P");
pdf.set_object(r, Object::Dictionary(d));
}
let sel = [ObjectRef::new(3, 0), ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let field_a = dict_of(&mut pdf, ObjectRef::new(7, 0));
assert_eq!(
field_a.get("P"),
Some(&Object::Reference(ObjectRef::new(3, 0))),
"FieldA /P should be set to page-1 ref"
);
let b1 = dict_of(&mut pdf, ObjectRef::new(9, 0));
assert_eq!(
b1.get("P"),
Some(&Object::Reference(ObjectRef::new(4, 0))),
"B1 /P should be set to page-2 ref"
);
}
#[test]
fn dropped_page_widget_p_removed() {
let mut pdf = open(build_acroform_pdf());
let sel = [ObjectRef::new(3, 0), ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let b2 = dict_of(&mut pdf, ObjectRef::new(10, 0));
assert!(
b2.get("P").is_none(),
"B2 (dropped page) /P should be removed; got {:?}",
b2.get("P")
);
}
#[test]
fn empty_fields_removes_acroform_from_catalog() {
let mut pdf = open(build_all_on_page1_pdf());
let sel = [ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let cat_ref = pdf.root_ref().unwrap();
let cat = dict_of(&mut pdf, cat_ref);
assert!(
cat.get("AcroForm").is_none(),
"/AcroForm should be removed from catalog when /Fields is empty"
);
}
#[test]
fn split_field_with_mixed_widgets_kept_and_kids_not_pruned() {
let mut pdf = open(build_acroform_pdf());
let sel = [ObjectRef::new(3, 0), ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let fields = acroform_fields(&mut pdf);
assert!(
fields.contains(&ObjectRef::new(8, 0)),
"FieldB kept because B1 is on retained page 2"
);
let field_b = dict_of(&mut pdf, ObjectRef::new(8, 0));
match field_b.get("Kids") {
Some(Object::Array(kids)) => {
assert_eq!(
kids.len(),
2,
"FieldB /Kids should still have 2 entries (not pruned)"
);
assert!(
kids.contains(&Object::Reference(ObjectRef::new(9, 0))),
"B1 should remain in /Kids"
);
assert!(
kids.contains(&Object::Reference(ObjectRef::new(10, 0))),
"B2 should remain in /Kids (qpdf-compatible: no /Kids pruning)"
);
}
other => panic!("FieldB /Kids unexpected: {other:?}"),
}
}
#[test]
fn cycle_in_field_kids_does_not_hang() {
let objects: Vec<(u32, &[u8])> = vec![
(1, b"<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
(
2,
b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>",
),
(3, b"<< /Type /Page /Parent 2 0 R >>"),
(4, b"<< /Fields [5 0 R] /DA (/Helvetica 12 Tf 0 g) >>"),
(5, b"<< /FT /Tx /T (FieldX) /Kids [5 0 R] >>"),
];
let mut pdf = open(build_pdf(&objects));
let pages = page_refs(&mut pdf).unwrap();
let result = rebuild_page_tree(&mut pdf, &pages).unwrap();
assert!(prune_acroform_after_subset(&mut pdf, &result).is_ok());
}
#[test]
fn round_trip_valid_pdf_after_prune() {
let mut pdf = open(build_acroform_pdf());
let sel = [ObjectRef::new(3, 0), ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let mut out: Vec<u8> = Vec::new();
write_pdf(&mut pdf, &mut out).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(out.clone())).expect("rebuilt PDF should parse");
let refs = page_refs(&mut pdf2).expect("page tree should walk");
assert_eq!(refs.len(), 2);
let report = check_reader(Cursor::new(out)).expect("check should run");
assert!(
report.valid,
"pruned PDF should pass check_reader: {:?}",
report.diagnostics
);
}
#[test]
fn all_pages_retained_keeps_all_fields() {
let mut pdf = open(build_acroform_pdf());
let all_pages = page_refs(&mut pdf).unwrap();
let result = rebuild_page_tree(&mut pdf, &all_pages).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let fields = acroform_fields(&mut pdf);
assert_eq!(fields.len(), 3, "All 3 fields should be kept");
}
}