use assert_cmd::Command;
use flpdf::{AnnotationObjectHelper, DecodeLevel, Pdf};
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::process::Command as ProcessCommand;
mod common;
use common::PdfCanonicalTestExt;
use common::{first_widget_ref, page_annotation_handles};
const EXPECTED_QPDF_VERSION: &str = "qpdf version 11.9.0";
fn qpdf_available() -> bool {
ProcessCommand::new("qpdf")
.arg("--version")
.output()
.map(|output| {
output.status.success()
&& String::from_utf8_lossy(&output.stdout)
.lines()
.next()
.is_some_and(|line| line.trim() == EXPECTED_QPDF_VERSION)
})
.unwrap_or(false)
}
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_without_ap_needing_appearances() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /NeedAppearances true /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_reversed_bbox() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /NeedAppearances true /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 [10 10 200 30] \
/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 100 200 0] \
/Resources <<>> /Length 4 >>\nstream\nq Q\nendstream\nendobj\n"
.to_vec(),
])
}
fn tx_widget_with_null_ap_n_needing_appearances() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /NeedAppearances true /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\nnull\nendobj\n".to_vec(),
])
}
fn tx_widget_with_ap() -> Vec<u8> {
tx_widget_with_ap_needing(false)
}
fn tx_widget_with_ap_needing_appearances() -> Vec<u8> {
tx_widget_with_ap_needing(true)
}
fn tx_widget_with_ap_needing(need_appearances: bool) -> Vec<u8> {
let acroform = if need_appearances {
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /NeedAppearances true /DR << >> /DA (/Helv 12 Tf 0 g) >> >>\nendobj\n"
.to_vec()
} else {
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()
};
assemble_pdf(&[
acroform,
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 nested_tx_widget_with_local_value() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R \
/AcroForm << /Fields [4 0 R] /NeedAppearances true \
/DR << /Font << /Helv 7 0 R >> >> /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 6 0 R /Annots [5 0 R] >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /FT /Tx /T (parent) /V (parent-value) /DA (/Helv 12 Tf 0 g) \
/Kids [5 0 R] >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Tx /T (child) \
/V (child-value) /DA (/Helv 12 Tf 0 g) /Parent 4 0 R \
/Rect [100 700 300 720] /P 3 0 R \
/AP << /N 8 0 R >> >>\nendobj\n"
.to_vec(),
b"6 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
b"7 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\nendobj\n".to_vec(),
b"8 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 200 20] \
/Resources << /ProcSet [/PDF /Text] /Font << /Helv 7 0 R >> >> \
/Length 33 >>\nstream\n/Tx BMC\nBT (old-value) Tj ET\nEMC\nendstream\nendobj\n"
.to_vec(),
])
}
fn widget_normal_appearance_data(path: &Path) -> Vec<u8> {
let mut pdf = Pdf::open(BufReader::new(File::open(path).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
helper
.get_appearance_stream(b"N", None)
.unwrap()
.get_stream_data(DecodeLevel::Generalized)
.unwrap()
.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 checkbox_widget_with_value_without_ap_needing_appearances() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /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 /V /On /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 checkbox_widget_with_ap_needing_appearances() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /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 /V /Yes /AS /Off /Rect [100 700 120 720] /P 3 0 R /AP << /N << /Off 6 0 R /Yes 7 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 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
b"7 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
])
}
fn direct_radio_widget_with_ap_needing_appearances() -> Vec<u8> {
assemble_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /NeedAppearances true /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 /V /Yes /AS /Off /Rect [100 700 120 720] /P 3 0 R /AP << /N << /Off 6 0 R /Yes 7 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 20 20] /Length 0 >>\nstream\n\nendstream\nendobj\n".to_vec(),
b"7 0 obj\n<< /Type /XObject /Subtype /Form /BBox [0 0 20 20] /Length 0 >>\nstream\n\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] /NeedAppearances true /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(),
])
}
#[test]
fn top_level_generate_appearances_routes_to_canonical_writer() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("top-level-tx.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--qdf",
"--no-original-object-ids",
"--static-id",
"--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 mut form = flpdf::AcroFormDocumentHelper::new(&mut pdf).unwrap();
assert!(!form.get_need_appearances().unwrap());
drop(form);
let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
let appearance = helper
.get_appearance_stream(b"N", None)
.unwrap()
.get_stream_data(DecodeLevel::Generalized)
.expect("top-level generation must install /AP/N");
assert!(
appearance.windows(7).any(|window| window == b"/Tx BMC"),
"top-level --qdf --generate-appearances --compress-streams=n must \
regenerate (not leave stale) the appearance content, matching \
qpdf 11.9.0's observed behavior: {}",
String::from_utf8_lossy(&appearance)
);
}
#[test]
fn top_level_generate_appearances_compress_streams_n_without_qdf_stays_stale_like_qpdf() {
if !qpdf_available() {
if std::env::var_os("CI").is_some() {
panic!("{EXPECTED_QPDF_VERSION} is required for this parity test on CI");
}
eprintln!("skipping: {EXPECTED_QPDF_VERSION} is not available");
return;
}
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("stale-ap-tx.pdf");
std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();
let read_appearance = |output: &Path| -> Vec<u8> {
let mut pdf = Pdf::open(BufReader::new(File::open(output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
helper
.get_appearance_stream(b"N", None)
.unwrap()
.get_stream_data(DecodeLevel::Generalized)
.expect("/AP/N must be present after --generate-appearances")
.to_vec()
};
let qpdf_output = temp.path().join("qpdf-out.pdf");
let qpdf = ProcessCommand::new("qpdf")
.args([
"--static-id",
"--generate-appearances",
"--compress-streams=n",
])
.arg(&input)
.arg(&qpdf_output)
.output()
.expect("qpdf 11.9.0 must be available");
assert!(qpdf.status.success(), "qpdf write failed: {qpdf:?}");
let qpdf_appearance = read_appearance(&qpdf_output);
assert!(
!qpdf_appearance
.windows(7)
.any(|window| window == b"/Tx BMC"),
"qpdf itself must leave the appearance stale (no /Tx BMC) for \
--compress-streams=n without --qdf: {}",
String::from_utf8_lossy(&qpdf_appearance)
);
assert!(
qpdf_appearance
.windows(16)
.any(|window| window == b"BT (Hello) Tj ET"),
"qpdf must preserve the pre-existing appearance content unchanged: {}",
String::from_utf8_lossy(&qpdf_appearance)
);
let flpdf_output = temp.path().join("flpdf-out.pdf");
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args([
"--static-id",
"--generate-appearances",
"--compress-streams=n",
])
.arg(&input)
.arg(&flpdf_output)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert!(flpdf.status.success(), "flpdf write failed: {flpdf:?}");
let flpdf_appearance = read_appearance(&flpdf_output);
assert_eq!(
flpdf_appearance,
qpdf_appearance,
"stale (non-regenerated) appearance content must match qpdf 11.9.0\nqpdf: {}\nflpdf: {}",
String::from_utf8_lossy(&qpdf_appearance),
String::from_utf8_lossy(&flpdf_appearance)
);
}
#[test]
fn top_level_generate_appearances_runs_before_show_object_like_qpdf() {
if !qpdf_available() {
if std::env::var_os("CI").is_some() {
panic!("{EXPECTED_QPDF_VERSION} is required for this parity test on CI");
}
eprintln!("skipping: {EXPECTED_QPDF_VERSION} is not available");
return;
}
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("inspection-tx.pdf");
std::fs::write(&input, tx_widget_without_ap_needing_appearances()).unwrap();
let qpdf = ProcessCommand::new("qpdf")
.args(["--show-object=4", "--generate-appearances"])
.arg(&input)
.output()
.expect("qpdf 11.9.0 must be available");
assert!(qpdf.status.success(), "qpdf show-object failed: {qpdf:?}");
assert!(
qpdf.stdout
.windows(b"/AP".len())
.any(|window| window == b"/AP"),
"qpdf must expose the generated normal appearance: {}",
String::from_utf8_lossy(&qpdf.stdout)
);
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-object=4", "--generate-appearances"])
.arg(&input)
.output()
.unwrap();
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"flpdf must accept the same inspection combination as qpdf"
);
assert_eq!(
flpdf.stdout,
qpdf.stdout,
"flpdf must render the transformed widget exactly like qpdf: {}",
String::from_utf8_lossy(&flpdf.stdout)
);
assert_eq!(
flpdf.stderr, qpdf.stderr,
"flpdf must preserve qpdf diagnostics for the transformed inspection"
);
}
#[test]
fn reversed_bbox_appearance_matches_qpdf_11_9_0_live() {
if !qpdf_available() {
if std::env::var_os("CI").is_some() {
panic!("{EXPECTED_QPDF_VERSION} is required for this parity test on CI");
}
eprintln!("skipping: {EXPECTED_QPDF_VERSION} is not available");
return;
}
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("reversed-bbox.pdf");
std::fs::write(&input, tx_widget_with_reversed_bbox()).unwrap();
let qpdf = ProcessCommand::new("qpdf")
.args([
"--show-object=6",
"--filtered-stream-data",
"--generate-appearances",
])
.arg(&input)
.output()
.expect("qpdf 11.9.0 must be available");
assert!(qpdf.status.success(), "qpdf show-object failed: {qpdf:?}");
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args([
"--show-object=6",
"--filtered-stream-data",
"--generate-appearances",
])
.arg(&input)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(
flpdf.stdout,
qpdf.stdout,
"reversed /BBox appearance must match qpdf 11.9.0\nqpdf: {}\nflpdf: {}",
String::from_utf8_lossy(&qpdf.stdout),
String::from_utf8_lossy(&flpdf.stdout)
);
assert_eq!(flpdf.stderr, qpdf.stderr);
}
#[test]
fn native_linearize_generate_appearances_is_accepted_like_qpdf() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("linearized-tx.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_with_ap_needing_appearances()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--linearize",
"--static-id",
"--generate-appearances",
])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(
output.is_file(),
"accepted linearized job must write output"
);
Command::cargo_bin("flpdf")
.unwrap()
.args(["check-linearization", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicates::str::contains("no linearization errors"));
}
#[test]
fn generate_appearances_without_need_marker_is_a_noop() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx-no-marker.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 mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
assert!(
helper.get_appearance_dictionary().unwrap().is_null(),
"qpdf leaves a widget without /AP unchanged when /NeedAppearances is false"
);
}
#[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_needing_appearances()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--generate-appearances",
"--stream-data=uncompress",
])
.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 mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
let n = helper.get_appearance_stream(b"N", None).unwrap();
let data = n
.get_stream_data(DecodeLevel::Generalized)
.expect("Tx widget should have /AP/N after --generate-appearances");
assert!(
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(&data).unwrap_or("<non-utf8>")
);
}
#[test]
fn generate_appearances_tx_reuses_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_needing_appearances()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=y"])
.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 mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
let n_handle = helper
.get_appearance_stream(b"N", None)
.expect("/AP must survive --generate-appearances for widget that already has one");
assert!(
n_handle.object_ref().is_some(),
"/AP/N must remain an indirect stream reference"
);
assert!(
n_handle.as_stream_dict().is_some(),
"/AP/N must be a stream"
);
let data = n_handle.get_stream_data(DecodeLevel::Generalized).unwrap();
let as_str = std::str::from_utf8(data.as_slice()).unwrap_or("<non-utf8>");
assert!(
data.windows(7).any(|w| w == b"/Tx BMC"),
"existing /AP/N must be updated through the generated-appearance path; data={as_str:?}"
);
assert!(
data.windows(2).any(|w| w == b"Tf"),
"generated /AP/N must carry the default-appearance font selection; data={as_str:?}"
);
assert!(
data.windows(16).any(|w| w == b"BT (Hello) Tj ET"),
"qpdf's no-wrapper fallback must preserve source appearance content; data={as_str:?}"
);
}
#[test]
fn generate_appearances_uses_nested_terminal_field_value() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("nested-tx.pdf");
let flpdf_output = temp.path().join("flpdf.pdf");
std::fs::write(&input, nested_tx_widget_with_local_value()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=y"])
.arg(&input)
.arg(&flpdf_output)
.assert()
.success();
let flpdf_data = widget_normal_appearance_data(&flpdf_output);
assert!(
flpdf_data
.windows(b"child-value".len())
.any(|w| w == b"child-value"),
"flpdf must render the same terminal field value; data={flpdf_data:?}"
);
assert!(
!flpdf_data
.windows(b"parent-value".len())
.any(|w| w == b"parent-value"),
"flpdf must not render the top-level ancestor's value; data={flpdf_data:?}"
);
}
#[test]
fn generate_appearances_checkbox_without_ap_leaves_ap_absent() {
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 mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
assert!(
helper.get_appearance_dictionary().unwrap().is_null(),
"qpdf leaves a button without /AP unchanged"
);
}
#[test]
fn generate_appearances_routes_checkbox_without_ap_through_set_value() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("cb-value-no-ap.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(
&input,
checkbox_widget_with_value_without_ap_needing_appearances(),
)
.unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.failure()
.code(3)
.stderr(predicates::str::contains(
"unable to set the value of this checkbox",
));
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let widget = pdf.resolve_canonical_object(widget_ref).unwrap();
assert_eq!(
widget.try_get_key(b"/V").unwrap().as_name(),
Some(b"Yes".to_vec())
);
assert_eq!(
widget.try_get_key(b"/AS").unwrap().as_name(),
Some(b"Off".to_vec())
);
assert!(!widget.try_has_key(b"/AP").unwrap());
}
#[test]
fn generate_appearances_radio_without_ap_leaves_ap_absent() {
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 mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
assert!(
helper.get_appearance_dictionary().unwrap().is_null(),
"qpdf leaves a radio button without /AP unchanged"
);
}
#[test]
fn generate_appearances_checkbox_with_ap_synchronizes_as_to_value() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("cb-existing-ap.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, checkbox_widget_with_ap_needing_appearances()).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 widget = pdf.resolve_canonical_object(widget_ref).unwrap();
assert_eq!(
widget.try_get_key(b"/AS").unwrap().as_name(),
Some(b"Yes".to_vec())
);
let ap = widget.try_get_key(b"/AP").unwrap();
let normal = ap.try_get_key(b"/N").unwrap();
assert!(normal.try_has_key(b"/Off").unwrap() && normal.try_has_key(b"/Yes").unwrap());
}
#[test]
fn generate_appearances_direct_radio_with_ap_leaves_as_unchanged() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("rd-existing-ap.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, direct_radio_widget_with_ap_needing_appearances()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances", "--compress-streams=n"])
.arg(&input)
.arg(&output)
.assert()
.failure()
.code(3)
.stderr(predicates::str::contains(
"don't know how to set the value of this field as a radio button",
));
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget_ref = first_widget_ref(&mut pdf);
let widget = pdf.resolve_canonical_object(widget_ref).unwrap();
assert_eq!(
widget.try_get_key(b"/AS").unwrap().as_name(),
Some(b"Off".to_vec())
);
let ap = widget.try_get_key(b"/AP").unwrap();
let normal = ap.try_get_key(b"/N").unwrap();
assert!(normal.try_has_key(b"/Off").unwrap() && normal.try_has_key(b"/Yes").unwrap());
}
#[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",
"--stream-data=uncompress",
])
.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 mut helper = AnnotationObjectHelper::new(pdf.get_object_handle(widget_ref));
let n = helper.get_appearance_stream(b"N", None).unwrap();
let data = n
.get_stream_data(DecodeLevel::Generalized)
.expect("combo widget should have /AP/N after --generate-appearances");
assert!(
data.windows(2).any(|w| w == b"Tj"),
"combo /AP/N content stream must contain Tj (selected value rendered); \
stream={:?}",
std::str::from_utf8(&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 = page_annotation_handles(&mut pdf, page_refs[0]);
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_needing_appearances()).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 = page_annotation_handles(&mut pdf, page_refs[0]);
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 generate_then_flatten_clears_need_appearances() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx_need_appearances.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_without_ap_needing_appearances()).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_ref = flpdf::pages::page_refs(&mut pdf).unwrap()[0];
assert!(
page_annotation_handles(&mut pdf, page_ref).is_empty(),
"generated widget must be flattened after qpdf clears NeedAppearances"
);
}
#[test]
fn generate_then_flatten_replaces_indirect_null_normal_appearance() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("tx_null_ap_n.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_widget_with_null_ap_n_needing_appearances()).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_ref = flpdf::pages::page_refs(&mut pdf).unwrap()[0];
assert!(
page_annotation_handles(&mut pdf, page_ref).is_empty(),
"generated widget must be flattened after qpdf clears NeedAppearances"
);
let content = flpdf::pages::page_content_bytes(&mut pdf, page_ref).unwrap();
assert!(
content.windows(2).any(|window| window == b"Do"),
"an indirect null /AP/N must be regenerated before flattening; content={:?}",
std::str::from_utf8(&content).unwrap_or("<non-utf8>")
);
}
#[test]
fn flatten_print_draws_print_bit_annot_and_removes_all_selected_appearances() {
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 = page_annotation_handles(&mut pdf, page_refs[0]);
assert!(annots.is_empty());
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_canonical_object(page_ref).unwrap();
let rotate = page_obj.try_get_key(b"/Rotate").unwrap().as_integer();
assert!(
rotate.is_none() || rotate == Some(0),
"page {} /Rotate should be absent or 0 after --flatten-rotation, got {rotate:?}",
i + 1
);
}
}