use crate::page_object_helper::PageObjectHelper;
#[cfg(test)]
use crate::page_object_helper::{
resolve_inherited_rotate, resolve_inherited_rotate_with_max_depth,
};
use crate::{ObjectRef, Pdf, Result};
use std::io::{Read, Seek};
pub fn flatten_rotation_on_pages<R: Read + Seek>(
pdf: &mut Pdf<R>,
pages: &[ObjectRef],
) -> Result<()> {
let acroform = crate::AcroFormDocumentHelper::new(pdf)?;
drop(acroform);
for &page_ref in pages {
let mut page = PageObjectHelper::new(page_ref, pdf);
page.flatten_rotation()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::writer::write_qpdf_to_memory;
use crate::{pages, Error, ObjectHandle, PageBox, Pdf};
use std::io::Cursor;
fn handle_to_pagebox(obj: &ObjectHandle) -> Option<PageBox> {
obj.try_is_scalar().ok()?;
let values = obj.as_array()?;
if values.len() != 4 {
return None;
}
let mut numbers = [0.0; 4];
for (index, value) in values.iter().enumerate() {
value.try_is_scalar().ok()?;
numbers[index] = value
.as_integer()
.map(|value| value as f64)
.or_else(|| value.as_real())?;
}
Some(PageBox::new(
numbers[0].min(numbers[2]),
numbers[1].min(numbers[3]),
numbers[0].max(numbers[2]),
numbers[1].max(numbers[3]),
))
}
fn object_key_handle(
pdf: &mut Pdf<Cursor<Vec<u8>>>,
object_ref: ObjectRef,
key: &[u8],
) -> ObjectHandle {
let owner = pdf.get_object_handle(object_ref);
owner.try_is_scalar().expect("object resolves");
let value = owner.try_get_key(key).unwrap();
value.try_is_scalar().expect("object key resolves");
value
}
fn pagebox_for(pdf: &mut Pdf<Cursor<Vec<u8>>>, object_ref: ObjectRef, key: &[u8]) -> PageBox {
let value = object_key_handle(pdf, object_ref, key);
handle_to_pagebox(&value).expect("page box must be a four-number array")
}
fn rotate_value(pdf: &mut Pdf<Cursor<Vec<u8>>>, page_ref: ObjectRef) -> Option<i64> {
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().expect("page resolves");
let rotate = page.try_get_key(b"/Rotate").unwrap();
rotate.try_is_scalar().expect("/Rotate resolves");
rotate.as_integer()
}
fn rotate_pages(
pdf: &mut Pdf<Cursor<Vec<u8>>>,
pages: &[ObjectRef],
degrees: i32,
relative: bool,
) -> Result<()> {
for &page_ref in pages {
PageObjectHelper::new(page_ref, pdf).rotate_page(degrees, relative)?;
}
Ok(())
}
fn rotate_key_absent(pdf: &mut Pdf<Cursor<Vec<u8>>>, page_ref: ObjectRef) -> bool {
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().expect("page resolves");
!page.try_has_key(b"/Rotate").unwrap()
}
#[test]
fn handle_to_pagebox_rejects_bad_shapes_and_accepts_real_literals() {
assert!(handle_to_pagebox(&ObjectHandle::integer(1)).is_none());
assert!(handle_to_pagebox(&ObjectHandle::array(vec![ObjectHandle::integer(1)])).is_none());
assert_eq!(
handle_to_pagebox(&ObjectHandle::array(vec![
ObjectHandle::real_literal(1.5, b"1.5".to_vec()),
ObjectHandle::integer(2),
ObjectHandle::real(11.5),
ObjectHandle::integer(22),
])),
Some(PageBox::new(1.5, 2.0, 11.5, 22.0))
);
assert!(handle_to_pagebox(&ObjectHandle::array(vec![
ObjectHandle::integer(1),
ObjectHandle::null(),
ObjectHandle::integer(11),
ObjectHandle::integer(22),
]))
.is_none());
}
#[test]
fn handle_to_pagebox_resolves_indirect_numeric_items() {
let bytes = assemble_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_owned()),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_owned()),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [1 4 0 R 3 4] >>".to_owned(),
),
(4, "7".to_owned()),
]);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
let media_box = object_key_handle(&mut pdf, page, b"/MediaBox");
assert_eq!(
handle_to_pagebox(&media_box),
Some(PageBox::new(1.0, 4.0, 3.0, 7.0))
);
}
fn build_single_page_pdf(page_rotate: Option<i32>, parent_rotate: Option<i32>) -> 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;
let pages_str = if let Some(r) = parent_rotate {
format!("2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 /Rotate {r} >>\nendobj\n")
} else {
"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n".to_string()
};
pdf.extend_from_slice(pages_str.as_bytes());
let off3 = pdf.len() as u64;
let page_str = if let Some(r) = page_rotate {
format!(
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Rotate {r} >>\nendobj\n"
)
} else {
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
};
pdf.extend_from_slice(page_str.as_bytes());
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
#[test]
fn resolve_page_has_direct_rotate() {
let bytes = build_single_page_pdf(Some(90), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
assert_eq!(resolve_inherited_rotate(&mut pdf, page_ref).unwrap(), 90);
}
#[test]
fn resolve_inherits_from_parent() {
let bytes = build_single_page_pdf(None, Some(180));
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
assert_eq!(resolve_inherited_rotate(&mut pdf, page_ref).unwrap(), 180);
}
#[test]
fn resolve_defaults_to_zero_when_absent() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
assert_eq!(resolve_inherited_rotate(&mut pdf, page_ref).unwrap(), 0);
}
#[test]
fn resolve_defaults_to_zero_for_a_parent_cycle() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let parent = pdf.get_object_handle(ObjectRef::new(2, 0));
parent.try_is_scalar().unwrap();
let page = pdf.get_object_handle(ObjectRef::new(3, 0));
parent
.replace_key(b"/Parent", page)
.expect("parent must be mutable");
assert_eq!(
resolve_inherited_rotate(&mut pdf, ObjectRef::new(3, 0)).unwrap(),
0
);
}
#[test]
fn resolve_defaults_to_zero_for_a_non_dictionary_parent() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pdf.get_object_handle(ObjectRef::new(3, 0));
page.try_is_scalar().unwrap();
page.replace_key(b"/Parent", ObjectHandle::integer(42))
.expect("page must be mutable");
assert_eq!(
resolve_inherited_rotate(&mut pdf, ObjectRef::new(3, 0)).unwrap(),
0
);
}
#[test]
fn resolve_preserves_non_standard_value() {
let bytes = build_single_page_pdf(Some(45), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
assert_eq!(resolve_inherited_rotate(&mut pdf, page_ref).unwrap(), 45);
}
#[test]
fn resolve_reports_depth_limit_at_a_direct_page_tree_node() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().unwrap();
let parent =
ObjectHandle::dictionary(vec![(b"/Rotate".to_vec(), ObjectHandle::integer(90))]);
page.replace_key(b"/Parent", parent)
.expect("page must be mutable");
let error = resolve_inherited_rotate_with_max_depth(&mut pdf, page_ref, 1).unwrap_err();
assert!(matches!(
error,
Error::Unsupported(message)
if message.contains("page tree depth exceeds maximum of 1")
&& message.contains("direct page-tree dictionary")
));
}
#[test]
fn resolve_rejects_a_non_integer_rotate_entry() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().unwrap();
page.replace_key(b"/Rotate", ObjectHandle::name(b"Bad".to_vec()))
.expect("page must be mutable");
let error = resolve_inherited_rotate(&mut pdf, page_ref).unwrap_err();
assert!(matches!(
error,
Error::Unsupported(message) if message.contains("/Rotate entry")
&& message.contains("has unexpected type")
));
}
#[test]
fn rotate_page_rejects_a_non_multiple_angle_like_qpdf() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let error = PageObjectHelper::new(ObjectRef::new(3, 0), &mut pdf)
.rotate_page(45, false)
.expect_err("qpdf rejects direct rotation angles that are not multiples of 90");
assert!(matches!(
error,
Error::System(message)
if message.contains("angle that is not a multiple of 90")
));
}
#[test]
fn assign_replaces_existing_rotate() {
let bytes = build_single_page_pdf(Some(90), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 180, false).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(180));
}
#[test]
fn add_accumulates_onto_direct_rotate() {
let bytes = build_single_page_pdf(Some(90), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(180));
}
#[test]
fn add_wraps_at_360() {
let bytes = build_single_page_pdf(Some(270), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(0));
}
#[test]
fn add_ignores_non_quarter_turn_existing_rotate_like_qpdf() {
let bytes = build_single_page_pdf(Some(45), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(90));
}
#[test]
fn add_clamps_an_out_of_i32_range_existing_rotate_like_qpdf() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().unwrap();
page.replace_key(b"/Rotate", ObjectHandle::integer(2_147_483_700))
.expect("page must be mutable");
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(90));
}
#[test]
fn add_clamps_a_below_i32_range_existing_rotate_like_qpdf() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().unwrap();
page.replace_key(b"/Rotate", ObjectHandle::integer(-2_147_483_700))
.expect("page must be mutable");
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(90));
}
#[test]
fn add_clamps_a_near_i64_max_existing_rotate_without_overflow() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().unwrap();
page.replace_key(b"/Rotate", ObjectHandle::integer(9_223_372_036_854_775_800))
.expect("page must be mutable");
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(90));
}
#[test]
fn inherited_rotate_is_materialized_on_leaf() {
let bytes = build_single_page_pdf(None, Some(90));
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 180, false).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(180));
}
#[test]
fn add_with_inherited_rotate_materializes_combined() {
let bytes = build_single_page_pdf(None, Some(90));
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(180));
}
#[test]
fn assign_zero_materializes_zero_explicitly() {
let bytes = build_single_page_pdf(None, None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 0, false).unwrap();
assert_eq!(rotate_value(&mut pdf, page_ref), Some(0));
}
#[test]
fn apply_to_empty_slice_is_noop() {
let bytes = build_single_page_pdf(Some(90), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
rotate_pages(&mut pdf, &[], 270, false).unwrap();
assert_eq!(rotate_value(&mut pdf, ObjectRef::new(3, 0)), Some(90));
}
#[test]
fn round_trip_rotate_preserved_after_write_reopen() {
let bytes = build_single_page_pdf(Some(90), None);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_ref = ObjectRef::new(3, 0);
rotate_pages(&mut pdf, &[page_ref], 270, false).unwrap();
let out = write_qpdf_to_memory(&mut pdf, |_| {}).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(out)).unwrap();
let page_refs = pages::page_refs(&mut pdf2).unwrap();
assert_eq!(page_refs.len(), 1);
assert_eq!(
rotate_value(&mut pdf2, page_refs[0]),
Some(270),
"expected /Rotate 270 explicitly on leaf after round-trip"
);
}
#[test]
fn round_trip_inherited_rotate_materialized_on_leaf() {
let bytes = build_single_page_pdf(None, Some(180));
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page_refs_before = pages::page_refs(&mut pdf).unwrap();
let page_ref = page_refs_before[0];
rotate_pages(&mut pdf, &[page_ref], 90, true).unwrap();
let out = write_qpdf_to_memory(&mut pdf, |_| {}).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(out)).unwrap();
let page_refs2 = pages::page_refs(&mut pdf2).unwrap();
assert_eq!(
rotate_value(&mut pdf2, page_refs2[0]),
Some(270),
"expected inherited+add materialized on leaf"
);
}
fn build_two_page_pdf(page1_rotate: Option<i32>, page2_rotate: Option<i32>) -> 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 4 0 R] /Count 2 >>\nendobj\n",
);
let off3 = pdf.len() as u64;
let page1_str = if let Some(r) = page1_rotate {
format!(
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Rotate {r} >>\nendobj\n"
)
} else {
"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
};
pdf.extend_from_slice(page1_str.as_bytes());
let off4 = pdf.len() as u64;
let page2_str = if let Some(r) = page2_rotate {
format!(
"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Rotate {r} >>\nendobj\n"
)
} else {
"4 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_string()
};
pdf.extend_from_slice(page2_str.as_bytes());
let xref_start = pdf.len() as u64;
let xref = format!(
"xref\n0 5\n0000000000 65535 f \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n{:010} 00000 n \n",
off1, off2, off3, off4,
);
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
#[test]
fn apply_to_multiple_pages_each_updated_independently() {
let bytes = build_two_page_pdf(Some(90), Some(0));
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page1 = ObjectRef::new(3, 0);
let page2 = ObjectRef::new(4, 0);
rotate_pages(&mut pdf, &[page1, page2], 90, true).unwrap();
assert_eq!(rotate_value(&mut pdf, page1), Some(180), "page 1");
assert_eq!(rotate_value(&mut pdf, page2), Some(90), "page 2");
}
fn assemble_pdf(objs: &[(u32, String)]) -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let mut offsets = Vec::with_capacity(objs.len());
for (num, body) in objs {
offsets.push(pdf.len() as u64);
pdf.extend_from_slice(format!("{num} 0 obj\n").as_bytes());
pdf.extend_from_slice(body.as_bytes());
pdf.extend_from_slice(b"\nendobj\n");
}
let n = objs.len() as u32 + 1;
let xref_start = pdf.len() as u64;
let mut xref = format!("xref\n0 {n}\n0000000000 65535 f \n");
for off in &offsets {
xref.push_str(&format!("{off:010} 00000 n \n"));
}
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size {n} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn content_obj_body(content: &str) -> String {
format!(
"<< /Length {} >>\nstream\n{}\nendstream",
content.len(),
content
)
}
fn build_single_page_with_content(mb: &str, rotate: Option<i32>, content: &str) -> Vec<u8> {
build_single_page_with_extra(mb, rotate, content, "")
}
fn build_single_page_with_extra(
mb: &str,
rotate: Option<i32>,
content: &str,
extra: &str,
) -> Vec<u8> {
let rotate_entry = match rotate {
Some(r) => format!(" /Rotate {r}"),
None => String::new(),
};
let page = format!(
"<< /Type /Page /Parent 2 0 R /MediaBox {mb} /Contents 4 0 R{rotate_entry} {extra} >>"
);
assemble_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string()),
(3, page),
(4, content_obj_body(content)),
])
}
fn build_single_page_inherited_rotate(parent_rotate: i32) -> Vec<u8> {
assemble_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
(
2,
format!("<< /Type /Pages /Kids [3 0 R] /Count 1 /Rotate {parent_rotate} >>"),
),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Contents 4 0 R >>"
.to_string(),
),
(4, content_obj_body("BT (x) Tj ET")),
])
}
#[test]
fn flatten_90_swaps_mediabox_zeroes_rotate_and_wraps_content() {
let bytes = build_single_page_with_content("[0 0 200 300]", Some(90), "BT (x) Tj ET");
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
assert!(rotate_key_absent(&mut pdf, page));
let mb = pagebox_for(&mut pdf, page, b"/MediaBox");
assert_eq!((mb.urx - mb.llx, mb.ury - mb.lly), (300.0, 200.0));
let content = pages::page_content_bytes(&mut pdf, page).unwrap();
let s = String::from_utf8(content).unwrap();
assert!(s.starts_with("q\n0 -1 1 0 0 200 cm\n"), "{s:?}");
assert!(s.contains("BT (x) Tj ET"), "{s:?}");
let buf = write_qpdf_to_memory(&mut pdf, |_| {}).unwrap();
let mut pdf2 = Pdf::open(Cursor::new(buf)).unwrap();
let p2 = pages::page_refs(&mut pdf2).unwrap()[0];
assert!(rotate_key_absent(&mut pdf2, p2));
}
#[test]
fn flatten_is_noop_when_rotate_zero() {
let bytes = build_single_page_with_content("[0 0 200 300]", None, "BT (x) Tj ET");
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
let before = pages::page_content_bytes(&mut pdf, page).unwrap();
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
let after = pages::page_content_bytes(&mut pdf, page).unwrap();
assert_eq!(before, after, "content must be untouched when rotate==0");
let mb = pagebox_for(&mut pdf, page, b"/MediaBox");
assert_eq!((mb.urx, mb.ury), (200.0, 300.0));
}
#[test]
fn flatten_180_keeps_mediabox_dims_and_zeroes_rotate() {
let bytes = build_single_page_with_content("[0 0 200 300]", Some(180), "BT (x) Tj ET");
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
assert!(rotate_key_absent(&mut pdf, page));
let mb = pagebox_for(&mut pdf, page, b"/MediaBox");
assert_eq!((mb.llx, mb.lly, mb.urx, mb.ury), (0.0, 0.0, 200.0, 300.0));
let content = pages::page_content_bytes(&mut pdf, page).unwrap();
let s = String::from_utf8(content).unwrap();
assert!(s.starts_with("q\n-1 0 0 -1 200 300 cm\n"), "{s:?}");
}
#[test]
fn flatten_transforms_cropbox_present_on_leaf() {
let bytes = build_single_page_with_extra(
"[0 0 200 300]",
Some(90),
"BT (x) Tj ET",
"/CropBox [10 10 190 290]",
);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
let cb = pagebox_for(&mut pdf, page, b"/CropBox");
assert_eq!((cb.llx, cb.lly, cb.urx, cb.ury), (10.0, 10.0, 290.0, 190.0));
let mb = pagebox_for(&mut pdf, page, b"/MediaBox");
assert_eq!((mb.urx - mb.llx, mb.ury - mb.lly), (300.0, 200.0));
}
fn build_single_page_with_annot(mb: &str, rotate: i32, rect: &str) -> Vec<u8> {
let page = format!(
"<< /Type /Page /Parent 2 0 R /MediaBox {mb} /Contents 4 0 R /Rotate {rotate} /Annots [5 0 R] >>"
);
assemble_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string()),
(3, page),
(4, content_obj_body("BT (x) Tj ET")),
(5, format!("<< /Type /Annot /Subtype /Text /Rect {rect} >>")),
])
}
fn build_single_page_with_direct_and_indirect_annots() -> Vec<u8> {
assemble_pdf(&[
(
1,
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
),
(
2,
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Contents 4 0 R /Rotate 90 /Annots [<< /Type /Annot /Subtype /Text /Rect [10 20 60 40] >> 5 0 R] >>".to_string(),
),
(4, content_obj_body("BT (x) Tj ET")),
(
5,
"<< /Type /Annot /Subtype /Text /Rect [20 30 70 50] >>".to_string(),
),
])
}
#[test]
fn flatten_transforms_annotation_rect() {
let bytes = build_single_page_with_annot("[0 0 200 300]", 90, "[10 20 60 40]");
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
let mut page_helper = PageObjectHelper::new(page, &mut pdf);
let annotations = page_helper
.get_annotation_handles(None)
.expect("flattened annotation must remain on the page");
assert_eq!(annotations.len(), 1);
let annotation = &annotations[0];
annotation.try_is_scalar().unwrap();
let rect = annotation.try_get_key(b"/Rect").unwrap();
rect.try_is_scalar().unwrap();
let r = handle_to_pagebox(&rect).expect("annotation rectangle");
assert_eq!((r.llx, r.lly, r.urx, r.ury), (20.0, 140.0, 40.0, 190.0));
}
#[test]
fn flatten_transforms_direct_and_indirect_annotation_rects() {
let bytes = build_single_page_with_direct_and_indirect_annots();
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
let indirect_annot = ObjectRef::new(5, 0);
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
let page_handle = pdf.get_object_handle(page);
page_handle.try_is_scalar().unwrap();
let annots_handle = page_handle.try_get_key(b"/Annots").unwrap();
annots_handle.try_is_scalar().unwrap();
let annots = annots_handle
.as_array()
.expect("/Annots must remain an array");
let mut rects = annots
.iter()
.map(|annotation| {
annotation.try_is_scalar().unwrap();
let rect = annotation.try_get_key(b"/Rect").unwrap();
rect.try_is_scalar().unwrap();
let rectangle = handle_to_pagebox(&rect).expect("annotation rectangle");
(rectangle.llx, rectangle.lly, rectangle.urx, rectangle.ury)
})
.collect::<Vec<_>>();
rects.sort_by(|left, right| left.partial_cmp(right).unwrap());
assert_eq!(
rects,
vec![(20.0, 140.0, 40.0, 190.0), (30.0, 130.0, 50.0, 180.0)]
);
let original = object_key_handle(&mut pdf, indirect_annot, b"/Rect");
assert_eq!(
handle_to_pagebox(&original),
Some(PageBox::new(20.0, 30.0, 70.0, 50.0))
);
}
fn build_single_page_indirect_annots(mb: &str, rotate: i32, rect: &str) -> Vec<u8> {
let page = format!(
"<< /Type /Page /Parent 2 0 R /MediaBox {mb} /Contents 4 0 R /Rotate {rotate} /Annots 6 0 R >>"
);
assemble_pdf(&[
(1, "<< /Type /Catalog /Pages 2 0 R >>".to_string()),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string()),
(3, page),
(4, content_obj_body("BT (x) Tj ET")),
(5, format!("<< /Type /Annot /Subtype /Text /Rect {rect} >>")),
(6, "[5 0 R]".to_string()),
])
}
#[test]
fn flatten_transforms_annotation_rect_via_indirect_annots() {
let bytes = build_single_page_indirect_annots("[0 0 200 300]", 90, "[10 20 60 40]");
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
let mut page_helper = PageObjectHelper::new(page, &mut pdf);
let annotations = page_helper
.get_annotation_handles(None)
.expect("flattened annotation must be indirect");
assert_eq!(annotations.len(), 1);
let annotation = &annotations[0];
annotation.try_is_scalar().unwrap();
let rect = annotation.try_get_key(b"/Rect").unwrap();
rect.try_is_scalar().unwrap();
let r = handle_to_pagebox(&rect).expect("annotation rectangle");
assert_eq!((r.llx, r.lly, r.urx, r.ury), (20.0, 140.0, 40.0, 190.0));
}
#[test]
fn flatten_rejects_non_leaf_target_even_when_rotate_zero() {
let bytes = build_single_page_with_content("[0 0 200 300]", None, "BT (x) Tj ET");
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let pages_node = ObjectRef::new(2, 0);
let err = flatten_rotation_on_pages(&mut pdf, &[pages_node]).unwrap_err();
assert!(
matches!(err, Error::Unsupported(_)),
"expected Unsupported, got {err:?}"
);
}
#[test]
fn flatten_does_not_materialize_inherited_rotate() {
let bytes = build_single_page_inherited_rotate(270);
let mut pdf = Pdf::open(Cursor::new(bytes)).unwrap();
let page = pages::page_refs(&mut pdf).unwrap()[0];
let before = pages::page_content_bytes(&mut pdf, page).unwrap();
flatten_rotation_on_pages(&mut pdf, &[page]).unwrap();
assert!(rotate_key_absent(&mut pdf, page));
assert_eq!(pages::page_content_bytes(&mut pdf, page).unwrap(), before);
let mb = pagebox_for(&mut pdf, page, b"/MediaBox");
assert_eq!((mb.urx - mb.llx, mb.ury - mb.lly), (200.0, 300.0));
}
}