use assert_cmd::Command;
use flpdf::{AnnotationObjectHelper, Object, Pdf};
use std::fs::File;
use std::io::BufReader;
mod common;
use common::first_widget_ref;
fn assemble_pdf(objects: &[Vec<u8>]) -> Vec<u8> {
use std::io::Write;
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::with_capacity(objects.len());
for object in objects {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
let _ = writeln!(&mut bytes, "xref\n0 {}", objects.len() + 1);
bytes.extend_from_slice(b"0000000000 65535 f \n");
for &offset in &offsets {
let _ = writeln!(&mut bytes, "{offset:010} 00000 n ");
}
let _ = writeln!(
&mut bytes,
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF",
objects.len() + 1,
start_xref
);
bytes
}
fn tx_widget_without_ap() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
.to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
/V (Hello) /DA (/Helv 12 Tf 0 g) \
/Rect [100 700 300 720] /P 3 0 R >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
fn tx_widget_with_ap() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
.to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (name1) \
/V (Hello) /DA (/Helv 12 Tf 0 g) \
/Rect [100 700 300 720] /P 3 0 R \
/AP << /N 6 0 R >> >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 200 20] \
/Length 17 >>\nstream\nBT (Hello) Tj ET\nendstream\nendobj\n"
.to_vec(),
])
}
fn checkbox_widget_without_ap() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /DR << >> >> >>\nendobj\n"
.to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (cb1) \
/Ff 0 /AS /Off \
/Rect [100 700 120 720] /P 3 0 R >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
fn radio_widget_without_ap() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /DR << >> >> >>\nendobj\n"
.to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Btn /T (rd1) \
/Ff 32768 /AS /Off \
/Rect [200 700 220 720] /P 3 0 R >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
fn combo_widget_without_ap() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /DR << >> /DA (/Helv 10 Tf 0 g) >> >>\nendobj\n"
.to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Contents 5 0 R /Annots [4 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Ch /T (combo1) \
/Ff 131072 /V (Option2) /DA (/Helv 10 Tf 0 g) \
/Rect [100 650 300 670] /P 3 0 R >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
fn two_annots_print_and_non_print() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \
/Contents 8 0 R /Annots [4 0 R 5 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (f1) \
/V (A) /F 4 /Rect [50 700 150 720] /P 3 0 R /AP << /N 6 0 R >> >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (f2) \
/V (B) /F 0 /Rect [200 700 300 720] /P 3 0 R /AP << /N 7 0 R >> >>\nendobj\n"
.to_vec(),
b"6 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] \
/Length 13 >>\nstream\nBT (A) Tj ET\nendstream\nendobj\n"
.to_vec(),
b"7 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] \
/Length 13 >>\nstream\nBT (B) Tj ET\nendstream\nendobj\n"
.to_vec(),
b"8 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
fn resolve_one<R: std::io::Read + std::io::Seek>(
pdf: &mut Pdf<R>,
obj: Object,
) -> flpdf::Result<Object> {
match obj {
Object::Reference(r) => pdf.resolve(r),
other => Ok(other),
}
}
#[test]
fn generate_appearances_tx_ap_n_contains_tj() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let n_val = {
let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("Tx widget should have /AP after --generate-appearances");
ap.get("N").cloned().expect("/AP should have /N entry")
};
let n_obj = resolve_one(&mut pdf, n_val).unwrap();
let stream = n_obj
.as_stream()
.expect("/AP/N should be a Form XObject stream");
assert!(
stream.data.windows(2).any(|w| w == b"Tj"),
"/AP/N content stream must contain Tj operator (observable: value rendered); \
stream bytes: {:?}",
std::str::from_utf8(&stream.data).unwrap_or("<non-utf8>")
);
}
#[test]
fn generate_appearances_tx_skips_existing_ap() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx_ap.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_with_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let n_val = {
let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("/AP must survive --generate-appearances for widget that already has one");
ap.get("N").cloned().expect("/AP/N must be present")
};
let n_obj = resolve_one(&mut pdf, n_val).unwrap();
let stream = n_obj.as_stream().expect("/AP/N must be a stream");
let data = &stream.data;
let as_str = std::str::from_utf8(data).unwrap_or("<non-utf8>");
assert!(
data.windows(16).any(|w| w == b"BT (Hello) Tj ET"),
"original /AP/N content must be preserved verbatim; data={as_str:?}"
);
assert!(
!data.windows(7).any(|w| w == b"/Tx BMC"),
"original /AP/N must not be replaced by a generated appearance \
(found /Tx BMC marker); data={as_str:?}"
);
assert!(
!data.windows(2).any(|w| w == b"Tf"),
"original /AP/N must not be replaced by a generated appearance \
(found Tf operator); data={as_str:?}"
);
}
#[test]
fn generate_appearances_checkbox_creates_state_dict() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("cb.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, checkbox_widget_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let n_val = {
let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("checkbox widget should have /AP after --generate-appearances");
ap.get("N").cloned().expect("/AP should have /N entry")
};
let n_obj = resolve_one(&mut pdf, n_val).unwrap();
let state_dict = n_obj
.as_dict()
.expect("/AP/N for checkbox must be a state dictionary, not a bare stream");
assert!(
state_dict.get("Off").is_some(),
"checkbox /AP/N state dict must have an 'Off' entry"
);
let has_on_state = state_dict.iter().any(|(k, _)| k != b"Off");
assert!(
has_on_state,
"checkbox /AP/N state dict must have a non-Off (on-state) entry"
);
let entry_count = state_dict.iter().count();
assert!(
entry_count >= 2,
"checkbox /AP/N state dict should have >=2 entries (on-state + Off), got {}",
entry_count
);
}
#[test]
fn generate_appearances_radio_creates_state_dict() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("rd.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, radio_widget_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let n_val = {
let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("radio widget should have /AP after --generate-appearances");
ap.get("N").cloned().expect("/AP should have /N entry")
};
let n_obj = resolve_one(&mut pdf, n_val).unwrap();
let state_dict = n_obj
.as_dict()
.expect("/AP/N for radio must be a state dictionary");
let entry_count = state_dict.iter().count();
assert!(
entry_count >= 2,
"radio /AP/N state dict should have >=2 entries, got {}",
entry_count
);
assert!(
state_dict.get("Off").is_some(),
"radio /AP/N state dict must have an 'Off' entry"
);
}
#[test]
fn generate_appearances_combo_ap_n_contains_tj() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("combo.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, combo_widget_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let n_val = {
let mut helper = AnnotationObjectHelper::new(widget_ref, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("combo widget should have /AP after --generate-appearances");
ap.get("N").cloned().expect("/AP should have /N entry")
};
let n_obj = resolve_one(&mut pdf, n_val).unwrap();
let stream = n_obj.as_stream().expect("/AP/N for combo must be a stream");
assert!(
stream.data.windows(2).any(|w| w == b"Tj"),
"combo /AP/N content stream must contain Tj (selected value rendered); \
stream={:?}",
std::str::from_utf8(&stream.data).unwrap_or("<non-utf8>")
);
}
#[test]
fn flatten_all_annot_removed_and_do_in_content() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx_ap.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_with_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--flatten-annotations=all",
"--compress-streams=n",
])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();
let annots = flpdf::enumerate_page_annotations(&mut pdf, page_refs[0]).unwrap();
assert!(
annots.is_empty(),
"flatten=all must remove widget from /Annots, found {} annotation(s)",
annots.len()
);
let content = flpdf::pages::page_content_bytes(&mut pdf, page_refs[0]).unwrap();
assert!(
content.windows(2).any(|w| w == b"Do"),
"flatten=all must insert a Do operator into page content; \
content={:?}",
std::str::from_utf8(&content).unwrap_or("<non-utf8>")
);
}
#[test]
fn generate_then_flatten_all_do_in_content() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx_no_ap.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--generate-appearances",
"--flatten-annotations=all",
"--compress-streams=n",
])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();
let annots = flpdf::enumerate_page_annotations(&mut pdf, page_refs[0]).unwrap();
assert!(
annots.is_empty(),
"generate+flatten=all must remove widget from /Annots, found {} annotation(s)",
annots.len()
);
let content = flpdf::pages::page_content_bytes(&mut pdf, page_refs[0]).unwrap();
assert!(
content.windows(2).any(|w| w == b"Do"),
"generate+flatten=all must insert Do into page content; \
content={:?}",
std::str::from_utf8(&content).unwrap_or("<non-utf8>")
);
}
#[test]
fn flatten_print_removes_print_bit_annot_only() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("two_annots.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, two_annots_print_and_non_print()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--flatten-annotations=print",
"--compress-streams=n",
])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();
let annots = flpdf::enumerate_page_annotations(&mut pdf, page_refs[0]).unwrap();
assert_eq!(
annots.len(),
1,
"flatten=print must leave exactly 1 annotation (the non-Print one), found {}",
annots.len()
);
let survivor = pdf.resolve(annots[0].annot_ref).unwrap();
let survivor_dict = survivor
.as_dict()
.expect("surviving annotation must resolve to a dictionary");
let f = survivor_dict
.get("F")
.and_then(|o| o.as_integer())
.unwrap_or(0);
assert_eq!(
f & 0x4,
0,
"surviving annotation must be the non-Print widget (Print bit clear in /F), got /F={f}"
);
let content = flpdf::pages::page_content_bytes(&mut pdf, page_refs[0]).unwrap();
assert!(
content.windows(2).any(|w| w == b"Do"),
"flatten=print must insert Do for the Print-bit annotation; \
content={:?}",
std::str::from_utf8(&content).unwrap_or("<non-utf8>")
);
}
#[test]
fn flatten_rotation_processes_all_pages() {
let input_bytes = assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec(),
b"2 0 obj\n<< /Type /Pages /Count 2 /Kids [3 0 R 5 0 R] >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /Rotate 90 \
/MediaBox [0 0 200 100] /Contents 4 0 R >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Length 14 >>\nstream\nBT (p1) Tj ET\nendstream\nendobj\n".to_vec(),
b"5 0 obj\n<< /Type /Page /Parent 2 0 R /Rotate 180 \
/MediaBox [0 0 612 792] /Contents 6 0 R >>\nendobj\n"
.to_vec(),
b"6 0 obj\n<< /Length 14 >>\nstream\nBT (p2) Tj ET\nendstream\nendobj\n".to_vec(),
]);
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("two_rotated.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, input_bytes).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--flatten-rotation", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let page_refs = flpdf::pages::page_refs(&mut pdf).unwrap();
assert_eq!(page_refs.len(), 2, "output must have 2 pages");
for (i, &page_ref) in page_refs.iter().enumerate() {
let page_obj = pdf.resolve(page_ref).unwrap();
let Object::Dictionary(dict) = page_obj else {
panic!("page {} is not a dictionary", i + 1);
};
let rotate = dict.get("Rotate").and_then(|o| o.as_integer());
assert!(
rotate.is_none() || rotate == Some(0),
"page {} /Rotate should be absent or 0 after --flatten-rotation, got {rotate:?}",
i + 1
);
}
}