use crate::page_annotation_enum::enumerate_page_annotations;
use crate::pages::{coalesce_page_contents, page_content_bytes, resolve_inherited_resources};
use crate::{Dictionary, Error, Object, ObjectRef, Pdf, Result, Stream};
use std::io::{Read, Seek};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlattenMode {
All,
Print,
Screen,
}
const FLAG_HIDDEN: i64 = 0x2;
const FLAG_PRINT: i64 = 0x4;
const FLAG_NO_VIEW: i64 = 0x20;
pub fn flatten_annotations_on_page<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_ref: ObjectRef,
mode: FlattenMode,
) -> Result<usize> {
let all_annots = enumerate_page_annotations(pdf, page_ref)?;
struct AnnotData {
xobj_ref: ObjectRef, matrix_a: [f64; 6], }
let mut to_flatten: Vec<AnnotData> = Vec::new();
let mut to_remove: Vec<ObjectRef> = Vec::new();
for ea in &all_annots {
let flags = read_annot_flags(pdf, ea.annot_ref)?;
let hidden = (flags & FLAG_HIDDEN) != 0;
let print_bit = (flags & FLAG_PRINT) != 0;
let no_view = (flags & FLAG_NO_VIEW) != 0;
let eligible = match mode {
FlattenMode::All => !hidden,
FlattenMode::Print => print_bit && !hidden,
FlattenMode::Screen => !print_bit && !hidden && !no_view,
};
if !eligible {
continue;
}
let xobj_ref = match resolve_ap_n(pdf, ea.annot_ref)? {
Some(r) => r,
None => continue, };
let rect = match &ea.rect {
Some(r) => *r,
None => continue, };
let (rx0, rx1) = if rect.llx <= rect.urx {
(rect.llx, rect.urx)
} else {
(rect.urx, rect.llx)
};
let (ry0, ry1) = if rect.lly <= rect.ury {
(rect.lly, rect.ury)
} else {
(rect.ury, rect.lly)
};
if (rx1 - rx0).abs() < 1e-6 || (ry1 - ry0).abs() < 1e-6 {
continue;
}
let (bbox, ap_matrix) = read_xobj_bbox_and_matrix(pdf, xobj_ref)?;
let bbox = match bbox {
Some(b) => b,
None => continue, };
let corners = [
apply_matrix(ap_matrix, bbox[0], bbox[1]),
apply_matrix(ap_matrix, bbox[2], bbox[1]),
apply_matrix(ap_matrix, bbox[2], bbox[3]),
apply_matrix(ap_matrix, bbox[0], bbox[3]),
];
let tx0 = corners.iter().map(|c| c.0).fold(f64::INFINITY, f64::min);
let tx1 = corners
.iter()
.map(|c| c.0)
.fold(f64::NEG_INFINITY, f64::max);
let ty0 = corners.iter().map(|c| c.1).fold(f64::INFINITY, f64::min);
let ty1 = corners
.iter()
.map(|c| c.1)
.fold(f64::NEG_INFINITY, f64::max);
let tw = tx1 - tx0;
let th = ty1 - ty0;
if tw.abs() < 1e-10 || th.abs() < 1e-10 {
continue;
}
let sx = (rx1 - rx0) / tw;
let sy = (ry1 - ry0) / th;
let matrix_a = [sx, 0.0, 0.0, sy, rx0 - sx * tx0, ry0 - sy * ty0];
to_flatten.push(AnnotData { xobj_ref, matrix_a });
to_remove.push(ea.annot_ref);
}
if to_flatten.is_empty() {
return Ok(0);
}
coalesce_page_contents(pdf, page_ref)?;
let inherited_resources = resolve_inherited_resources(pdf, page_ref)?;
let mut resources_dict = inherited_resources.unwrap_or_default();
let mut xobj_dict: Dictionary = match resources_dict.remove("XObject") {
Some(Object::Dictionary(d)) => d,
Some(Object::Reference(r)) => match pdf.resolve(r)? {
Object::Dictionary(d) => d,
_ => Dictionary::new(),
},
_ => Dictionary::new(),
};
let mut append_bytes: Vec<u8> = Vec::new();
let mut xobj_counter: u32 = 1;
for data in &to_flatten {
let xobj_name = loop {
let candidate = format!("FlAnnot{xobj_counter}");
xobj_counter += 1;
if xobj_dict.get(candidate.as_str()).is_none() {
break candidate;
}
};
xobj_dict.insert(xobj_name.as_str(), Object::Reference(data.xobj_ref));
let cm_line = format!(
"q\n{} {} {} {} {} {} cm\n/{} Do\nQ\n",
fmt_f64(data.matrix_a[0]),
fmt_f64(data.matrix_a[1]),
fmt_f64(data.matrix_a[2]),
fmt_f64(data.matrix_a[3]),
fmt_f64(data.matrix_a[4]),
fmt_f64(data.matrix_a[5]),
xobj_name,
);
append_bytes.extend_from_slice(cm_line.as_bytes());
}
let existing_content = page_content_bytes(pdf, page_ref)?;
let mut new_content = existing_content;
if !new_content.is_empty() && new_content.last() != Some(&b'\n') {
new_content.push(b'\n');
}
new_content.extend_from_slice(&append_bytes);
let stream_ref = next_object_ref(pdf)?;
let mut sdict = Dictionary::new();
sdict.insert("Length", Object::Integer(new_content.len() as i64));
pdf.set_object(stream_ref, Object::Stream(Stream::new(sdict, new_content)));
let page_obj = pdf.resolve(page_ref)?;
let Object::Dictionary(mut page_dict) = page_obj else {
return Err(Error::Unsupported(format!(
"object {page_ref} is not a dictionary after flatten"
)));
};
page_dict.insert("Contents", Object::Reference(stream_ref));
resources_dict.insert("XObject", Object::Dictionary(xobj_dict));
page_dict.insert("Resources", Object::Dictionary(resources_dict));
let new_annots = build_pruned_annots_array(pdf, &page_dict, &to_remove)?;
page_dict.insert("Annots", Object::Array(new_annots));
pdf.set_object(page_ref, Object::Dictionary(page_dict));
Ok(to_flatten.len())
}
pub fn flatten_annotations<R: Read + Seek>(pdf: &mut Pdf<R>, mode: FlattenMode) -> Result<usize> {
let page_refs = crate::pages::page_refs(pdf)?;
let mut total = 0;
for page_ref in page_refs {
total += flatten_annotations_on_page(pdf, page_ref, mode)?;
}
Ok(total)
}
fn apply_matrix(m: [f64; 6], x: f64, y: f64) -> (f64, f64) {
(m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])
}
fn fmt_f64(v: f64) -> String {
if v.is_finite() && v == v.trunc() && v.abs() < 1e15 {
format!("{}", v as i64)
} else {
let s = format!("{v:.6}");
let trimmed = s.trim_end_matches('0').trim_end_matches('.');
trimmed.to_string()
}
}
fn read_annot_flags<R: Read + Seek>(pdf: &mut Pdf<R>, annot_ref: ObjectRef) -> Result<i64> {
let obj = pdf.resolve_borrowed(annot_ref)?;
let Some(dict) = obj.as_dict() else {
return Ok(0);
};
let flags_val = match dict.get("F").cloned() {
None | Some(Object::Null) => return Ok(0),
Some(v) => v,
};
let resolved = match flags_val {
Object::Reference(r) => pdf.resolve(r)?,
other => other,
};
Ok(resolved.as_integer().unwrap_or(0))
}
fn resolve_ap_n<R: Read + Seek>(
pdf: &mut Pdf<R>,
annot_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
let ap_val = {
let obj = pdf.resolve_borrowed(annot_ref)?;
let Some(dict) = obj.as_dict() else {
return Ok(None);
};
dict.get("AP").cloned()
};
let ap_val = match ap_val {
None | Some(Object::Null) => return Ok(None),
Some(v) => v,
};
let ap_dict: Dictionary = match ap_val {
Object::Dictionary(d) => d,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Dictionary(d) => d,
_ => return Ok(None),
},
_ => return Ok(None),
};
let n_val = match ap_dict.get("N").cloned() {
None | Some(Object::Null) => return Ok(None),
Some(v) => v,
};
let n_resolved_for_type: Object = match &n_val {
Object::Reference(r) => {
let peeked = pdf.resolve_borrowed(*r)?;
match peeked {
Object::Stream(_) => return Ok(Some(*r)), Object::Dictionary(_) => {
pdf.resolve(*r)?
}
_ => return Ok(None),
}
}
Object::Stream(_) => n_val.clone(), Object::Dictionary(_) => n_val.clone(), _ => return Ok(None),
};
match n_resolved_for_type {
Object::Stream(s) => {
let new_ref = next_object_ref(pdf)?;
pdf.set_object(new_ref, Object::Stream(s));
Ok(Some(new_ref))
}
Object::Dictionary(state_dict) => {
let as_name: Vec<u8> = {
let obj = pdf.resolve_borrowed(annot_ref)?;
let Some(adict) = obj.as_dict() else {
return Ok(None);
};
match adict.get("AS").cloned() {
Some(Object::Name(n)) => n,
Some(Object::Reference(r)) => match pdf.resolve(r)? {
Object::Name(n) => n,
_ => return Ok(None),
},
_ => return Ok(None),
}
};
let as_key = String::from_utf8_lossy(&as_name).into_owned();
match state_dict.get(as_key.as_str()).cloned() {
Some(Object::Reference(r)) => match pdf.resolve_borrowed(r)? {
Object::Stream(_) => Ok(Some(r)),
_ => Ok(None),
},
Some(Object::Stream(s)) => {
let new_ref = next_object_ref(pdf)?;
pdf.set_object(new_ref, Object::Stream(s));
Ok(Some(new_ref))
}
_ => Ok(None),
}
}
_ => Ok(None),
}
}
fn read_xobj_bbox_and_matrix<R: Read + Seek>(
pdf: &mut Pdf<R>,
xobj_ref: ObjectRef,
) -> Result<(Option<[f64; 4]>, [f64; 6])> {
let identity: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
let obj = pdf.resolve_borrowed(xobj_ref)?;
let stream_dict = match obj {
Object::Stream(s) => s.dict.clone(),
_ => return Ok((None, identity)),
};
let bbox_val = stream_dict.get("BBox").cloned();
let bbox = match bbox_val {
None | Some(Object::Null) => return Ok((None, identity)),
Some(v) => v,
};
let bbox_arr = match bbox {
Object::Array(a) => a,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Array(a) => a,
_ => return Ok((None, identity)),
},
_ => return Ok((None, identity)),
};
if bbox_arr.len() != 4 {
return Ok((None, identity));
}
let mut bbox_vals = [0.0f64; 4];
for (i, elem) in bbox_arr.iter().take(4).enumerate() {
bbox_vals[i] = match elem {
Object::Integer(n) => *n as f64,
Object::Real(r) | Object::RealLiteral { value: r, .. } => *r,
_ => return Ok((None, identity)),
};
}
let matrix_val = stream_dict.get("Matrix").cloned();
let ap_matrix = match matrix_val {
None | Some(Object::Null) => identity,
Some(Object::Array(a)) if a.len() == 6 => {
let mut m = [0.0f64; 6];
let mut valid = true;
for (i, elem) in a.iter().take(6).enumerate() {
m[i] = match elem {
Object::Integer(n) => *n as f64,
Object::Real(r) | Object::RealLiteral { value: r, .. } => *r,
_ => {
valid = false;
break;
}
};
}
if valid {
m
} else {
identity
}
}
Some(Object::Reference(r)) => match pdf.resolve(r)? {
Object::Array(a) if a.len() == 6 => {
let mut m = [0.0f64; 6];
let mut valid = true;
for (i, elem) in a.iter().take(6).enumerate() {
m[i] = match elem {
Object::Integer(n) => *n as f64,
Object::Real(r) | Object::RealLiteral { value: r, .. } => *r,
_ => {
valid = false;
break;
}
};
}
if valid {
m
} else {
identity
}
}
_ => identity,
},
_ => identity,
};
Ok((Some(bbox_vals), ap_matrix))
}
fn build_pruned_annots_array<R: Read + Seek>(
pdf: &mut Pdf<R>,
page_dict: &Dictionary,
to_remove: &[ObjectRef],
) -> Result<Vec<Object>> {
let annots_val = match page_dict.get("Annots").cloned() {
None | Some(Object::Null) => return Ok(Vec::new()),
Some(v) => v,
};
let annots_arr = match annots_val {
Object::Array(a) => a,
Object::Reference(r) => match pdf.resolve(r)? {
Object::Array(a) => a,
_ => return Ok(Vec::new()),
},
_ => return Ok(Vec::new()),
};
let pruned: Vec<Object> = annots_arr
.into_iter()
.filter(|entry| match entry {
Object::Reference(r) => !to_remove.contains(r),
_ => true, })
.collect();
Ok(pruned)
}
fn next_object_ref<R: Read + Seek>(pdf: &Pdf<R>) -> Result<ObjectRef> {
let n = pdf
.object_refs()
.iter()
.map(|r| r.number)
.max()
.unwrap_or(0)
.checked_add(1)
.ok_or_else(|| Error::Unsupported("object-number space exhausted".to_string()))?;
Ok(ObjectRef::new(n, 0))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pages::{page_content_bytes, page_refs};
use crate::writer::write_pdf;
use crate::{Object, ObjectRef, Pdf};
use std::io::Cursor;
fn build_pdf(page_extra: &str, extra_objects: &[(u32, Vec<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 = format!(
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] {page_extra} >>\nendobj\n"
);
pdf.extend_from_slice(page_body.as_bytes());
let mut extra_offsets: Vec<(u32, u64)> = Vec::new();
for &(num, ref 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
}
fn make_xobj_stream(bbox: [f64; 4], content: &[u8]) -> Vec<u8> {
let inner = format!(
"<< /Type /XObject /Subtype /Form /BBox [{} {} {} {}] /Length {} >>",
bbox[0],
bbox[1],
bbox[2],
bbox[3],
content.len()
);
let mut out = inner.into_bytes();
out.extend_from_slice(b"\nstream\n");
out.extend_from_slice(content);
out.extend_from_slice(b"\nendstream\n");
out
}
fn obj_wrap(num: u32, body: Vec<u8>) -> (u32, Vec<u8>) {
let header = format!("{num} 0 obj\n").into_bytes();
let footer = b"endobj\n".to_vec();
let mut out = header;
out.extend_from_slice(&body);
out.extend_from_slice(&footer);
(num, out)
}
fn obj_dict(num: u32, dict: &str) -> (u32, Vec<u8>) {
let body = format!("{dict}\n").into_bytes();
obj_wrap(num, body)
}
#[test]
fn flatten_widget_all_mode() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"0.5 g 0 0 100 20 re f");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1);
let page_obj = pdf.resolve_borrowed(page_ref).unwrap();
let page_dict = page_obj.as_dict().unwrap();
let resources = match page_dict.get("Resources").unwrap() {
Object::Dictionary(d) => d.clone(),
_ => panic!("Resources should be a dict"),
};
let xobj_dict = match resources.get("XObject").unwrap() {
Object::Dictionary(d) => d.clone(),
_ => panic!("XObject should be a dict"),
};
assert_eq!(xobj_dict.iter().count(), 1, "exactly one XObject entry");
let xobj_val = xobj_dict.iter().next().unwrap().1;
assert_eq!(xobj_val, &Object::Reference(ObjectRef::new(5, 0)));
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let content_str = String::from_utf8_lossy(&content);
assert!(content_str.contains("cm"), "content should contain cm");
assert!(content_str.contains("Do"), "content should contain Do");
assert!(content_str.contains('q'), "content should contain q");
assert!(content_str.contains('Q'), "content should contain Q");
let page_obj2 = pdf.resolve_borrowed(page_ref).unwrap();
let page_dict2 = page_obj2.as_dict().unwrap();
let annots = match page_dict2.get("Annots").unwrap() {
Object::Array(a) => a.clone(),
_ => panic!("Annots should be an array"),
};
assert!(annots.is_empty(), "Annots should be empty after flattening");
}
#[test]
fn placement_matrix_values() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let content_str = String::from_utf8_lossy(&content);
assert!(
content_str.contains("1 0 0 1 50 50 cm"),
"expected identity+translate matrix, got: {content_str}"
);
}
#[test]
fn print_mode_only_prints_print_bit_annotations() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body.clone());
let (n6, obj6_bytes) = obj_wrap(6, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /F 4 /AP << /N 5 0 R >> >>",
);
let (n7, obj7_bytes) = obj_dict(
7,
"<< /Type /Annot /Subtype /Widget /Rect [100 0 200 20] /F 0 /AP << /N 6 0 R >> >>",
);
let bytes = build_pdf(
"/Annots [4 0 R 7 0 R]",
&[
(n4, obj4_bytes),
(n5, obj5_bytes),
(n6, obj6_bytes),
(n7, obj7_bytes),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::Print).unwrap();
assert_eq!(
count, 1,
"only the Print-bit annotation should be flattened"
);
let page_obj = pdf.resolve_borrowed(page_ref).unwrap();
let page_dict = page_obj.as_dict().unwrap();
let annots = match page_dict.get("Annots").unwrap() {
Object::Array(a) => a.clone(),
_ => panic!("expected array"),
};
assert_eq!(annots.len(), 1, "one annotation should remain");
assert_eq!(annots[0], Object::Reference(ObjectRef::new(7, 0)));
}
#[test]
fn screen_mode_only_flattens_non_print_annotations() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body.clone());
let (n6, obj6_bytes) = obj_wrap(6, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /F 4 /AP << /N 5 0 R >> >>",
);
let (n7, obj7_bytes) = obj_dict(
7,
"<< /Type /Annot /Subtype /Widget /Rect [100 0 200 20] /F 0 /AP << /N 6 0 R >> >>",
);
let bytes = build_pdf(
"/Annots [4 0 R 7 0 R]",
&[
(n4, obj4_bytes),
(n5, obj5_bytes),
(n6, obj6_bytes),
(n7, obj7_bytes),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::Screen).unwrap();
assert_eq!(count, 1, "only the no-Print annotation should be flattened");
let page_obj = pdf.resolve_borrowed(page_ref).unwrap();
let page_dict = page_obj.as_dict().unwrap();
let annots = match page_dict.get("Annots").unwrap() {
Object::Array(a) => a.clone(),
_ => panic!("expected array"),
};
assert_eq!(annots.len(), 1);
assert_eq!(annots[0], Object::Reference(ObjectRef::new(4, 0)));
}
#[test]
fn hidden_annotation_skipped_in_all_mode() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /F 2 /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 0, "hidden annotation should be skipped");
}
#[test]
fn annotation_without_ap_is_skipped() {
let (n4, obj4_bytes) =
obj_dict(4, "<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] >>");
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 0);
}
#[test]
fn checkbox_state_dict_with_as_selection() {
let xobj_on = make_xobj_stream([0.0, 0.0, 20.0, 20.0], b"1 g 0 0 20 20 re f");
let (n5, obj5_bytes) = obj_wrap(5, xobj_on);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [10 10 30 30] \
/AS /On /AP << /N << /On 5 0 R /Off 0 0 R >> >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1, "checkbox On state should be flattened");
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let content_str = String::from_utf8_lossy(&content);
assert!(content_str.contains("Do"), "content should contain Do");
}
#[test]
fn write_pdf_round_trip_is_valid() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"0.5 g 0 0 100 20 re f");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
let mut out = Vec::new();
write_pdf(&mut pdf, &mut out).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(out)).unwrap();
let pages = page_refs(&mut pdf2).unwrap();
assert_eq!(pages.len(), 1);
let content = page_content_bytes(&mut pdf2, pages[0]).unwrap();
assert!(content.windows(2).any(|w| w == b"Do"));
}
#[test]
fn non_identity_matrix_in_xobj() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0 0 50 10] /Matrix [2 0 0 2 0 0] /Length 0 >>\nstream\n\nendstream\n";
let (n5, obj5_bytes) = obj_wrap(5, xobj_str.as_bytes().to_vec());
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let content_str = String::from_utf8_lossy(&content);
assert!(
content_str.contains("1 0 0 1 50 50 cm"),
"expected A=[1 0 0 1 50 50], got: {content_str}"
);
}
#[test]
fn multiple_annotations_flattened_count() {
let xobj_body1 = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let xobj_body2 = make_xobj_stream([0.0, 0.0, 50.0, 50.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body1);
let (n6, obj6_bytes) = obj_wrap(6, xobj_body2);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /AP << /N 5 0 R >> >>",
);
let (n7, obj7_bytes) = obj_dict(
7,
"<< /Type /Annot /Subtype /Widget /Rect [100 100 150 150] /AP << /N 6 0 R >> >>",
);
let bytes = build_pdf(
"/Annots [4 0 R 7 0 R]",
&[
(n4, obj4_bytes),
(n5, obj5_bytes),
(n6, obj6_bytes),
(n7, obj7_bytes),
],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 2);
let page_obj = pdf.resolve_borrowed(page_ref).unwrap();
let page_dict = page_obj.as_dict().unwrap();
let resources = match page_dict.get("Resources").unwrap() {
Object::Dictionary(d) => d.clone(),
_ => panic!("expected dict"),
};
let xobj_dict = match resources.get("XObject").unwrap() {
Object::Dictionary(d) => d.clone(),
_ => panic!("expected dict"),
};
assert_eq!(xobj_dict.iter().count(), 2, "two XObject entries");
let annots = match page_dict.get("Annots").unwrap() {
Object::Array(a) => a.clone(),
_ => panic!("expected array"),
};
assert!(annots.is_empty());
}
#[test]
fn fmt_f64_formats_correctly() {
assert_eq!(fmt_f64(0.0), "0");
assert_eq!(fmt_f64(1.0), "1");
assert_eq!(fmt_f64(-1.0), "-1");
assert_eq!(fmt_f64(50.0), "50");
assert_eq!(fmt_f64(0.5), "0.5");
assert_eq!(fmt_f64(1.25), "1.25");
}
#[test]
fn flatten_annotations_document_level() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let count = flatten_annotations(&mut pdf, FlattenMode::All).unwrap();
assert_eq!(count, 1);
}
#[test]
fn annotation_without_rect_is_skipped() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) =
obj_dict(4, "<< /Type /Annot /Subtype /Widget /AP << /N 5 0 R >> >>");
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 0, "annotation without /Rect should be skipped");
}
#[test]
fn inverted_rect_normalized_and_flattened() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [150 70 50 50] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1, "inverted rect should be normalized and flattened");
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let content_str = String::from_utf8_lossy(&content);
assert!(content_str.contains("cm"), "content should contain cm");
}
#[test]
fn degenerate_zero_dim_rect_is_skipped() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 50 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 0, "zero-dim rect should be skipped");
}
#[test]
fn xobj_without_bbox_is_skipped() {
let no_bbox_xobj = "<< /Type /XObject /Subtype /Form /Length 0 >>\nstream\n\nendstream\n";
let (n5, obj5_bytes) = obj_wrap(5, no_bbox_xobj.as_bytes().to_vec());
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 0, "XObject without /BBox should be skipped");
}
#[test]
fn degenerate_transformed_bbox_is_skipped() {
let xobj_str = "<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix [0 0 0 0 0 0] /Length 0 >>\nstream\n\nendstream\n";
let (n5, obj5_bytes) = obj_wrap(5, xobj_str.as_bytes().to_vec());
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 0, "degenerate transformed BBox should be skipped");
}
#[test]
fn resources_xobject_as_indirect_ref() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let (n6, obj6_bytes) = obj_dict(6, "<< /ExistingEntry 5 0 R >>");
let bytes = build_pdf(
"/Annots [4 0 R] /Resources << /XObject 6 0 R >>",
&[(n4, obj4_bytes), (n5, obj5_bytes), (n6, obj6_bytes)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
assert!(
content.windows(2).any(|w| w == b"Do"),
"content should contain Do"
);
}
#[test]
fn xobj_name_collision_forces_unique_name() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf(
"/Annots [4 0 R] /Resources << /XObject << /FlAnnot1 5 0 R >> >>",
&[(n4, obj4_bytes), (n5, obj5_bytes)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
let content_str = String::from_utf8_lossy(&content);
assert!(
content_str.contains("FlAnnot2"),
"expected FlAnnot2 due to name collision, got: {content_str}"
);
}
#[test]
fn page_content_without_trailing_newline_gets_newline() {
let content_data = b"BT /F1 12 Tf 100 700 Td (hello) Tj ET"; let content_len = content_data.len();
let stream_header = format!("<< /Length {content_len} >>\nstream\n");
let mut stream_bytes = stream_header.into_bytes();
stream_bytes.extend_from_slice(content_data);
stream_bytes.extend_from_slice(b"\nendstream\n");
let (n6, obj6_bytes) = obj_wrap(6, stream_bytes);
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf(
"/Annots [4 0 R] /Contents 6 0 R",
&[(n4, obj4_bytes), (n5, obj5_bytes), (n6, obj6_bytes)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1);
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
assert!(
content.windows(2).any(|w| w == b"Do"),
"content should contain Do"
);
}
#[test]
fn screen_mode_skips_noview_annotation() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /F 32 /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::Screen).unwrap();
assert_eq!(
count, 0,
"NoView annotation should be skipped in Screen mode"
);
}
#[test]
fn print_mode_skips_hidden_annotation() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [0 0 100 20] /F 6 /AP << /N 5 0 R >> >>",
);
let bytes = build_pdf("/Annots [4 0 R]", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::Print).unwrap();
assert_eq!(
count, 0,
"Hidden+Print annotation should be skipped in Print mode"
);
}
fn build_pdf_with_stream_obj(stream_dict_str: &str, data: &[u8]) -> (Vec<u8>, ObjectRef) {
let data_len = data.len();
let header = format!("{stream_dict_str} /Length {data_len}");
let mut body = format!("<< {header} >>\nstream\n").into_bytes();
body.extend_from_slice(data);
body.extend_from_slice(b"\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, body);
let pdf_bytes = build_pdf("", &[(n4, obj4_bytes)]);
(pdf_bytes, ObjectRef::new(4, 0))
}
#[test]
fn read_bbox_matrix_non_stream_object_returns_none_bbox() {
let (n4, obj4_bytes) = obj_dict(4, "<< /Foo /Bar >>");
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let xobj_ref = ObjectRef::new(4, 0);
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, xobj_ref).unwrap();
assert!(bbox.is_none(), "non-stream should return None bbox");
assert_eq!(
matrix,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
"non-stream should return identity matrix"
);
}
#[test]
fn read_bbox_matrix_missing_bbox_returns_none() {
let (pdf_bytes, xobj_ref) = build_pdf_with_stream_obj("/Type /XObject /Subtype /Form", b"");
let mut pdf = Pdf::open(Cursor::new(pdf_bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, xobj_ref).unwrap();
assert!(bbox.is_none());
assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
}
#[test]
fn read_bbox_matrix_bbox_wrong_length_returns_none() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100] /Length 0 >>\nstream\n\nendstream\n";
let (n4, obj4_bytes) = obj_wrap(4, xobj_str.as_bytes().to_vec());
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_none(), "BBox with wrong length should return None");
assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
}
#[test]
fn read_bbox_matrix_bbox_with_real_values() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0.5 0.5 100.5 20.5] /Length 0 >>\nstream\n\nendstream\n";
let (n4, obj4_bytes) = obj_wrap(4, xobj_str.as_bytes().to_vec());
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some(), "real-valued BBox should succeed");
let b = bbox.unwrap();
assert!((b[0] - 0.5).abs() < 1e-10);
assert!((b[2] - 100.5).abs() < 1e-10);
assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
}
#[test]
fn read_bbox_matrix_bbox_non_numeric_element_returns_none() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0 0 /Bad 20] /Length 0 >>\nstream\n\nendstream\n";
let (n4, obj4_bytes) = obj_wrap(4, xobj_str.as_bytes().to_vec());
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, _matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(
bbox.is_none(),
"non-numeric BBox element should return None"
);
}
#[test]
fn read_bbox_matrix_matrix_with_real_values() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix [1.5 0.0 0.0 1.5 0.0 0.0] /Length 0 >>\nstream\n\nendstream\n";
let (n4, obj4_bytes) = obj_wrap(4, xobj_str.as_bytes().to_vec());
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert!((matrix[0] - 1.5).abs() < 1e-10, "matrix[0] should be 1.5");
assert!((matrix[3] - 1.5).abs() < 1e-10, "matrix[3] should be 1.5");
}
#[test]
fn read_bbox_matrix_matrix_with_non_numeric_element_falls_back_to_identity() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix [1 0 0 /Bad 0 0] /Length 0 >>\nstream\n\nendstream\n";
let (n4, obj4_bytes) = obj_wrap(4, xobj_str.as_bytes().to_vec());
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert_eq!(
matrix,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
"should fall back to identity"
);
}
#[test]
fn read_bbox_matrix_matrix_wrong_length_falls_back_to_identity() {
let xobj_str =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix [1 0 0 1 0] /Length 0 >>\nstream\n\nendstream\n";
let (n4, obj4_bytes) = obj_wrap(4, xobj_str.as_bytes().to_vec());
let bytes = build_pdf("", &[(n4, obj4_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert_eq!(
matrix,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
"wrong-length matrix falls back to identity"
);
}
#[test]
fn read_bbox_via_indirect_ref() {
let (n5, obj5_bytes) = {
let body = "[0 0 100 20]\n";
obj_wrap(5, body.as_bytes().to_vec())
};
let stream_header = "<< /Type /XObject /Subtype /Form /BBox 5 0 R /Length 0 >>";
let mut stream_body = stream_header.as_bytes().to_vec();
stream_body.extend_from_slice(b"\nstream\n\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, stream_body);
let bytes = build_pdf("", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let array_ref = ObjectRef::new(5, 0);
pdf.set_object(
array_ref,
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(100),
Object::Integer(20),
]),
);
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some(), "BBox via indirect ref should be parsed");
let b = bbox.unwrap();
assert_eq!(b[2] as i64, 100);
assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
}
#[test]
fn read_bbox_indirect_ref_non_array_returns_none() {
let stream_header = "<< /Type /XObject /Subtype /Form /BBox 5 0 R /Length 0 >>";
let mut stream_body = stream_header.as_bytes().to_vec();
stream_body.extend_from_slice(b"\nstream\n\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, stream_body);
let (n5, obj5_bytes) = obj_dict(5, "<< /NotAnArray true >>");
let bytes = build_pdf("", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_none(), "BBox ref → non-array should return None");
assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
}
#[test]
fn read_matrix_via_indirect_ref() {
let stream_header =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix 5 0 R /Length 0 >>";
let mut stream_body = stream_header.as_bytes().to_vec();
stream_body.extend_from_slice(b"\nstream\n\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, stream_body);
let (n5, obj5_bytes) = obj_dict(5, "<< /NotAnArray true >>");
let bytes = build_pdf("", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
pdf.set_object(
ObjectRef::new(5, 0),
Object::Array(vec![
Object::Real(2.0),
Object::Integer(0),
Object::Integer(0),
Object::Real(2.0),
Object::Integer(0),
Object::Integer(0),
]),
);
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert!(
(matrix[0] - 2.0).abs() < 1e-10,
"matrix[0] via indirect ref should be 2.0"
);
assert!(
(matrix[3] - 2.0).abs() < 1e-10,
"matrix[3] via indirect ref should be 2.0"
);
}
#[test]
fn read_matrix_indirect_ref_non_array_returns_identity() {
let stream_header =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix 5 0 R /Length 0 >>";
let mut stream_body = stream_header.as_bytes().to_vec();
stream_body.extend_from_slice(b"\nstream\n\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, stream_body);
let (n5, obj5_bytes) = obj_dict(5, "<< /NotAnArray true >>");
let bytes = build_pdf("", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert_eq!(
matrix,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
"non-array matrix ref → identity"
);
}
#[test]
fn read_matrix_indirect_ref_with_non_numeric_element_falls_back_to_identity() {
let stream_header =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix 5 0 R /Length 0 >>";
let mut stream_body = stream_header.as_bytes().to_vec();
stream_body.extend_from_slice(b"\nstream\n\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, stream_body);
let (n5, obj5_bytes) = obj_dict(5, "<< /NotAnArray true >>");
let bytes = build_pdf("", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
pdf.set_object(
ObjectRef::new(5, 0),
Object::Array(vec![
Object::Integer(1),
Object::Integer(0),
Object::Integer(0),
Object::Name(b"BadElement".to_vec()), Object::Integer(0),
Object::Integer(0),
]),
);
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert_eq!(
matrix,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
"bad element in matrix ref → identity"
);
}
#[test]
fn read_matrix_indirect_ref_wrong_length_returns_identity() {
let stream_header =
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Matrix 5 0 R /Length 0 >>";
let mut stream_body = stream_header.as_bytes().to_vec();
stream_body.extend_from_slice(b"\nstream\n\nendstream\n");
let (n4, obj4_bytes) = obj_wrap(4, stream_body);
let (n5, obj5_bytes) = obj_dict(5, "<< /NotAnArray true >>");
let bytes = build_pdf("", &[(n4, obj4_bytes), (n5, obj5_bytes)]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
pdf.set_object(
ObjectRef::new(5, 0),
Object::Array(vec![
Object::Integer(1),
Object::Integer(0),
Object::Integer(0),
Object::Integer(1),
]),
);
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, ObjectRef::new(4, 0)).unwrap();
assert!(bbox.is_some());
assert_eq!(
matrix,
[1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
"wrong-length matrix ref → identity"
);
}
#[test]
fn read_annot_flags_non_dict_returns_zero() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
pdf.set_object(annot_ref, Object::Integer(42));
let flags = read_annot_flags(&mut pdf, annot_ref).unwrap();
assert_eq!(flags, 0, "non-dict annot should return flags=0");
}
#[test]
fn read_annot_flags_f_as_indirect_ref() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let flag_ref = ObjectRef::new(11, 0);
pdf.set_object(flag_ref, Object::Integer(4));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
annot_dict.insert("Type", Object::Name(b"Annot".to_vec()));
annot_dict.insert("F", Object::Reference(flag_ref));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let flags = read_annot_flags(&mut pdf, annot_ref).unwrap();
assert_eq!(
flags, 4,
"/F via indirect ref should resolve to 4 (Print bit)"
);
}
#[test]
fn resolve_ap_n_non_dict_annot_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
pdf.set_object(annot_ref, Object::Integer(99));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "non-dict annot should return None");
}
#[test]
fn resolve_ap_n_ap_null_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
annot_dict.insert("AP", Object::Null);
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none());
}
#[test]
fn resolve_ap_n_ap_as_indirect_ref_to_dict() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let xobj_ref = ObjectRef::new(11, 0);
let mut xobj_dict = Dictionary::new();
xobj_dict.insert("Type", Object::Name(b"XObject".to_vec()));
xobj_dict.insert("Subtype", Object::Name(b"Form".to_vec()));
xobj_dict.insert(
"BBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(100),
Object::Integer(20),
]),
);
pdf.set_object(xobj_ref, Object::Stream(Stream::new(xobj_dict, vec![])));
let ap_dict_ref = ObjectRef::new(12, 0);
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(xobj_ref));
pdf.set_object(ap_dict_ref, Object::Dictionary(ap_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
annot_dict.insert("Type", Object::Name(b"Annot".to_vec()));
annot_dict.insert("AP", Object::Reference(ap_dict_ref));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert_eq!(
result,
Some(xobj_ref),
"/AP as indirect ref should resolve to xobj"
);
}
#[test]
fn resolve_ap_n_ap_ref_to_non_dict_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let bad_ref = ObjectRef::new(11, 0);
pdf.set_object(bad_ref, Object::Integer(42));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
annot_dict.insert("AP", Object::Reference(bad_ref));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "/AP ref → non-dict should return None");
}
#[test]
fn resolve_ap_n_ap_direct_non_dict_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
annot_dict.insert("AP", Object::Integer(99));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "non-dict /AP should return None");
}
#[test]
fn resolve_ap_n_n_null_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Null);
annot_dict.insert("AP", Object::Dictionary(ap_dict));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "/N null should return None");
}
#[test]
fn resolve_ap_n_n_ref_to_dict_selects_by_as() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let xobj_ref = ObjectRef::new(11, 0);
let mut xobj_dict = Dictionary::new();
xobj_dict.insert("Type", Object::Name(b"XObject".to_vec()));
xobj_dict.insert("Subtype", Object::Name(b"Form".to_vec()));
xobj_dict.insert(
"BBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(20),
Object::Integer(20),
]),
);
pdf.set_object(xobj_ref, Object::Stream(Stream::new(xobj_dict, vec![])));
let state_dict_ref = ObjectRef::new(12, 0);
let mut state_dict = Dictionary::new();
state_dict.insert("On", Object::Reference(xobj_ref));
pdf.set_object(state_dict_ref, Object::Dictionary(state_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(state_dict_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
annot_dict.insert("AS", Object::Name(b"On".to_vec()));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert_eq!(
result,
Some(xobj_ref),
"state dict /AS selection should return correct xobj"
);
}
#[test]
fn resolve_ap_n_n_ref_to_non_stream_non_dict_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let bad_ref = ObjectRef::new(11, 0);
pdf.set_object(bad_ref, Object::Integer(99));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(bad_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(
result.is_none(),
"/N ref → non-stream/dict should return None"
);
}
#[test]
fn resolve_ap_n_n_direct_integer_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Integer(42));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "direct integer /N should return None");
}
#[test]
fn resolve_ap_n_as_via_indirect_ref() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let xobj_ref = ObjectRef::new(11, 0);
let mut xobj_dict = Dictionary::new();
xobj_dict.insert("Type", Object::Name(b"XObject".to_vec()));
xobj_dict.insert("Subtype", Object::Name(b"Form".to_vec()));
xobj_dict.insert(
"BBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(20),
Object::Integer(20),
]),
);
pdf.set_object(xobj_ref, Object::Stream(Stream::new(xobj_dict, vec![])));
let name_ref = ObjectRef::new(13, 0);
pdf.set_object(name_ref, Object::Name(b"On".to_vec()));
let state_dict_ref = ObjectRef::new(12, 0);
let mut state_dict = Dictionary::new();
state_dict.insert("On", Object::Reference(xobj_ref));
pdf.set_object(state_dict_ref, Object::Dictionary(state_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(state_dict_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
annot_dict.insert("AS", Object::Reference(name_ref));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert_eq!(result, Some(xobj_ref), "/AS via indirect ref should work");
}
#[test]
fn resolve_ap_n_as_ref_to_non_name_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let bad_ref = ObjectRef::new(13, 0);
pdf.set_object(bad_ref, Object::Integer(42));
let state_dict_ref = ObjectRef::new(12, 0);
let mut state_dict = Dictionary::new();
state_dict.insert("On", Object::Integer(0));
pdf.set_object(state_dict_ref, Object::Dictionary(state_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(state_dict_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
annot_dict.insert("AS", Object::Reference(bad_ref));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "/AS ref → non-name should return None");
}
#[test]
fn resolve_ap_n_state_dict_as_absent_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let state_dict_ref = ObjectRef::new(12, 0);
let mut state_dict = Dictionary::new();
state_dict.insert("On", Object::Integer(0));
pdf.set_object(state_dict_ref, Object::Dictionary(state_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(state_dict_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(result.is_none(), "missing /AS should return None");
}
#[test]
fn resolve_ap_n_state_dict_entry_ref_to_non_stream_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let non_stream_ref = ObjectRef::new(11, 0);
pdf.set_object(non_stream_ref, Object::Integer(99));
let state_dict_ref = ObjectRef::new(12, 0);
let mut state_dict = Dictionary::new();
state_dict.insert("On", Object::Reference(non_stream_ref));
pdf.set_object(state_dict_ref, Object::Dictionary(state_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(state_dict_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
annot_dict.insert("AS", Object::Name(b"On".to_vec()));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(
result.is_none(),
"state entry ref → non-stream should return None"
);
}
#[test]
fn resolve_ap_n_state_dict_missing_key_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let state_dict_ref = ObjectRef::new(12, 0);
let mut state_dict = Dictionary::new();
state_dict.insert("Off", Object::Integer(0));
pdf.set_object(state_dict_ref, Object::Dictionary(state_dict));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", Object::Reference(state_dict_ref));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
annot_dict.insert("AS", Object::Name(b"On".to_vec())); pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(
result.is_none(),
"missing state dict key should return None"
);
}
#[test]
fn pruned_annots_no_annots_entry_returns_empty() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_dict = Dictionary::new();
let result = build_pruned_annots_array(&mut pdf, &page_dict, &[]).unwrap();
assert!(result.is_empty(), "no /Annots should return empty vec");
}
#[test]
fn pruned_annots_annots_as_indirect_ref_to_array() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let annot_ref = ObjectRef::new(10, 0);
let keep_ref = ObjectRef::new(11, 0);
let arr_ref = ObjectRef::new(20, 0);
pdf.set_object(
arr_ref,
Object::Array(vec![
Object::Reference(annot_ref),
Object::Reference(keep_ref),
]),
);
let mut page_dict = Dictionary::new();
page_dict.insert("Annots", Object::Reference(arr_ref));
let result = build_pruned_annots_array(&mut pdf, &page_dict, &[annot_ref]).unwrap();
assert_eq!(result.len(), 1, "one annot should be pruned");
assert_eq!(result[0], Object::Reference(keep_ref));
}
#[test]
fn pruned_annots_annots_ref_to_non_array_returns_empty() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let bad_ref = ObjectRef::new(20, 0);
pdf.set_object(bad_ref, Object::Integer(42));
let mut page_dict = Dictionary::new();
page_dict.insert("Annots", Object::Reference(bad_ref));
let result = build_pruned_annots_array(&mut pdf, &page_dict, &[]).unwrap();
assert!(result.is_empty(), "ref → non-array should return empty");
}
#[test]
fn pruned_annots_annots_direct_non_array_returns_empty() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let mut page_dict = Dictionary::new();
page_dict.insert("Annots", Object::Integer(99));
let result = build_pruned_annots_array(&mut pdf, &page_dict, &[]).unwrap();
assert!(
result.is_empty(),
"direct non-array /Annots should return empty"
);
}
#[test]
fn pruned_annots_non_ref_entries_are_kept() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let keep_ref = ObjectRef::new(11, 0);
let remove_ref = ObjectRef::new(10, 0);
let mut page_dict = Dictionary::new();
page_dict.insert(
"Annots",
Object::Array(vec![
Object::Reference(remove_ref),
Object::Integer(42), Object::Reference(keep_ref),
]),
);
let result = build_pruned_annots_array(&mut pdf, &page_dict, &[remove_ref]).unwrap();
assert_eq!(result.len(), 2, "non-ref entries should be kept");
assert_eq!(result[0], Object::Integer(42));
assert_eq!(result[1], Object::Reference(keep_ref));
}
#[test]
fn resolve_ap_n_direct_stream_materializes() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let mut xobj_dict = Dictionary::new();
xobj_dict.insert("Type", Object::Name(b"XObject".to_vec()));
xobj_dict.insert("Subtype", Object::Name(b"Form".to_vec()));
xobj_dict.insert(
"BBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(100),
Object::Integer(20),
]),
);
let inline_stream = Object::Stream(Stream::new(xobj_dict, b"q Q".to_vec()));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
ap_dict.insert("N", inline_stream);
annot_dict.insert("AP", Object::Dictionary(ap_dict));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(
result.is_some(),
"direct stream /N should be materialized and returned"
);
}
#[test]
fn resolve_ap_n_state_dict_direct_stream_entry_materializes() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let mut xobj_dict = Dictionary::new();
xobj_dict.insert("Type", Object::Name(b"XObject".to_vec()));
xobj_dict.insert("Subtype", Object::Name(b"Form".to_vec()));
xobj_dict.insert(
"BBox",
Object::Array(vec![
Object::Integer(0),
Object::Integer(0),
Object::Integer(20),
Object::Integer(20),
]),
);
let inline_stream = Object::Stream(Stream::new(xobj_dict, vec![]));
let annot_ref = ObjectRef::new(10, 0);
let mut annot_dict = Dictionary::new();
let mut ap_dict = Dictionary::new();
let mut state_dict = Dictionary::new();
state_dict.insert("On", inline_stream);
ap_dict.insert("N", Object::Dictionary(state_dict));
annot_dict.insert("AP", Object::Dictionary(ap_dict));
annot_dict.insert("AS", Object::Name(b"On".to_vec()));
pdf.set_object(annot_ref, Object::Dictionary(annot_dict));
let result = resolve_ap_n(&mut pdf, annot_ref).unwrap();
assert!(
result.is_some(),
"state dict direct stream entry should be materialized"
);
}
#[test]
fn resources_xobject_indirect_ref_to_non_dict_uses_empty_dict() {
let xobj_body = make_xobj_stream([0.0, 0.0, 100.0, 20.0], b"");
let (n5, obj5_bytes) = obj_wrap(5, xobj_body);
let (n4, obj4_bytes) = obj_dict(
4,
"<< /Type /Annot /Subtype /Widget /Rect [50 50 150 70] /AP << /N 5 0 R >> >>",
);
let (n6, obj6_bytes) = obj_dict(6, "42");
let bytes = build_pdf(
"/Annots [4 0 R] /Resources << /XObject 6 0 R >>",
&[(n4, obj4_bytes), (n5, obj5_bytes), (n6, obj6_bytes)],
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
pdf.set_object(ObjectRef::new(6, 0), Object::Integer(42));
let page_ref = ObjectRef::new(3, 0);
let count = flatten_annotations_on_page(&mut pdf, page_ref, FlattenMode::All).unwrap();
assert_eq!(count, 1, "should flatten even when /XObject ref → non-dict");
let content = page_content_bytes(&mut pdf, page_ref).unwrap();
assert!(content.windows(2).any(|w| w == b"Do"));
}
#[test]
fn read_bbox_direct_non_array_value_returns_none() {
let bytes = build_pdf("", &[]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let xobj_ref = ObjectRef::new(10, 0);
let mut xobj_dict = Dictionary::new();
xobj_dict.insert("Type", Object::Name(b"XObject".to_vec()));
xobj_dict.insert("Subtype", Object::Name(b"Form".to_vec()));
xobj_dict.insert("BBox", Object::Integer(99));
pdf.set_object(xobj_ref, Object::Stream(Stream::new(xobj_dict, vec![])));
let (bbox, matrix) = read_xobj_bbox_and_matrix(&mut pdf, xobj_ref).unwrap();
assert!(bbox.is_none(), "direct non-array /BBox should return None");
assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
}
#[test]
fn fmt_f64_non_integer_float() {
assert_eq!(fmt_f64(0.5), "0.5");
assert_eq!(fmt_f64(1.25), "1.25");
assert_eq!(fmt_f64(0.123456), "0.123456");
assert_eq!(fmt_f64(1.500_000), "1.5");
assert_eq!(fmt_f64(1_000_000.0), "1000000");
}
}