use crate::object_handle::{ObjectHandle, ObjectHandleIdentity};
use crate::page_object_helper::PageObjectHelper;
use crate::pages::tree_rebuild::RebuildResult;
use crate::{ObjectRef, Pdf, Result};
use std::collections::{BTreeSet, HashMap};
use std::io::{Read, Seek};
pub const DEFAULT_MAX_ACROFORM_DEPTH: usize = 100;
#[allow(clippy::mutable_key_type)]
type WidgetPageMap = HashMap<ObjectHandleIdentity, (ObjectHandle, ObjectRef)>;
pub(crate) 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)
}
#[allow(clippy::mutable_key_type)]
pub(crate) 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 = WidgetPageMap::new();
for new_refs in result.ref_map.values() {
for &new_page in new_refs {
collect_page_widgets(pdf, new_page, &mut widget_to_page)?;
}
}
let catalog = pdf.trailer().try_get_key(b"/Root")?;
if !catalog.try_is_dictionary()? {
return Ok(());
}
let acroform = catalog.try_get_key(b"/AcroForm")?;
if !acroform.try_is_dictionary()? {
return Ok(()); }
let fields = acroform.try_get_key(b"/Fields")?;
let Some(fields_arr) = fields.try_as_array()? else {
return Ok(()); };
let mut kept_fields = Vec::new();
for field in fields_arr {
if field.object_ref().is_none() {
continue;
}
let has_widget = field_has_retained_widget(
pdf,
field.object_ref().expect("field entries are indirect"),
&widget_to_page,
&mut BTreeSet::new(),
0,
max_depth,
)?;
if has_widget {
kept_fields.push(field);
}
}
let retained_page_refs: BTreeSet<ObjectRef> = result.new_kids.iter().copied().collect();
for (widget, _) in widget_to_page.values() {
remove_stale_widget_page_ref(widget, &retained_page_refs, &result.removed_pages)?;
}
for field in &kept_fields {
let field_ref = field.object_ref().expect("kept field entries are indirect");
strip_dropped_widget_p_refs(
pdf,
field_ref,
&widget_to_page,
&mut BTreeSet::new(),
0,
max_depth,
)?;
}
if kept_fields.is_empty() {
catalog.remove_key(b"/AcroForm");
} else {
let replacement = ObjectHandle::array(kept_fields);
let replacement = if fields.is_indirect() {
pdf.make_indirect_object_handle(replacement)?
} else {
replacement
};
acroform.replace_key(b"/Fields", replacement)?;
}
*pdf.acroform_cache.borrow_mut() = None;
Ok(())
}
#[allow(clippy::mutable_key_type)]
fn collect_page_widgets<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
widget_to_page: &mut WidgetPageMap,
) -> Result<()> {
let widgets = {
let mut page = PageObjectHelper::new(page_ref, pdf);
page.get_annotations_filtered(Some(b"/Widget"))?
};
for widget in widgets {
widget_to_page
.entry(widget.identity_key())
.or_insert((widget, page_ref));
}
Ok(())
}
#[allow(clippy::mutable_key_type)]
fn field_has_retained_widget<R: Read + Seek>(
pdf: &mut Pdf<R>,
field_ref: ObjectRef,
widget_to_page: &WidgetPageMap,
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);
}
let field = pdf.get_object_handle(field_ref);
if widget_to_page.contains_key(&field.identity_key()) {
return Ok(true);
}
let kids = field.try_get_key(b"/Kids")?;
let Some(kids_arr) = kids.try_as_array()? else {
return Ok(false);
};
for kid in kids_arr {
kid.try_dereference()?;
let Some(kid_ref) = kid.object_ref() else {
continue;
};
if widget_to_page.contains_key(&kid.identity_key()) {
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 remove_stale_widget_page_ref(
widget: &ObjectHandle,
retained_page_refs: &BTreeSet<ObjectRef>,
removed_pages: &BTreeSet<ObjectRef>,
) -> Result<()> {
if !widget.try_is_dictionary()? || !widget.try_has_key(b"/P")? {
return Ok(());
}
let existing = widget.try_get_key(b"/P")?;
let Some(existing_ref) = existing.object_ref() else {
return Ok(());
};
if retained_page_refs.contains(&existing_ref) {
return Ok(());
}
if removed_pages.contains(&existing_ref) {
widget.remove_key(b"/P");
return Ok(());
}
if !existing.try_is_null()? {
return Ok(());
}
widget.remove_key(b"/P");
Ok(())
}
#[allow(clippy::mutable_key_type)]
fn strip_dropped_widget_p_refs<R: Read + Seek>(
pdf: &mut Pdf<R>,
field_ref: ObjectRef,
widget_to_page: &WidgetPageMap,
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 = pdf.get_object_handle(field_ref);
let kids = field.try_get_key(b"/Kids")?;
let Some(kids_arr) = kids.try_as_array()? else {
return Ok(());
};
for kid in kids_arr {
kid.try_dereference()?;
let Some(kid_ref) = kid.object_ref() else {
continue;
};
let subtype = kid.try_get_key(b"/Subtype")?;
let is_widget = subtype.try_as_name()?.as_deref() == Some(b"Widget".as_slice());
if is_widget {
if !widget_to_page.contains_key(&kid.identity_key()) {
kid.remove_key(b"/P");
}
} 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::job::check_bytes_for_test;
use crate::pages::page_refs;
use crate::pages::tree_rebuild::rebuild_page_tree;
use crate::writer::write_qpdf_to_memory;
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 [<< /FT /Tx /T (DirectTop) /Kids [] >> 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_direct_field_kid_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] /Count 1 /MediaBox [0 0 612 792] >>",
),
(3, b"<< /Type /Page /Parent 2 0 R >>"),
(5, b"<< /Fields [6 0 R] /DA (/Helvetica 12 Tf 0 g) >>"),
(
6,
b"<< /FT /Tx /T (DirectKid) /Kids [<< /Type /Annot /Subtype /Widget /P 3 0 R /Rect [10 700 200 720] >>] >>",
),
];
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) -> BTreeMap<Vec<u8>, ObjectHandle> {
let handle = pdf.get_object_handle(r);
handle.try_is_scalar().unwrap();
handle
.as_dictionary()
.unwrap_or_else(|| panic!("{r} is not a dictionary: {handle:?}"))
}
fn reference_target(value: &ObjectHandle) -> Option<ObjectRef> {
value.object_ref()
}
fn acroform_fields(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> Vec<ObjectRef> {
let catalog = pdf.trailer().try_get_key(b"/Root").unwrap();
catalog.try_is_scalar().unwrap();
let acroform = catalog.try_get_key(b"/AcroForm").unwrap();
acroform.try_is_scalar().unwrap();
if acroform.as_dictionary().is_none() {
return vec![];
}
let fields = acroform.try_get_key(b"/Fields").unwrap();
fields.try_is_scalar().unwrap();
fields
.as_array()
.unwrap_or_default()
.into_iter()
.filter_map(|field| field.object_ref())
.collect()
}
#[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());
assert!(acroform_fields(&mut pdf).is_empty());
}
#[test]
fn non_dictionary_widget_handle_is_ignored() {
let widget = ObjectHandle::integer(1);
let retained = BTreeSet::from([ObjectRef::new(3, 0)]);
remove_stale_widget_page_ref(&widget, &retained, &BTreeSet::new()).unwrap();
}
#[test]
fn retained_indirect_widget_keeps_existing_page_reference() {
let mut pdf = open(build_acroform_pdf());
let widget = pdf.get_object_handle(ObjectRef::new(7, 0));
let retained = BTreeSet::from([ObjectRef::new(3, 0)]);
remove_stale_widget_page_ref(&widget, &retained, &BTreeSet::new()).unwrap();
let widget_dict = dict_of(&mut pdf, ObjectRef::new(7, 0));
assert_eq!(
widget_dict.get(b"/P".as_slice()).and_then(reference_target),
Some(ObjectRef::new(3, 0)),
"an indirect widget already owned by a retained page must keep /P"
);
}
#[test]
fn standalone_caller_removes_p_for_a_removed_page_before_null_out_runs() {
let mut pdf = open(build_acroform_pdf());
let widget = pdf.get_object_handle(ObjectRef::new(11, 0));
widget.try_is_scalar().unwrap();
let retained = BTreeSet::from([ObjectRef::new(3, 0), ObjectRef::new(4, 0)]);
let removed_pages = BTreeSet::from([ObjectRef::new(5, 0)]);
remove_stale_widget_page_ref(&widget, &retained, &removed_pages).unwrap();
let widget_dict = dict_of(&mut pdf, ObjectRef::new(11, 0));
assert!(
!widget_dict.contains_key(b"/P".as_slice()),
"a widget /P pointing at a page reported as removed must lose \
the key even when the target has not been nulled yet"
);
}
#[test]
fn widget_non_reference_page_value_is_preserved() {
let mut pdf = open(build_acroform_pdf());
let widget = pdf.get_object_handle(ObjectRef::new(7, 0));
widget.try_is_scalar().unwrap();
widget.replace_key(b"/P", ObjectHandle::integer(7)).unwrap();
let result = rebuild_page_tree(&mut pdf, &[ObjectRef::new(3, 0)]).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
assert_eq!(
dict_of(&mut pdf, ObjectRef::new(7, 0))
.get(b"/P".as_slice())
.and_then(ObjectHandle::as_integer),
Some(7),
"qpdf writer does not infer page ownership from a non-reference /P value"
);
}
#[test]
fn widget_non_page_reference_is_preserved() {
let mut pdf = open(build_acroform_pdf());
let widget = pdf.get_object_handle(ObjectRef::new(7, 0));
widget.try_is_scalar().unwrap();
let non_page_ref = pdf.get_object_handle(ObjectRef::new(6, 0));
widget.replace_key(b"/P", non_page_ref).unwrap();
let result = rebuild_page_tree(&mut pdf, &[ObjectRef::new(3, 0)]).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
assert_eq!(
dict_of(&mut pdf, ObjectRef::new(7, 0))
.get(b"/P".as_slice())
.and_then(reference_target),
Some(ObjectRef::new(6, 0)),
"qpdf does not rewrite a non-page /P target through an owner heuristic"
);
}
#[test]
fn direct_field_kid_is_not_promoted_to_retained_widget() {
let mut pdf = open(build_direct_field_kid_pdf());
let result = rebuild_page_tree(&mut pdf, &[ObjectRef::new(3, 0)]).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let catalog = dict_of(&mut pdf, ObjectRef::new(1, 0));
assert!(
!catalog.contains_key(b"/AcroForm".as_slice()),
"direct field-tree kid must not keep its parent field"
);
}
#[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_missing_is_left_missing() {
let mut pdf = open(build_acroform_pdf());
for &r in &[ObjectRef::new(7, 0), ObjectRef::new(9, 0)] {
let widget = pdf.get_object_handle(r);
widget.try_is_scalar().unwrap();
widget.remove_key(b"/P");
}
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!(
!field_a.contains_key(b"/P".as_slice()),
"FieldA /P must not be synthesized"
);
let b1 = dict_of(&mut pdf, ObjectRef::new(9, 0));
assert!(
!b1.contains_key(b"/P".as_slice()),
"B1 /P must not be synthesized"
);
}
#[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.contains_key(b"/P".as_slice()),
"B2 (dropped page) /P should be removed"
);
}
#[test]
fn indirect_arrays_are_resolved_while_pruning_fields_annots_and_kids() {
let objects: Vec<(u32, &[u8])> = vec![
(1, b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields 12 0 R /DA (/Helvetica 12 Tf 0 g) >> >>"),
(
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 13 0 R >>"),
(4, b"<< /Type /Page /Parent 2 0 R /Annots [10 0 R] >>"),
(8, b"<< /FT /Tx /T (FieldB) /Kids 14 0 R >>"),
(
9,
b"<< /Type /Annot /Subtype /Widget /Parent 8 0 R /P 3 0 R /Rect [10 600 200 620] >>",
),
(
10,
b"<< /Type /Annot /Subtype /Widget /Parent 8 0 R /P 4 0 R /Rect [10 500 200 520] >>",
),
(12, b"[8 0 R]"),
(13, b"[9 0 R]"),
(14, b"[9 0 R 10 0 R]"),
];
let mut pdf = open(build_pdf(&objects));
let sel = [ObjectRef::new(3, 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_eq!(fields, vec![ObjectRef::new(8, 0)]);
let b1 = dict_of(&mut pdf, ObjectRef::new(9, 0));
assert_eq!(
b1.get(b"/P".as_slice()).and_then(reference_target),
Some(ObjectRef::new(3, 0))
);
let b2 = dict_of(&mut pdf, ObjectRef::new(10, 0));
assert!(
!b2.contains_key(b"/P".as_slice()),
"dropped-page widget /P must be stripped"
);
}
#[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 = dict_of(&mut pdf, ObjectRef::new(1, 0));
assert!(
!cat.contains_key(b"/AcroForm".as_slice()),
"/AcroForm should be removed from catalog when /Fields is empty"
);
}
#[test]
fn prune_invalidates_a_shared_acroform_cache_after_writeback() {
let mut pdf = open(build_acroform_pdf());
let before = pdf
.acroform()
.unwrap()
.canonical_annotation_to_field_handles()
.unwrap();
assert!(before
.iter()
.any(|(annotation, _)| annotation.object_ref() == Some(ObjectRef::new(11, 0))));
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 after = pdf
.acroform()
.unwrap()
.canonical_annotation_to_field_handles()
.unwrap();
assert!(
!after
.iter()
.any(|(annotation, _)| annotation.object_ref() == Some(ObjectRef::new(11, 0))),
"pruning /AcroForm /Fields must invalidate the shared cache"
);
}
#[test]
fn prune_invalidates_a_shared_acroform_cache_after_removing_acroform() {
let mut pdf = open(build_all_on_page1_pdf());
let before = pdf
.acroform()
.unwrap()
.canonical_annotation_to_field_handles()
.unwrap();
assert!(before
.iter()
.any(|(annotation, _)| annotation.object_ref() == Some(ObjectRef::new(6, 0))));
let sel = [ObjectRef::new(4, 0)];
let result = rebuild_page_tree(&mut pdf, &sel).unwrap();
prune_acroform_after_subset(&mut pdf, &result).unwrap();
let after = pdf
.acroform()
.unwrap()
.canonical_annotation_to_field_handles()
.unwrap();
assert!(
after.is_empty(),
"removing /AcroForm must invalidate the shared cache"
);
}
#[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(b"/Kids".as_slice())
.and_then(ObjectHandle::as_array)
{
Some(kids) => {
assert_eq!(
kids.len(),
2,
"FieldB /Kids should still have 2 entries (not pruned)"
);
assert!(
kids.iter()
.any(|kid| kid.object_ref() == Some(ObjectRef::new(9, 0))),
"B1 should remain in /Kids"
);
assert!(
kids.iter()
.any(|kid| kid.object_ref() == Some(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 out = write_qpdf_to_memory(&mut pdf, |_| {}).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);
check_bytes_for_test(out).expect("canonical qpdf check should run");
}
#[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");
}
}