use crate::page_object_helper::PageBox;
use crate::{AnnotationObjectHelper, Object, ObjectRef, PageObjectHelper, Pdf, Result};
use std::io::{Read, Seek};
#[derive(Debug, Clone, PartialEq)]
pub struct EnumeratedAnnotation {
pub annot_ref: ObjectRef,
pub subtype: Option<Vec<u8>>,
pub rect: Option<PageBox>,
pub is_widget: bool,
pub field_ref: Option<ObjectRef>,
}
pub fn enumerate_page_annotations<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
) -> Result<Vec<EnumeratedAnnotation>> {
let annot_refs = {
let mut page_helper = PageObjectHelper::new(page_ref, pdf);
page_helper.get_annotations()?
};
let mut result = Vec::with_capacity(annot_refs.len());
for annot_ref in annot_refs {
let (subtype, rect) = {
let mut annot_helper = AnnotationObjectHelper::new(annot_ref, pdf);
let subtype = annot_helper.subtype()?;
let rect = annot_helper.rect()?;
(subtype, rect)
};
let is_widget = subtype.as_deref().is_some_and(|s| s == b"Widget");
let field_ref = if is_widget {
find_field_ref(pdf, annot_ref)?
} else {
None
};
result.push(EnumeratedAnnotation {
annot_ref,
subtype,
rect,
is_widget,
field_ref,
});
}
Ok(result)
}
pub fn enumerate_document_annotations<R: Read + Seek>(
pdf: &mut Pdf<R>,
) -> Result<Vec<(ObjectRef, Vec<EnumeratedAnnotation>)>> {
let page_refs = crate::pages::page_refs(pdf)?;
let mut out = Vec::with_capacity(page_refs.len());
for page_ref in page_refs {
let annots = enumerate_page_annotations(pdf, page_ref)?;
out.push((page_ref, annots));
}
Ok(out)
}
fn find_field_ref<R: Read + Seek>(pdf: &mut Pdf<R>, start: ObjectRef) -> Result<Option<ObjectRef>> {
let node = pdf.resolve_borrowed(start)?;
let Some(dict) = node.as_dict() else {
return Ok(None);
};
if matches!(dict.get("FT"), Some(v) if !matches!(v, Object::Null))
|| matches!(dict.get("T"), Some(v) if !matches!(v, Object::Null))
{
return Ok(Some(start));
}
match dict.get("Parent") {
Some(Object::Reference(parent_ref)) => Ok(Some(*parent_ref)),
_ => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ObjectRef, Pdf};
use std::io::Cursor;
fn build_pdf(annots_entry: Option<&str>, extra_objects: &[(u32, &[u8])]) -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len() as u64;
let page_body = match annots_entry {
None => "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n"
.to_string(),
Some(annots) => format!(
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Annots {annots} >>\nendobj\n"
),
};
pdf.extend_from_slice(page_body.as_bytes());
let mut extra_offsets: Vec<(u32, u64)> = Vec::new();
for &(num, body) in extra_objects.iter() {
let off = pdf.len() as u64;
extra_offsets.push((num, off));
pdf.extend_from_slice(body);
}
let xref_start = pdf.len() as u64;
let max_num = extra_offsets.iter().map(|(n, _)| *n).max().unwrap_or(3);
let total = max_num as usize + 1;
let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
xref.push_str(&format!("{:010} 00000 n \n", off1));
xref.push_str(&format!("{:010} 00000 n \n", off2));
xref.push_str(&format!("{:010} 00000 n \n", off3));
for i in 4u32..=max_num {
if let Some((_, off)) = extra_offsets.iter().find(|(n, _)| *n == i) {
xref.push_str(&format!("{:010} 00000 n \n", off));
} else {
xref.push_str("0000000000 65535 f \n");
}
}
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
#[test]
fn no_annots_returns_empty_vec() {
let bytes = build_pdf(None, &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let result = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert!(result.is_empty());
}
#[test]
fn mixed_subtypes_are_classified_and_ordered() {
let obj4: &[u8] =
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /Rect [10 20 100 30] /FT /Tx >>\nendobj\n";
let obj5: &[u8] =
b"5 0 obj\n<< /Type /Annot /Subtype /Link /Rect [0 0 100 20] >>\nendobj\n";
let obj6: &[u8] = b"6 0 obj\n<< /Type /Annot /Subtype /Text >>\nendobj\n";
let bytes = build_pdf(
Some("[4 0 R 5 0 R 6 0 R]"),
&[(4, obj4), (5, obj5), (6, obj6)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots.len(), 3);
assert_eq!(annots[0].annot_ref, ObjectRef::new(4, 0));
assert_eq!(annots[0].subtype.as_deref(), Some(b"Widget" as &[u8]));
assert!(annots[0].is_widget);
assert_eq!(annots[0].field_ref, Some(ObjectRef::new(4, 0)));
assert_eq!(annots[0].rect, Some(PageBox::new(10.0, 20.0, 100.0, 30.0)));
assert_eq!(annots[1].annot_ref, ObjectRef::new(5, 0));
assert_eq!(annots[1].subtype.as_deref(), Some(b"Link" as &[u8]));
assert!(!annots[1].is_widget);
assert_eq!(annots[1].field_ref, None);
assert_eq!(annots[2].annot_ref, ObjectRef::new(6, 0));
assert_eq!(annots[2].subtype.as_deref(), Some(b"Text" as &[u8]));
assert!(!annots[2].is_widget);
assert_eq!(annots[2].field_ref, None);
assert_eq!(annots[2].rect, None);
}
#[test]
fn merged_widget_field_ref_is_annot_itself() {
let obj4: &[u8] =
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /FT /Tx >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots.len(), 1);
let a = &annots[0];
assert!(a.is_widget);
assert_eq!(a.field_ref, Some(ObjectRef::new(4, 0)));
}
#[test]
fn separated_widget_field_ref_is_parent_field() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 100 20] /Parent 5 0 R >>\nendobj\n";
let obj5: &[u8] =
b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (myfield) >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4), (5, obj5)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots.len(), 1);
let a = &annots[0];
assert!(a.is_widget);
assert_eq!(a.field_ref, Some(ObjectRef::new(5, 0)));
}
#[test]
fn merged_fields_inheriting_ft_are_not_aggregated_to_ancestor() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 100 20] /T (field0) /Parent 5 0 R >>\nendobj\n";
let obj5: &[u8] = b"5 0 obj\n<< /FT /Tx /T (group) /Kids [4 0 R 6 0 R] >>\nendobj\n";
let obj6: &[u8] = b"6 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 30 100 50] /T (field1) /Parent 5 0 R >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R 6 0 R]"), &[(4, obj4), (5, obj5), (6, obj6)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots.len(), 2);
assert_eq!(annots[0].field_ref, Some(ObjectRef::new(4, 0)));
assert_eq!(annots[1].field_ref, Some(ObjectRef::new(6, 0)));
}
#[test]
fn owning_field_is_direct_parent_not_ft_ancestor() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 100 20] /Parent 5 0 R >>\nendobj\n";
let obj5: &[u8] = b"5 0 obj\n<< /Parent 6 0 R /T (option1) >>\nendobj\n";
let obj6: &[u8] = b"6 0 obj\n<< /FT /Btn /T (radio) >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4), (5, obj5), (6, obj6)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
let a = &annots[0];
assert!(a.is_widget);
assert_eq!(a.field_ref, Some(ObjectRef::new(5, 0)));
}
#[test]
fn sibling_terminal_fields_are_distinct() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 50 20] /Parent 6 0 R >>\nendobj\n";
let obj5: &[u8] = b"5 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [60 0 110 20] /Parent 7 0 R >>\nendobj\n";
let obj6: &[u8] = b"6 0 obj\n<< /Parent 8 0 R /T (a) >>\nendobj\n";
let obj7: &[u8] = b"7 0 obj\n<< /Parent 8 0 R /T (b) >>\nendobj\n";
let obj8: &[u8] = b"8 0 obj\n<< /FT /Btn /T (group) >>\nendobj\n";
let bytes = build_pdf(
Some("[4 0 R 5 0 R]"),
&[(4, obj4), (5, obj5), (6, obj6), (7, obj7), (8, obj8)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annots = enumerate_page_annotations(&mut pdf, ObjectRef::new(3, 0)).unwrap();
assert_eq!(annots[0].field_ref, Some(ObjectRef::new(6, 0)));
assert_eq!(annots[1].field_ref, Some(ObjectRef::new(7, 0)));
assert_ne!(annots[0].field_ref, annots[1].field_ref);
}
#[test]
fn link_annotation_has_no_field_ref() {
let obj4: &[u8] =
b"4 0 obj\n<< /Type /Annot /Subtype /Link /Rect [0 0 200 40] >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots.len(), 1);
let a = &annots[0];
assert!(!a.is_widget);
assert_eq!(a.field_ref, None);
}
#[test]
fn orphan_widget_field_ref_is_none() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 100 20] >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
let a = &annots[0];
assert!(a.is_widget);
assert_eq!(a.field_ref, None);
}
#[test]
fn cyclic_parent_chain_terminates() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 100 20] /Parent 5 0 R >>\nendobj\n";
let obj5: &[u8] = b"5 0 obj\n<< /Parent 4 0 R >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4), (5, obj5)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots.len(), 1);
let a = &annots[0];
assert!(a.is_widget);
assert_eq!(a.field_ref, Some(ObjectRef::new(5, 0)));
}
#[test]
fn rect_is_resolved_correctly() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Text \
/Rect [10 20 300 400] >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert_eq!(annots[0].rect, Some(PageBox::new(10.0, 20.0, 300.0, 400.0)));
}
#[test]
fn widget_parent_without_ft_returns_direct_parent() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Widget \
/Rect [0 0 100 20] /Parent 5 0 R >>\nendobj\n";
let obj5: &[u8] = b"5 0 obj\n<< /T (noFT) >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4), (5, obj5)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
let a = &annots[0];
assert!(a.is_widget);
assert_eq!(a.field_ref, Some(ObjectRef::new(5, 0)));
}
#[test]
fn enumerate_document_annotations_covers_all_pages() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Text >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let result = enumerate_document_annotations(&mut pdf).unwrap();
assert_eq!(result.len(), 1);
let (pref, annots) = &result[0];
assert_eq!(*pref, ObjectRef::new(3, 0));
assert_eq!(annots.len(), 1);
assert_eq!(annots[0].subtype.as_deref(), Some(b"Text" as &[u8]));
}
#[test]
fn empty_annots_array_returns_empty_vec() {
let bytes = build_pdf(Some("[]"), &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let result = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
assert!(result.is_empty());
}
#[test]
fn enumerated_annotation_clone_and_eq() {
let a = EnumeratedAnnotation {
annot_ref: ObjectRef::new(4, 0),
subtype: Some(b"Widget".to_vec()),
rect: Some(PageBox::new(0.0, 0.0, 100.0, 20.0)),
is_widget: true,
field_ref: Some(ObjectRef::new(4, 0)),
};
let b = a.clone();
assert_eq!(a, b);
}
#[test]
fn highlight_annotation_is_not_widget() {
let obj4: &[u8] = b"4 0 obj\n<< /Type /Annot /Subtype /Highlight \
/Rect [0 10 200 30] >>\nendobj\n";
let bytes = build_pdf(Some("[4 0 R]"), &[(4, obj4)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let annots = enumerate_page_annotations(&mut pdf, page_ref).unwrap();
let a = &annots[0];
assert_eq!(a.subtype.as_deref(), Some(b"Highlight" as &[u8]));
assert!(!a.is_widget);
assert_eq!(a.field_ref, None);
}
}