use assert_cmd::Command;
use flpdf::{
acroform_sig_flags, filespec_helper::encode_utf16be, AnnotationObjectHelper, Object, Pdf,
};
use predicates::prelude::*;
use std::fs::File;
use std::io::BufReader;
use std::io::Write;
mod common;
use common::first_widget_ref;
fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
fn json_qpdf_metadata(json: &serde_json::Value) -> &serde_json::Value {
&json["qpdf"][0]
}
#[test]
fn check_valid_fixture_exits_successfully() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--check", "../../tests/fixtures/minimal.pdf"])
.assert()
.success()
.stdout(predicate::str::contains("File is not encrypted\n"));
}
#[test]
fn check_encrypted_fixture_accepts_correct_empty_password_flag() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"--check",
"--password=",
"../../tests/fixtures/compat/encrypted-r4-three-page.pdf",
])
.assert()
.success()
.stdout(predicate::str::contains("File is encrypted\n"));
}
#[test]
fn check_encrypted_fixture_rejects_wrong_password() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"--check",
"--password=wrong",
"../../tests/fixtures/compat/encrypted-r4-three-page.pdf",
])
.assert()
.failure()
.stderr(predicate::str::contains("incorrect password"))
.stderr(predicate::str::contains("--password"));
}
#[test]
fn check_inspects_rc4_encrypted_input_by_default() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("rc4.pdf");
std::fs::write(&input, encrypted_v1_owner_password_fixture()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--check", "--password=owner"])
.arg(&input)
.assert()
.code(0)
.stdout(predicate::str::contains("File is encrypted\n"))
.stderr(predicate::str::contains("weak crypto").not());
}
#[test]
fn check_rc4_with_allow_weak_crypto_still_clean_no_warning() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("rc4.pdf");
std::fs::write(&input, encrypted_v1_owner_password_fixture()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--check", "--allow-weak-crypto", "--password=owner"])
.arg(&input)
.assert()
.code(0)
.stdout(predicate::str::contains("File is encrypted\n"))
.stderr(predicate::str::contains("weak crypto").not());
}
#[test]
fn check_repair_encrypted_fixture_rejects_wrong_password_actionably() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"--check",
"--repair",
"--password=wrong",
"../../tests/fixtures/compat/encrypted-r4-three-page.pdf",
])
.assert()
.failure()
.stderr(predicate::str::contains("incorrect password"))
.stderr(predicate::str::contains("--password"));
}
#[test]
fn rewrite_encrypted_fixture_writes_plaintext_output() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.arg("--password=")
.arg("../../tests/fixtures/compat/encrypted-r4-three-page.pdf")
.arg(&output)
.assert()
.success();
assert!(output.exists());
let mut check = Command::cargo_bin("flpdf").unwrap();
check
.args(["--check", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("File is not encrypted\n"));
}
#[test]
fn check_encrypted_fixture_uses_empty_default_password() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"--check",
"../../tests/fixtures/compat/encrypted-r4-three-page.pdf",
])
.assert()
.success()
.stdout(predicate::str::contains("File is encrypted\n"));
}
#[test]
fn check_encrypted_fixture_reads_password_file_and_strips_newline() {
let temp = tempfile::tempdir().unwrap();
let password_file = temp.path().join("password.txt");
std::fs::write(&password_file, b"\r\n").unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--check"])
.arg(format!("--password-file={}", password_file.display()))
.arg("../../tests/fixtures/compat/encrypted-r4-three-page.pdf")
.assert()
.success()
.stdout(predicate::str::contains("File is encrypted\n"));
}
#[test]
fn password_and_password_file_are_mutually_exclusive() {
let temp = tempfile::tempdir().unwrap();
let password_file = temp.path().join("password.txt");
std::fs::write(&password_file, b"").unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--check", "--password="])
.arg(format!("--password-file={}", password_file.display()))
.arg("../../tests/fixtures/compat/encrypted-r4-three-page.pdf")
.assert()
.failure()
.stderr(predicate::str::contains("cannot be used with"));
}
#[test]
fn rewrite_fixture_creates_output() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.arg("../../tests/fixtures/minimal.pdf")
.arg(&output)
.assert()
.success();
assert!(output.exists());
assert!(std::fs::metadata(output).unwrap().len() > 0);
}
#[test]
fn rewrite_remove_restrictions_strips_signatures_and_warns() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("signed.pdf");
let output = temp.path().join("unsigned.pdf");
std::fs::write(&input, signed_acroform_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicate::str::contains("signatures are now invalidated"));
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
assert_eq!(acroform_sig_flags(&mut pdf).unwrap(), Some(0));
assert!(
pdf.signatures().unwrap().is_empty(),
"--remove-restrictions output must not report signed fields"
);
assert_eq!(
acroform_fields_len(&mut pdf),
Some(0),
"AcroForm must survive with an emptied /Fields array"
);
let output_bytes = std::fs::read(&output).unwrap();
assert!(
!contains(&output_bytes, b"/V "),
"signature field /V entries must be removed"
);
assert!(
!contains(&output_bytes, b"/FT"),
"signature field /FT entries must be removed (field object GC'd)"
);
assert!(
!contains(&output_bytes, b"/ByteRange"),
"orphaned signature dictionaries must be removed"
);
}
#[test]
fn rewrite_linearize_remove_restrictions_strips_signatures_and_warns() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("signed.pdf");
let output = temp.path().join("unsigned-linearized.pdf");
std::fs::write(&input, signed_acroform_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--linearize", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicate::str::contains("signatures are now invalidated"));
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
assert_eq!(acroform_sig_flags(&mut pdf).unwrap(), Some(0));
assert!(
pdf.signatures().unwrap().is_empty(),
"linearized --remove-restrictions output must not report signed fields"
);
let output_bytes = std::fs::read(&output).unwrap();
assert!(
!contains(&output_bytes, b"/V "),
"linearized signature field /V entries must be removed"
);
assert!(
!contains(&output_bytes, b"/ByteRange"),
"linearized output must remove orphaned signature dictionaries"
);
}
#[test]
fn rewrite_linearize_remove_restrictions_strips_docmdp_perms() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("docmdp.pdf");
let output = temp.path().join("out-linearized.pdf");
std::fs::write(&input, signed_perms_docmdp_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--linearize", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicate::str::contains("signatures are now invalidated"));
let output_bytes = std::fs::read(&output).unwrap();
for tok in [&b"/Perms"[..], &b"/DocMDP"[..], &b"/ByteRange"[..]] {
assert!(
!contains(&output_bytes, tok),
"linearized --remove-restrictions must drop {:?}",
std::str::from_utf8(tok).unwrap()
);
}
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
assert!(pdf.signatures().unwrap().is_empty());
}
#[test]
fn rewrite_linearize_remove_restrictions_keeps_widget_annotation() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("widget.pdf");
let output = temp.path().join("out-linearized.pdf");
std::fs::write(&input, signed_widget_acroform_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--linearize", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicate::str::contains("signatures are now invalidated"));
let output_bytes = std::fs::read(&output).unwrap();
assert!(contains(&output_bytes, b"/Widget"));
assert!(!contains(&output_bytes, b"/ByteRange"));
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
assert_eq!(acroform_sig_flags(&mut pdf).unwrap(), Some(0));
assert_eq!(
acroform_fields_len(&mut pdf),
Some(0),
"top-level /Fields must be emptied"
);
assert!(pdf.signatures().unwrap().is_empty());
}
#[test]
fn rewrite_remove_restrictions_strips_docmdp_perms_and_warns() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("certified.pdf");
let output = temp.path().join("uncertified.pdf");
std::fs::write(&input, signed_perms_docmdp_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicate::str::contains("signatures are now invalidated"));
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
assert!(
pdf.signatures().unwrap().is_empty(),
"DocMDP --remove-restrictions output must not report signed fields"
);
let output_bytes = std::fs::read(&output).unwrap();
assert!(
!contains(&output_bytes, b"/Perms"),
"catalog /Perms must be removed"
);
assert!(
!contains(&output_bytes, b"/DocMDP"),
"the /DocMDP dictionary must be removed with /Perms"
);
assert!(
!contains(&output_bytes, b"/ByteRange"),
"the orphaned DocMDP signature dictionary must be garbage-collected"
);
}
#[test]
fn rewrite_remove_restrictions_keeps_widget_annotation() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("signed-widget.pdf");
let output = temp.path().join("unsigned-widget.pdf");
std::fs::write(&input, signed_widget_acroform_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-restrictions"])
.arg(&input)
.arg(&output)
.assert()
.success()
.stderr(predicate::str::contains("signatures are now invalidated"));
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
assert_eq!(acroform_sig_flags(&mut pdf).unwrap(), Some(0));
assert!(
pdf.signatures().unwrap().is_empty(),
"widget --remove-restrictions output must not report signed fields"
);
assert_eq!(
acroform_fields_len(&mut pdf),
Some(0),
"AcroForm must survive with an emptied /Fields array"
);
let output_bytes = std::fs::read(&output).unwrap();
assert!(
contains(&output_bytes, b"/Subtype /Widget"),
"the widget annotation must survive as a page annotation"
);
assert!(
contains(&output_bytes, b"/T (Approval)"),
"the surviving widget must keep its /T field name"
);
assert!(
!contains(&output_bytes, b"/FT"),
"the surviving widget must lose its /FT (signature field type)"
);
assert!(
!contains(&output_bytes, b"/ByteRange"),
"the orphaned signature dictionary must be garbage-collected"
);
}
#[test]
fn rewrite_default_is_qpdf_equivalent_full_rewrite() {
let temp = tempfile::tempdir().unwrap();
let default_out = temp.path().join("default.pdf");
let nocomp_out = temp.path().join("nocomp.pdf");
let input = "../../tests/fixtures/compat/one-page.pdf";
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", input, default_out.to_str().unwrap()])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--compress-streams=n",
input,
nocomp_out.to_str().unwrap(),
])
.assert()
.success();
let default_bytes = std::fs::read(&default_out).unwrap();
let nocomp_bytes = std::fs::read(&nocomp_out).unwrap();
let input_bytes = std::fs::read(input).unwrap();
assert_ne!(
default_bytes, input_bytes,
"default rewrite must full-rewrite, not copy the source verbatim"
);
let has_flate = |b: &[u8]| b.windows(11).any(|w| w == b"FlateDecode");
assert!(
has_flate(&default_bytes),
"default rewrite must FlateDecode-compress streams (qpdf-equivalent default)"
);
assert_ne!(
default_bytes, nocomp_bytes,
"default rewrite (compress=y) must differ from --compress-streams=n output"
);
}
#[test]
fn rewrite_repaired_fixture_with_repair_flag() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("corrupt.pdf");
std::fs::write(&input, corrupt_xref_pdf()).unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"--repair",
input.to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists());
assert!(std::fs::metadata(output).unwrap().len() > 0);
}
#[test]
fn check_subcommand_succeeds() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["check", "../../tests/fixtures/minimal.pdf"])
.assert()
.success()
.stdout(predicate::str::contains("File is not encrypted\n"));
}
#[test]
fn pages_subcommand_prints_each_page() {
let fixture = fixture_with_nested_pages();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["pages", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("page 1: 3 0 R"))
.stdout(predicate::str::contains("page 2: 6 0 R"));
}
#[test]
fn pages_subcommand_prints_count() {
let fixture = fixture_with_nested_pages();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["pages", "--count", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("2"));
}
#[test]
fn dump_object_subcommand_accepts_ref() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["dump-object", "1 0", "../../tests/fixtures/minimal.pdf"])
.assert()
.success()
.stdout(predicate::str::contains("/Type /Catalog"));
}
#[test]
fn qdf_subcommand_rewrites_output() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"qdf",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists());
assert!(std::fs::metadata(&output).unwrap().len() > 0);
let rendered = std::fs::read(&output).unwrap();
let has = |needle: &[u8]| rendered.windows(needle.len()).any(|w| w == needle);
assert!(has(b"%QDF-1.0"), "expected %QDF-1.0 header marker");
assert!(
has(b"%% Original object ID:"),
"expected %% Original object ID: comments"
);
assert!(has(b"\nxref\n"), "expected a classic `xref` table");
assert!(!has(b"/Type /XRef"), "QDF must not use an xref stream");
assert!(!has(b"/Type /ObjStm"), "QDF must not use object streams");
}
#[test]
fn qdf_subcommand_dumps_all_reachable_objects() {
let temp = tempfile::tempdir().unwrap();
let fixture = fixture_with_orphan_object();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"qdf",
fixture.path().to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let rendered = std::fs::read(&output).unwrap();
let has = |needle: &[u8]| rendered.windows(needle.len()).any(|w| w == needle);
assert!(
has(b"/Type /Catalog"),
"expected the reachable Catalog object"
);
assert!(has(b"/Type /Pages"), "expected the reachable Pages object");
assert!(has(b"/Type /Page"), "expected the reachable Page object");
assert!(
!has(b"/Type /Orphan"),
"unreferenced orphan object must be dropped (qpdf-consistent)"
);
assert!(has(b"%QDF-1.0"), "expected %QDF-1.0 header marker");
assert!(
has(b"%% Original object ID:"),
"expected %% Original object ID: comments"
);
assert!(has(b"\nxref\n"), "expected a classic `xref` table");
assert!(!has(b"/Type /XRef"), "QDF must not use an xref stream");
assert!(!has(b"/Type /ObjStm"), "QDF must not use object streams");
}
#[test]
fn rewrite_subcommand_rewrites_output() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists());
assert!(std::fs::metadata(output).unwrap().len() > 0);
}
fn one_page_pdf_bytes() -> Vec<u8> {
let mut pdf = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len();
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len();
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
let off3 = pdf.len();
pdf.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
);
let xref_start = pdf.len();
let xref = format!(
"xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \n"
);
pdf.extend_from_slice(xref.as_bytes());
pdf.extend_from_slice(
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
);
pdf
}
#[test]
fn top_level_linearize_rewrites_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--linearize", "--static-id"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
assert!(std::fs::metadata(output).unwrap().len() > 0);
}
#[test]
fn top_level_linearize_accepts_compress_streams_and_pass1() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("a.pdf");
let pass1 = temp.path().join("b.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.env("FLPDF_STATIC_ID_QUIET", "1")
.args(["--linearize", "--static-id", "--compress-streams=n"])
.arg(format!("--linearize-pass1={}", pass1.display()))
.arg(&input)
.arg(&output)
.assert()
.success()
.stdout(predicate::str::is_empty())
.stderr(predicate::str::is_empty());
assert!(output.exists());
assert!(pass1.exists());
}
#[test]
fn rewrite_force_version_invalid_abc_exits_nonzero() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"--force-version=abc",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("invalid --force-version"));
}
#[test]
fn rewrite_force_version_with_newline_exits_nonzero() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.arg("--force-version=1.4\n")
.assert()
.failure()
.stderr(predicate::str::contains("invalid --force-version"));
}
#[test]
fn rewrite_min_version_invalid_abc_exits_nonzero() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"--min-version=abc",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("invalid --min-version"));
}
#[test]
fn rewrite_valid_force_version_succeeds() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"--force-version=1.4",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists());
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.4\n"),
"expected forced header %PDF-1.4; got {:?}",
std::str::from_utf8(&bytes[..bytes.len().min(9)]).unwrap_or("<bad>")
);
}
#[test]
fn rewrite_valid_min_version_succeeds() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"--min-version=1.3",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert!(output.exists());
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.7\n"),
"min-version below source must be a no-op (header stays 1.7); got {:?}",
std::str::from_utf8(&bytes[..bytes.len().min(9)]).unwrap_or("<bad>")
);
}
#[test]
fn rewrite_min_version_raises_header_on_low_source() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("v13.pdf");
let output = temp.path().join("out.pdf");
let mut pdf = b"%PDF-1.3\n".to_vec();
let o1 = pdf.len();
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let o2 = pdf.len();
pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Count 0 /Kids [] >>\nendobj\n");
let startxref = pdf.len();
pdf.extend_from_slice(b"xref\n0 3\n0000000000 65535 f \n");
pdf.extend_from_slice(format!("{o1:010} 00000 n \n{o2:010} 00000 n \n").as_bytes());
pdf.extend_from_slice(
format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{startxref}\n%%EOF\n").as_bytes(),
);
std::fs::write(&input, &pdf).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"--min-version=1.7",
input.to_str().unwrap(),
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.7\n"),
"min-version 1.7 must raise header 1.3 -> 1.7; got {:?}",
std::str::from_utf8(&bytes[..bytes.len().min(9)]).unwrap_or("<bad>")
);
}
#[test]
fn rewrite_force_version_honored_on_incremental_path() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args([
"rewrite",
"--remove-unreferenced-resources=no",
"--force-version=1.4",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
let bytes = std::fs::read(&output).unwrap();
assert!(
bytes.starts_with(b"%PDF-1.4\n"),
"force-version must be honored even on the would-be incremental path; \
got {:?}",
std::str::from_utf8(&bytes[..bytes.len().min(9)]).unwrap_or("<bad>")
);
}
#[test]
fn show_info_with_repair_flag_handles_corrupt_xref() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("corrupt.pdf");
std::fs::write(&input, corrupt_xref_with_info_pdf()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--repair", "--show-info", input.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("Title = (Corrupt fixture)"));
}
#[test]
fn show_info_without_repair_rejects_corrupt_xref() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("corrupt.pdf");
std::fs::write(&input, corrupt_xref_with_info_pdf()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-info", input.to_str().unwrap()])
.assert()
.failure();
}
#[test]
fn check_without_repair_rejects_corrupt_xref() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("corrupt.pdf");
std::fs::write(&input, corrupt_xref_with_info_pdf()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--check", input.to_str().unwrap()])
.assert()
.failure();
}
#[test]
fn check_with_repair_accepts_corrupt_xref() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("corrupt.pdf");
std::fs::write(&input, corrupt_xref_with_info_pdf()).unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--repair", "--check", input.to_str().unwrap()])
.assert()
.code(3)
.stdout(predicate::str::contains("File is not encrypted\n"));
}
#[test]
fn dump_object_accepts_ref_without_suffix() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--dump-object", "1 0", "../../tests/fixtures/minimal.pdf"])
.assert()
.success()
.stdout(predicate::str::contains("/Type /Catalog"));
}
#[test]
fn dump_object_accepts_ref_with_r_suffix() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--dump-object", "1 0 R", "../../tests/fixtures/minimal.pdf"])
.assert()
.success()
.stdout(predicate::str::contains("/Type /Catalog"));
}
#[test]
fn dump_object_rejects_invalid_ref() {
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--dump-object", "bad", "../../tests/fixtures/minimal.pdf"])
.assert()
.failure();
}
#[test]
fn show_info_prints_document_info() {
let fixture = fixture_with_metadata_outline_and_fonts();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-info", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("Title = (Fixture PDF)"))
.stdout(predicate::str::contains("Creator = (flpdf)"));
}
#[test]
fn show_catalog_prints_root_dictionary() {
let fixture = fixture_with_metadata_outline_and_fonts();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-catalog", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("Catalog: <<"))
.stdout(predicate::str::contains("/Type /Catalog"));
}
#[test]
fn show_metadata_prints_stream_summary() {
let fixture = fixture_with_metadata_outline_and_fonts();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-metadata", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("Metadata: stream"))
.stdout(predicate::str::contains("/XML"));
}
#[test]
fn show_outline_prints_titles() {
let fixture = fixture_with_metadata_outline_and_fonts();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-outline", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("1: Chapter One"));
}
#[test]
fn show_outline_warns_and_prints_empty_when_outline_resolution_fails() {
let fixture = fixture_with_unresolvable_outline();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-outline", fixture.path().to_str().unwrap()])
.assert()
.success()
.stderr(predicate::str::contains("Warning:"))
.stdout(predicate::str::contains("Outline:\n <empty>"));
}
#[test]
fn json_outlines_short_first_name_tree_pair_exits_two_without_complete_json() {
let fixture = fixture_with_short_first_name_tree_pair();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-key=outlines"])
.arg(fixture.path())
.assert()
.code(2);
let output = assert.get_output();
let stderr = String::from_utf8_lossy(&output.stderr);
let repair = stderr
.find("attempting to repair after error:")
.unwrap_or_else(|| panic!("missing repair warning in {stderr}"));
let fatal = stderr
.rfind("update ivalue: items array is too short")
.unwrap_or_else(|| panic!("missing fatal error in {stderr}"));
assert!(repair < fatal, "{stderr}");
assert_eq!(
stderr.matches("attempting to repair after error:").count(),
1
);
assert_eq!(
stderr
.matches("update ivalue: items array is too short")
.count(),
2
);
assert!(output.stdout.is_empty());
}
#[test]
fn json_successful_name_tree_repair_emits_warning_summary_and_exits_three() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-key=outlines"])
.arg(fixture.path())
.assert()
.code(3);
let output = assert.get_output();
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json["outlines"][0]["dest"][0], "3 0 R");
let stderr = String::from_utf8_lossy(&output.stderr);
let warning = stderr
.find("attempting to repair after error:")
.unwrap_or_else(|| panic!("missing repair warning in {stderr}"));
let summary = stderr
.find("flpdf: operation succeeded with warnings")
.unwrap_or_else(|| panic!("missing warning summary in {stderr}"));
assert!(warning < summary, "{stderr}");
assert_eq!(
stderr.matches("attempting to repair after error:").count(),
1
);
assert_eq!(
stderr
.matches("flpdf: operation succeeded with warnings")
.count(),
1
);
}
#[test]
fn json_key_qpdf_skips_unselected_outline_repair() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.assert()
.code(0);
let output = assert.get_output();
assert!(
output.stderr.is_empty(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert!(json.get("outlines").is_none());
let dests = &json["qpdf"][1]["obj:1 0 R"]["value"]["/Names"]["/Dests"];
assert_eq!(dests["/Kids"][0], "8 0 R");
assert!(dests.get("/Names").is_none());
}
#[test]
fn json_key_outlines_and_qpdf_repairs_before_raw_object_projection() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-key=outlines", "--json-key=qpdf"])
.arg(fixture.path())
.assert()
.code(3);
let output = assert.get_output();
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json["outlines"][0]["dest"][0], "3 0 R");
let dests = &json["qpdf"][1]["obj:1 0 R"]["value"]["/Names"]["/Dests"];
assert_eq!(dests["/Names"][0], "u:shape");
assert_eq!(dests["/Names"][1][0], "3 0 R");
assert!(dests.get("/Kids").is_none());
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
stderr.matches("attempting to repair after error:").count(),
1
);
assert_eq!(
stderr
.matches("flpdf: operation succeeded with warnings")
.count(),
1
);
}
#[test]
fn json_key_selection_order_is_qpdf_fixed() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-key=qpdf", "--json-key=outlines"])
.arg(fixture.path())
.assert()
.code(3);
let output = assert.get_output();
let stdout = String::from_utf8_lossy(&output.stdout);
let outlines = stdout
.find("\"outlines\":")
.unwrap_or_else(|| panic!("missing outlines section in {stdout}"));
let qpdf = stdout
.find("\"qpdf\":")
.unwrap_or_else(|| panic!("missing qpdf section in {stdout}"));
assert!(outlines < qpdf, "{stdout}");
}
#[test]
fn json_metadata_tracks_page_enumeration_without_pushing_inherited_resources() {
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/inherited-resources-one-page.pdf");
let cases = [
("qpdf only", &["--json=2", "--json-key=qpdf"][..], false),
(
"pages then qpdf",
&["--json=2", "--json-key=pages", "--json-key=qpdf"][..],
true,
),
];
for (label, args, called_get_all_pages) in cases {
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(&fixture)
.output()
.unwrap();
assert!(output.status.success(), "{label}");
assert!(output.stderr.is_empty(), "{label}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(
json_qpdf_metadata(&json),
&serde_json::json!({
"jsonversion": 2,
"pdfversion": "1.4",
"pushedinheritedpageresources": false,
"calledgetallpages": called_get_all_pages,
"maxobjectid": 5
}),
"{label}"
);
assert!(
json["qpdf"][1]["obj:3 0 R"]["value"]
.get("/Resources")
.is_none(),
"{label}: page dictionary must remain unmodified"
);
}
}
#[test]
fn json_metadata_includes_outline_repair_allocations_in_maxobjectid() {
let fixture = fixture_with_name_tree_repair_allocations();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=outlines", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(output.status.code(), Some(3));
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(
json_qpdf_metadata(&json),
&serde_json::json!({
"jsonversion": 2,
"pdfversion": "1.7",
"pushedinheritedpageresources": false,
"calledgetallpages": true,
"maxobjectid": 10
})
);
assert!(json["qpdf"][1].get("obj:9 0 R").is_some());
assert!(json["qpdf"][1].get("obj:10 0 R").is_some());
}
#[test]
fn json_qpdf_preparation_treats_referenced_empty_object_as_null_with_warning() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&empty_object_json_pdf()).unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf", "--json-object=7"])
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(output.status.code(), Some(3));
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(
json["qpdf"][1]["obj:7 0 R"],
serde_json::json!({"value": null})
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(stderr.matches("empty object treated as null").count(), 1);
assert_eq!(
stderr.matches("operation succeeded with warnings").count(),
1
);
assert!(
stderr.find("empty object treated as null").unwrap()
< stderr.find("operation succeeded with warnings").unwrap(),
"{stderr}"
);
}
#[test]
fn json_qpdf_preparation_treats_top_level_bare_reference_as_integer() {
let bytes = top_level_bare_reference_json_pdf();
let expected_warning_offset = bytes
.windows(b"4 0 obj\n3 0 R".len())
.position(|window| window == b"4 0 obj\n3 0 R")
.expect("fixture must contain malformed object")
+ b"4 0 obj\n3 ".len();
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&bytes).unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf", "--json-object=4"])
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(output.status.code(), Some(3));
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(
json["qpdf"][1]["obj:4 0 R"],
serde_json::json!({"value": 3})
);
let stderr = String::from_utf8_lossy(&output.stderr);
let warning = format!("(object 4 0, offset {expected_warning_offset}): expected endobj");
assert_eq!(stderr.matches(&warning).count(), 1, "{stderr}");
assert_eq!(
stderr.matches("operation succeeded with warnings").count(),
1
);
assert!(
stderr.find(&warning).unwrap() < stderr.find("operation succeeded with warnings").unwrap(),
"{stderr}"
);
}
#[test]
fn json_unselected_qpdf_does_not_resolve_unrelated_empty_object() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&empty_object_json_pdf()).unwrap();
for section in ["pages", "outlines"] {
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", &format!("--json-key={section}")])
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success(), "{section}");
assert!(output.stderr.is_empty(), "{section}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert!(json.get(section).is_some(), "{section}");
assert!(json.get("qpdf").is_none(), "{section}");
}
}
#[test]
fn json_qpdf_preparation_walks_nested_stream_holder_and_cycle_objects() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&dangling_container_json_pdf()).unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(output.status.code(), Some(0));
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99);
assert_eq!(
json["qpdf"][1]["obj:1 0 R"]["value"]["/Nested"],
serde_json::json!({"/Array": ["99 2 R", null]})
);
assert_eq!(
json["qpdf"][1]["obj:4 0 R"]["stream"]["dict"],
serde_json::json!({"/Length": 0})
);
assert_eq!(
json["qpdf"][1]["obj:5 0 R"],
serde_json::json!({"value": {}})
);
assert_eq!(
json["qpdf"][1]["obj:99 2 R"],
serde_json::json!({"value": null})
);
assert_eq!(
json["qpdf"][1]["obj:6 0 R"],
serde_json::json!({"value": {"/Next": "7 0 R"}})
);
assert_eq!(
json["qpdf"][1]["obj:7 0 R"],
serde_json::json!({"value": {"/Next": "6 0 R"}})
);
assert!(output.stderr.is_empty());
}
#[test]
#[ignore = "live qpdf 11.9.0 dangling container JSON oracle"]
fn live_qpdf_dangling_container_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&dangling_container_json_pdf()).unwrap();
let args = ["--json=2", "--json-key=qpdf"];
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let qpdf_stderr = String::from_utf8_lossy(&qpdf.stderr);
let flpdf_stderr = String::from_utf8_lossy(&flpdf.stderr);
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"qpdf stderr: {qpdf_stderr}\nflpdf stderr: {flpdf_stderr}"
);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"]);
assert_eq!(flpdf_stderr, qpdf_stderr);
}
#[test]
fn json_qpdf_preparation_resolves_lazy_objects_and_exact_free_generations() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&dangling_generation_free_json_pdf())
.unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success());
assert!(output.stderr.is_empty());
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 88);
let objects = &json["qpdf"][1];
assert_eq!(objects["obj:8 0 R"], serde_json::json!({"value": null}));
assert_eq!(
objects["obj:8 1 R"],
serde_json::json!({"value": {"/Value": 1}})
);
assert_eq!(objects["obj:20 7 R"], serde_json::json!({"value": null}));
assert_eq!(objects["obj:88 4 R"], serde_json::json!({"value": null}));
assert!(objects.get("obj:200 7 R").is_none());
}
#[test]
#[ignore = "live qpdf 11.9.0 lazy/generation/free JSON oracle"]
fn live_qpdf_dangling_generation_free_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&dangling_generation_free_json_pdf())
.unwrap();
let args = ["--json=2", "--json-key=qpdf"];
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stderr, qpdf.stderr);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"]);
}
#[test]
fn json_qpdf_preparation_discovers_trailer_only_dangling_generations() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&trailer_dangling_json_pdf()).unwrap();
let cases: [(&str, &[&str]); 4] = [
(
"trailer",
&["--json=2", "--json-key=qpdf", "--json-object=trailer"],
),
(
"object99",
&["--json=2", "--json-key=qpdf", "--json-object=99"],
),
(
"generation",
&["--json=2", "--json-key=qpdf", "--json-object=88,4"],
),
("all", &["--json=2", "--json-key=qpdf"]),
];
for (label, args) in cases {
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success(), "{label}");
assert!(output.stderr.is_empty(), "{label}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99, "{label}");
let map = json["qpdf"][1].as_object().unwrap();
match label {
"trailer" => assert_eq!(
map.keys().map(String::as_str).collect::<Vec<_>>(),
vec!["trailer"]
),
"object99" => assert_eq!(
map,
&serde_json::Map::from_iter([(
"obj:99 0 R".to_string(),
serde_json::json!({"value": null}),
)])
),
"generation" => assert_eq!(
map,
&serde_json::Map::from_iter([(
"obj:88 4 R".to_string(),
serde_json::json!({"value": null}),
)])
),
"all" => {
assert_eq!(map["obj:99 0 R"], serde_json::json!({"value": null}));
assert_eq!(map["obj:88 4 R"], serde_json::json!({"value": null}));
assert!(map.get("obj:0 0 R").is_none());
assert!(map.get("obj:77 65535 R").is_none());
assert!(map.get("obj:200 7 R").is_none());
}
_ => unreachable!(),
}
if let Some(trailer) = map.get("trailer") {
let value = trailer["value"].as_object().unwrap();
assert_eq!(value["/Root"], "1 0 R");
assert_eq!(value["/Size"], 201);
for omitted in ["/Info", "/Gen", "/Zero", "/BadGen"] {
assert!(value.get(omitted).is_none(), "{label}: {omitted}");
}
}
}
}
#[test]
#[ignore = "live qpdf 11.9.0 trailer-only dangling JSON oracle"]
fn live_qpdf_trailer_only_dangling_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&trailer_dangling_json_pdf()).unwrap();
let cases: [&[&str]; 4] = [
&["--json=2", "--json-key=qpdf", "--json-object=trailer"],
&["--json=2", "--json-key=qpdf", "--json-object=99"],
&["--json=2", "--json-key=qpdf", "--json-object=88,4"],
&["--json=2", "--json-key=qpdf"],
];
for args in cases {
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code(), "{args:?}");
assert_eq!(flpdf.stderr, qpdf.stderr, "{args:?}");
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"], "{args:?}");
}
}
#[test]
fn json_qpdf_preparation_discovers_all_historical_incremental_trailer_refs() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&multigeneration_historical_trailer_json_pdf())
.unwrap();
let cases: [(&str, &[&str]); 6] = [
(
"trailer",
&["--json=2", "--json-key=qpdf", "--json-object=trailer"],
),
(
"oldest",
&["--json=2", "--json-key=qpdf", "--json-object=99"],
),
(
"old-generation",
&["--json=2", "--json-key=qpdf", "--json-object=88,4"],
),
(
"replaced-generation",
&["--json=2", "--json-key=qpdf", "--json-object=60,1"],
),
(
"referenced-free",
&["--json=2", "--json-key=qpdf", "--json-object=20,7"],
),
("all", &["--json=2", "--json-key=qpdf"]),
];
for (label, args) in cases {
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success(), "{label}");
assert!(output.stderr.is_empty(), "{label}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99, "{label}");
let map = json["qpdf"][1].as_object().unwrap();
match label {
"trailer" => {
assert_eq!(
map.keys().map(String::as_str).collect::<Vec<_>>(),
vec!["trailer"]
);
let value = map["trailer"]["value"].as_object().unwrap();
assert_eq!(value["/Root"], "1 0 R");
assert_eq!(value["/Size"], 201);
assert!(value.get("/Newest").is_none());
for historical in ["/Info", "/OldGen", "/Freed", "/Middle"] {
assert!(value.get(historical).is_none(), "{historical}");
}
}
"oldest" => assert_eq!(map["obj:99 0 R"], serde_json::json!({"value": null})),
"old-generation" => {
assert_eq!(map["obj:88 4 R"], serde_json::json!({"value": null}))
}
"replaced-generation" => {
assert_eq!(map["obj:60 1 R"], serde_json::json!({"value": null}))
}
"referenced-free" => {
assert_eq!(map["obj:20 7 R"], serde_json::json!({"value": null}))
}
"all" => {
for key in [
"obj:99 0 R",
"obj:88 4 R",
"obj:20 7 R",
"obj:60 1 R",
"obj:70 3 R",
"obj:50 2 R",
] {
assert_eq!(map[key], serde_json::json!({"value": null}), "{key}");
}
assert!(map.get("obj:0 0 R").is_none());
assert!(map.get("obj:77 65535 R").is_none());
assert!(map.get("obj:200 7 R").is_none());
}
_ => unreachable!(),
}
}
}
#[test]
fn json_qpdf_preparation_discovers_refs_from_a_freed_historical_xref_stream() {
for free_generation in [0, 1] {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&historical_xref_stream_json_pdf_with_free_generation(
free_generation,
))
.unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success(), "generation {free_generation}");
assert!(output.stderr.is_empty(), "generation {free_generation}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99);
let map = json["qpdf"][1].as_object().unwrap();
assert_eq!(map["obj:99 0 R"], serde_json::json!({"value": null}));
assert_eq!(map["obj:88 4 R"], serde_json::json!({"value": null}));
assert_eq!(
map["obj:4 0 R"]["stream"]["dict"]["/Type"],
serde_json::json!("/XRef")
);
assert!(map["obj:4 0 R"]["stream"]["dict"].get("/Info").is_none());
assert!(map["obj:4 0 R"]["stream"]["dict"].get("/Gen").is_none());
let trailer = map["trailer"]["value"].as_object().unwrap();
assert!(trailer.get("/Info").is_none());
assert!(trailer.get("/Gen").is_none());
}
}
#[test]
fn json_file_mode_writes_selected_historical_xref_stream_bytes_only() {
for free_generation in [0, 1] {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&historical_xref_stream_json_pdf_with_free_generation(
free_generation,
))
.unwrap();
let temp = tempfile::tempdir().unwrap();
let prefix = temp.path().join(format!("stream-{free_generation}"));
let output = Command::cargo_bin("flpdf")
.unwrap()
.args([
"--json=2",
"--json-key=qpdf",
"--json-object=4,0",
"--json-stream-data=file",
"--json-stream-prefix",
])
.arg(&prefix)
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success(), "generation {free_generation}");
assert!(output.stderr.is_empty(), "generation {free_generation}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
let side_path = format!("{}-4", prefix.display());
assert_eq!(
json["qpdf"][1]["obj:4 0 R"]["stream"]["datafile"],
side_path
);
assert_eq!(std::fs::read(&side_path).unwrap().len(), 35);
let unselected_prefix = temp.path().join(format!("unselected-{free_generation}"));
let unselected = Command::cargo_bin("flpdf")
.unwrap()
.args([
"--json=2",
"--json-key=pages",
"--json-stream-data=file",
"--json-stream-prefix",
])
.arg(&unselected_prefix)
.arg(fixture.path())
.output()
.unwrap();
assert!(unselected.status.success());
assert!(!std::path::Path::new(&format!("{}-4", unselected_prefix.display())).exists());
}
}
#[test]
#[ignore = "live qpdf 11.9.0 historical xref stream datafile oracle"]
fn live_qpdf_historical_xref_stream_file_payload_matches() {
for free_generation in [0, 1] {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&historical_xref_stream_json_pdf_with_free_generation(
free_generation,
))
.unwrap();
let temp = tempfile::tempdir().unwrap();
let prefix = temp.path().join("stream");
let args = [
"--json=2",
"--json-key=qpdf",
"--json-object=4,0",
"--json-stream-data=file",
];
let prefix_arg = format!("--json-stream-prefix={}", prefix.display());
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(&prefix_arg)
.arg(fixture.path())
.output()
.unwrap();
let side_path = format!("{}-4", prefix.display());
let qpdf_payload = std::fs::read(&side_path).unwrap();
std::fs::remove_file(&side_path).unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(&prefix_arg)
.arg(fixture.path())
.env("FLPDF_PROGNAME", "qpdf")
.output()
.unwrap();
let flpdf_payload = std::fs::read(&side_path).unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stderr, qpdf.stderr);
assert_eq!(flpdf_payload, qpdf_payload);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(
flpdf_json["qpdf"][1]["obj:4 0 R"]["stream"]["datafile"],
qpdf_json["qpdf"][1]["obj:4 0 R"]["stream"]["datafile"]
);
}
}
#[test]
fn json_qpdf_preparation_prefers_a_live_reuse_of_an_xref_stream_ref() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&reused_historical_xref_stream_json_pdf())
.unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf", "--json-object=4,0"])
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success());
assert!(output.stderr.is_empty());
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99);
assert_eq!(
json["qpdf"][1]["obj:4 0 R"],
serde_json::json!({"value": {"/Marker": "/New"}})
);
}
#[test]
fn json_qpdf_preparation_prefers_the_nearest_repeated_xref_stream_generation() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&repeated_historical_xref_stream_json_pdf())
.unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf", "--json-object=4,0"])
.arg(fixture.path())
.output()
.unwrap();
assert!(output.status.success());
assert!(output.stderr.is_empty());
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 92);
let dict = &json["qpdf"][1]["obj:4 0 R"]["stream"]["dict"];
assert_eq!(dict["/Marker"], serde_json::json!("/Near"));
assert!(dict.get("/Info").is_none());
}
#[test]
fn json_qpdf_preparation_keeps_historical_refs_when_repair_stops_a_prev_cycle() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&circular_historical_trailer_json_pdf())
.unwrap();
let strict = Command::cargo_bin("flpdf")
.unwrap()
.args(["--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert!(!strict.status.success());
let repaired = Command::cargo_bin("flpdf")
.unwrap()
.args(["--repair", "--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(repaired.status.code(), Some(3));
let stderr = String::from_utf8_lossy(&repaired.stderr);
assert_eq!(stderr.matches("WARNING:").count(), 3, "{stderr}");
assert!(stderr.ends_with("flpdf: operation succeeded with warnings\n"));
let json: serde_json::Value = serde_json::from_slice(&repaired.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99);
assert_eq!(
json["qpdf"][1]["obj:99 0 R"],
serde_json::json!({"value": null})
);
assert!(json["qpdf"][1]["trailer"]["value"].get("/Info").is_none());
}
#[test]
fn json_repair_preserves_refs_and_xref_stream_after_a_late_malformed_prev() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&malformed_late_prev_after_valid_sections_json_pdf())
.unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--repair", "--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(output.status.code(), Some(3));
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(stderr.matches("WARNING:").count(), 3, "{stderr}");
assert!(stderr.ends_with("flpdf: operation succeeded with warnings\n"));
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
let objects = json["qpdf"][1].as_object().unwrap();
for key in ["obj:99 0 R", "obj:88 4 R", "obj:70 3 R", "obj:50 2 R"] {
assert!(objects.contains_key(key), "missing {key}: {json}");
}
assert_eq!(objects["obj:4 0 R"]["stream"]["dict"]["/Type"], "/XRef");
}
#[test]
fn json_open_warnings_precede_fatal_output_error_without_success_summary() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&malformed_late_prev_after_valid_sections_json_pdf())
.unwrap();
let output_directory = tempfile::tempdir().unwrap();
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(["--repair", "--json=2", "--json-key=qpdf", "--json-output"])
.arg(output_directory.path())
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(output.stdout.is_empty());
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(stderr.matches("WARNING:").count(), 3, "{stderr}");
let last_warning = stderr.rfind("WARNING:").unwrap();
let fatal = stderr.rfind("flpdf:").unwrap();
assert!(last_warning < fatal, "{stderr}");
assert!(!stderr.contains("operation succeeded with warnings"));
}
#[test]
#[ignore = "live qpdf 11.9.0 historical incremental trailer JSON oracle"]
fn live_qpdf_historical_incremental_trailer_json_matches() {
for bytes in [
historical_xref_stream_json_pdf_with_free_generation(0),
historical_xref_stream_json_pdf_with_free_generation(1),
reused_historical_xref_stream_json_pdf(),
multigeneration_historical_trailer_json_pdf(),
] {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&bytes).unwrap();
for args in [
&["--json=2", "--json-key=qpdf", "--json-object=trailer"][..],
&["--json=2", "--json-key=qpdf", "--json-object=99"][..],
&["--json=2", "--json-key=qpdf", "--json-object=88,4"][..],
&["--json=2", "--json-key=qpdf"][..],
] {
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code(), "{args:?}");
assert_eq!(flpdf.stderr, qpdf.stderr, "{args:?}");
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"], "{args:?}");
}
}
}
#[test]
#[ignore = "live qpdf 11.9.0 repeated historical xref stream cache oracle"]
fn live_qpdf_repeated_historical_xref_stream_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&repeated_historical_xref_stream_json_pdf())
.unwrap();
for args in [
&["--json=2", "--json-key=qpdf", "--json-object=4,0"][..],
&["--json=2", "--json-key=qpdf"][..],
] {
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code(), "{args:?}");
assert_eq!(flpdf.stderr, qpdf.stderr, "{args:?}");
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"], "{args:?}");
}
}
#[test]
#[ignore = "live qpdf 11.9.0 historical trailer through /Prev cycle oracle"]
fn live_qpdf_prev_cycle_historical_trailer_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&circular_historical_trailer_json_pdf())
.unwrap();
let qpdf = std::process::Command::new("qpdf")
.args(["--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--repair", "--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.env("FLPDF_PROGNAME", "qpdf")
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stderr, qpdf.stderr);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"]);
}
#[test]
#[ignore = "live qpdf 11.9.0 malformed late /Prev repair oracle"]
fn live_qpdf_malformed_late_prev_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture
.write_all(&malformed_late_prev_after_valid_sections_json_pdf())
.unwrap();
let args = ["--json=2", "--json-key=qpdf"];
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(["--repair", "--json=2", "--json-key=qpdf"])
.arg(fixture.path())
.env("FLPDF_PROGNAME", "qpdf")
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stderr, qpdf.stderr);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"]);
}
#[test]
#[ignore = "live qpdf 11.9.0 empty-object diagnostic oracle"]
fn live_qpdf_empty_object_json_matches() {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
fixture.write_all(&empty_object_json_pdf()).unwrap();
let args = ["--json=2", "--json-key=qpdf", "--json-object=7"];
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"]);
for stderr in [&qpdf.stderr, &flpdf.stderr] {
let stderr = String::from_utf8_lossy(stderr);
assert_eq!(stderr.matches("empty object treated as null").count(), 1);
assert_eq!(
stderr.matches("operation succeeded with warnings").count(),
1
);
}
let warning_suffix = |stderr: &[u8]| {
String::from_utf8_lossy(stderr)
.lines()
.find(|line| line.contains("empty object treated as null"))
.and_then(|line| line.split_once("(object"))
.map(|(_, suffix)| suffix.to_string())
.unwrap()
};
assert_eq!(warning_suffix(&flpdf.stderr), warning_suffix(&qpdf.stderr));
}
#[test]
fn json_qpdf_dangling_fixture_selectors_and_all_match_raw_rules() {
let input = "../../tests/fixtures/compat/dangling-body-one-page.pdf";
let cases: [(&str, &[&str], &[&str]); 3] = [
(
"trailer",
&["--json=2", "--json-key=qpdf", "--json-object=trailer"],
&["trailer"],
),
(
"dangling",
&["--json=2", "--json-key=qpdf", "--json-object=99"],
&["obj:99 0 R"],
),
(
"all",
&["--json=2", "--json-key=qpdf"],
&["obj:4 0 R", "obj:99 0 R", "trailer"],
),
];
for (label, args, expected_keys) in cases {
let output = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(input)
.output()
.unwrap();
assert!(output.status.success(), "{label}");
assert!(output.stderr.is_empty(), "{label}");
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json_qpdf_metadata(&json)["maxobjectid"], 99, "{label}");
let map = json["qpdf"][1].as_object().unwrap();
if label == "all" {
assert!(expected_keys.iter().all(|key| map.contains_key(*key)));
} else {
assert_eq!(
map.keys().map(String::as_str).collect::<Vec<_>>(),
expected_keys,
"{label}"
);
}
if label != "trailer" {
assert_eq!(map["obj:99 0 R"], serde_json::json!({"value": null}));
}
if label == "all" {
let catalog = &map["obj:4 0 R"]["value"];
assert!(catalog.get("/Bad").is_none());
assert!(catalog.get("/Junk").is_none());
assert_eq!(catalog["/Nested"], serde_json::json!({}));
assert_eq!(catalog["/ArrZero"], serde_json::json!([null]));
}
}
}
#[test]
#[ignore = "live qpdf 11.9.0 dangling selectors/all oracle"]
fn live_qpdf_dangling_fixture_selectors_and_all_match() {
let input = "../../tests/fixtures/compat/dangling-body-one-page.pdf";
let cases: [&[&str]; 3] = [
&["--json=2", "--json-key=qpdf", "--json-object=trailer"],
&["--json=2", "--json-key=qpdf", "--json-object=99"],
&["--json=2", "--json-key=qpdf"],
];
for args in cases {
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(input)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(input)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code(), "{args:?}");
assert_eq!(flpdf.stderr, qpdf.stderr, "{args:?}");
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"], "{args:?}");
}
}
#[test]
#[ignore = "live qpdf 11.9.0 compressed dangling JSON oracle"]
fn live_qpdf_compressed_dangling_json_matches() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("input.pdf");
let compressed = temp.path().join("compressed.pdf");
std::fs::write(&input, dangling_container_json_pdf()).unwrap();
let generate = std::process::Command::new("qpdf")
.args(["--object-streams=generate"])
.arg(&input)
.arg(&compressed)
.output()
.unwrap();
assert!(
generate.status.success(),
"{}",
String::from_utf8_lossy(&generate.stderr)
);
assert!(contains(&std::fs::read(&compressed).unwrap(), b"/ObjStm"));
let args = ["--json=2", "--json-key=qpdf"];
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(&compressed)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(&compressed)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code());
assert_eq!(flpdf.stderr, qpdf.stderr);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(flpdf_json["qpdf"], qpdf_json["qpdf"]);
}
#[test]
#[ignore = "live qpdf 11.9.0 selected JSON section oracle"]
fn live_qpdf_selected_json_sections_match_construction_side_effects() {
struct Case {
label: &'static str,
args: &'static [&'static str],
has_outlines: bool,
has_qpdf: bool,
warned: bool,
}
let cases = [
Case {
label: "qpdf only",
args: &["--json=2", "--json-key=qpdf"],
has_outlines: false,
has_qpdf: true,
warned: false,
},
Case {
label: "outlines only",
args: &["--json=2", "--json-key=outlines"],
has_outlines: true,
has_qpdf: false,
warned: true,
},
Case {
label: "outlines plus qpdf",
args: &["--json=2", "--json-key=outlines", "--json-key=qpdf"],
has_outlines: true,
has_qpdf: true,
warned: true,
},
Case {
label: "full",
args: &["--json=2"],
has_outlines: true,
has_qpdf: true,
warned: true,
},
];
for case in cases {
let fixture = fixture_with_repaired_name_tree_and_stream();
let qpdf = std::process::Command::new("qpdf")
.args(case.args)
.arg(fixture.path())
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(case.args)
.arg(fixture.path())
.output()
.unwrap();
assert_eq!(
flpdf.status.code(),
qpdf.status.code(),
"{}: qpdf stderr={} flpdf stderr={}",
case.label,
String::from_utf8_lossy(&qpdf.stderr),
String::from_utf8_lossy(&flpdf.stderr)
);
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
let qpdf_keys = qpdf_json.as_object().unwrap().keys().collect::<Vec<_>>();
let flpdf_keys = flpdf_json.as_object().unwrap().keys().collect::<Vec<_>>();
assert_eq!(flpdf_keys, qpdf_keys, "{}", case.label);
assert_eq!(
flpdf_json.get("outlines").is_some(),
case.has_outlines,
"{}",
case.label
);
assert_eq!(
flpdf_json.get("qpdf").is_some(),
case.has_qpdf,
"{}",
case.label
);
if case.has_outlines {
assert_eq!(
flpdf_json["outlines"][0]["dest"], qpdf_json["outlines"][0]["dest"],
"{}",
case.label
);
}
if case.has_qpdf {
assert_eq!(
json_qpdf_metadata(&flpdf_json),
json_qpdf_metadata(&qpdf_json),
"{}: complete qpdf metadata",
case.label
);
for object in ["obj:1 0 R", "obj:8 0 R"] {
assert_eq!(
flpdf_json["qpdf"][1][object], qpdf_json["qpdf"][1][object],
"{}: {object}",
case.label
);
}
}
let qpdf_stderr = String::from_utf8_lossy(&qpdf.stderr);
let flpdf_stderr = String::from_utf8_lossy(&flpdf.stderr);
let expected_count = usize::from(case.warned);
assert_eq!(
qpdf_stderr
.matches("attempting to repair after error:")
.count(),
expected_count,
"{}: {qpdf_stderr}",
case.label
);
assert_eq!(
flpdf_stderr
.matches("attempting to repair after error:")
.count(),
expected_count,
"{}: {flpdf_stderr}",
case.label
);
assert_eq!(
qpdf_stderr
.matches("operation succeeded with warnings")
.count(),
expected_count,
"{}: {qpdf_stderr}",
case.label
);
assert_eq!(
flpdf_stderr
.matches("operation succeeded with warnings")
.count(),
expected_count,
"{}: {flpdf_stderr}",
case.label
);
if case.warned {
assert!(
qpdf_stderr
.find("attempting to repair after error:")
.unwrap()
< qpdf_stderr
.find("operation succeeded with warnings")
.unwrap(),
"{}: {qpdf_stderr}",
case.label
);
assert!(
flpdf_stderr
.find("attempting to repair after error:")
.unwrap()
< flpdf_stderr
.find("operation succeeded with warnings")
.unwrap(),
"{}: {flpdf_stderr}",
case.label
);
}
}
}
#[test]
#[ignore = "live qpdf 11.9.0 JSON metadata oracle"]
fn live_qpdf_json_metadata_matches_inherited_resources_and_outline_allocation() {
let inherited = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/inherited-resources-one-page.pdf");
let allocation = fixture_with_name_tree_repair_allocations();
let cases = [
(
"inherited qpdf only",
inherited.as_path(),
&["--json=2", "--json-key=qpdf"][..],
),
(
"inherited pages then qpdf",
inherited.as_path(),
&["--json=2", "--json-key=pages", "--json-key=qpdf"][..],
),
(
"inherited pagelabels then qpdf",
inherited.as_path(),
&["--json=2", "--json-key=pagelabels", "--json-key=qpdf"][..],
),
(
"inherited acroform then qpdf",
inherited.as_path(),
&["--json=2", "--json-key=acroform", "--json-key=qpdf"][..],
),
(
"inherited attachments then qpdf",
inherited.as_path(),
&["--json=2", "--json-key=attachments", "--json-key=qpdf"][..],
),
(
"inherited encrypt then qpdf",
inherited.as_path(),
&["--json=2", "--json-key=encrypt", "--json-key=qpdf"][..],
),
(
"inherited outlines then qpdf",
inherited.as_path(),
&["--json=2", "--json-key=outlines", "--json-key=qpdf"][..],
),
(
"inherited non-page combination",
inherited.as_path(),
&[
"--json=2",
"--json-key=attachments",
"--json-key=encrypt",
"--json-key=qpdf",
][..],
),
(
"inherited mixed combination",
inherited.as_path(),
&[
"--json=2",
"--json-key=qpdf",
"--json-key=attachments",
"--json-key=outlines",
][..],
),
(
"inherited full document",
inherited.as_path(),
&["--json=2"][..],
),
(
"outline repair allocation",
allocation.path(),
&["--json=2", "--json-key=outlines", "--json-key=qpdf"][..],
),
];
for (label, fixture, args) in cases {
let qpdf = std::process::Command::new("qpdf")
.args(args)
.arg(fixture)
.output()
.unwrap();
let flpdf = Command::cargo_bin("flpdf")
.unwrap()
.args(args)
.arg(fixture)
.output()
.unwrap();
assert_eq!(flpdf.status.code(), qpdf.status.code(), "{label}");
let qpdf_json: serde_json::Value = serde_json::from_slice(&qpdf.stdout).unwrap();
let flpdf_json: serde_json::Value = serde_json::from_slice(&flpdf.stdout).unwrap();
assert_eq!(
json_qpdf_metadata(&flpdf_json),
json_qpdf_metadata(&qpdf_json),
"{label}"
);
assert_eq!(
flpdf_json["qpdf"][1]["obj:3 0 R"]["value"].get("/Resources"),
qpdf_json["qpdf"][1]["obj:3 0 R"]["value"].get("/Resources"),
"{label}"
);
}
}
#[test]
fn json_processing_warnings_do_not_repeat_open_time_warnings() {
let fixture = corrupt_xref_repaired_name_tree_fixture();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--repair", "--json=2", "--json-key=outlines"])
.arg(fixture.path())
.assert()
.code(3);
let output = assert.get_output();
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
let open_warning = stderr
.lines()
.find(|line| line.starts_with("WARNING:") && !line.contains("attempting to repair"))
.unwrap_or_else(|| panic!("missing open-time warning in {stderr}"));
assert_eq!(
stderr.lines().filter(|line| *line == open_warning).count(),
1,
"{stderr}"
);
assert_eq!(
stderr.matches("attempting to repair after error:").count(),
1
);
assert_eq!(
stderr
.matches("flpdf: operation succeeded with warnings")
.count(),
1
);
}
#[test]
fn json_output_error_emits_recorded_processing_warning_before_fatal_error() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let output_directory = tempfile::tempdir().unwrap();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-key=outlines", "--json-output"])
.arg(output_directory.path())
.arg(fixture.path())
.assert()
.code(2);
let output = assert.get_output();
let stderr = String::from_utf8_lossy(&output.stderr);
let warning = stderr
.find("attempting to repair after error:")
.unwrap_or_else(|| panic!("missing repair warning in {stderr}"));
let fatal = stderr
.rfind("flpdf:")
.unwrap_or_else(|| panic!("missing fatal error in {stderr}"));
assert!(warning < fatal, "{stderr}");
assert_eq!(
stderr.matches("attempting to repair after error:").count(),
1
);
assert!(!stderr.contains("operation succeeded with warnings"));
assert!(output.stdout.is_empty());
}
#[test]
fn json_side_file_error_emits_recorded_warning_after_complete_json_before_fatal_error() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let temp = tempfile::tempdir().unwrap();
let missing_prefix = temp.path().join("missing").join("stream");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args([
"--json=2",
"--json-stream-data=file",
"--json-stream-prefix",
])
.arg(&missing_prefix)
.arg(fixture.path())
.assert()
.code(2);
let output = assert.get_output();
let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(json["outlines"][0]["dest"][0], "3 0 R");
let stderr = String::from_utf8_lossy(&output.stderr);
let warning = stderr
.find("attempting to repair after error:")
.unwrap_or_else(|| panic!("missing repair warning in {stderr}"));
let fatal = stderr
.rfind("flpdf:")
.unwrap_or_else(|| panic!("missing fatal error in {stderr}"));
assert!(warning < fatal, "{stderr}");
assert_eq!(
stderr.matches("attempting to repair after error:").count(),
1
);
assert!(!stderr.contains("operation succeeded with warnings"));
}
#[test]
fn json_and_side_files_complete_before_warning_exit_three() {
let fixture = fixture_with_repaired_name_tree_and_stream();
let temp = tempfile::tempdir().unwrap();
let json_path = temp.path().join("out.json");
let prefix = temp.path().join("stream");
let mut cmd = Command::cargo_bin("flpdf").unwrap();
let assert = cmd
.args(["--json=2", "--json-output"])
.arg(&json_path)
.args(["--json-stream-data=file", "--json-stream-prefix"])
.arg(&prefix)
.arg(fixture.path())
.assert()
.code(3);
let output = assert.get_output();
assert!(output.stdout.is_empty());
let json: serde_json::Value =
serde_json::from_slice(&std::fs::read(&json_path).unwrap()).unwrap();
assert_eq!(json["outlines"][0]["dest"][0], "3 0 R");
assert!(std::path::Path::new(&format!("{}-6", prefix.display())).is_file());
let stderr = String::from_utf8_lossy(&output.stderr);
let warning = stderr.find("attempting to repair after error:").unwrap();
let summary = stderr
.find("flpdf: operation succeeded with warnings")
.unwrap();
assert!(warning < summary, "{stderr}");
}
#[test]
fn show_fonts_prints_summary() {
let fixture = fixture_with_metadata_outline_and_fonts();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-fonts", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("F1"))
.stdout(predicate::str::contains("F2"));
}
#[test]
fn show_fonts_prints_inline_dictionary_fonts() {
let fixture = fixture_with_inline_font_dictionary();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-fonts", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("FDirect"))
.stdout(predicate::str::contains("type: /Font"));
}
#[test]
fn show_npages_prints_total_pages() {
let fixture = fixture_with_nested_pages();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-npages", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("2"));
}
#[test]
fn show_pages_lists_each_page() {
let fixture = fixture_with_nested_pages();
let mut cmd = Command::cargo_bin("flpdf").unwrap();
cmd.args(["--show-pages", fixture.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("page 1: 3 0 R"))
.stdout(predicate::str::contains("page 2: 6 0 R"))
.stdout(predicate::str::contains("media-box: [ 0 0 595.28 842 ]"))
.stdout(predicate::str::contains("media-box: [ 0 0 200 100 ]"));
}
fn fixture_with_metadata_outline_and_fonts() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let object1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines 3 0 R /Metadata 4 0 R /Info 5 0 R >>\nendobj\n";
let object2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [6 0 R] >>\nendobj\n";
let object3 = b"3 0 obj\n<< /Type /Outlines /First 10 0 R /Last 10 0 R /Count 1 >>\nendobj\n";
let metadata_data = b"<xmpmeta>Fixture metadata</xmpmeta>";
let object4 = format!(
"4 0 obj\n<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n{}\nendstream\nendobj\n",
metadata_data.len(),
String::from_utf8_lossy(metadata_data)
)
.into_bytes();
let object5 = b"5 0 obj\n<< /Title (Fixture PDF) /Creator (flpdf) >>\nendobj\n";
let object6 = b"6 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /F1 7 0 R /F2 8 0 R >> >> /MediaBox [0 0 612 792] /Contents 9 0 R >>\nendobj\n";
let object7 = b"7 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>\nendobj\n";
let object8 = b"8 0 obj\n<< /Type /Font /Subtype /Type0 /BaseFont /Courier >>\nendobj\n";
let content_data = b"BT /F1 12 Tf (Hello) Tj ET";
let object9 = format!(
"9 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
content_data.len(),
String::from_utf8_lossy(content_data)
)
.into_bytes();
let object10 =
b"10 0 obj\n<< /Title (Chapter One) /Parent 3 0 R /Dest [6 0 R /Fit] >>\nendobj\n";
let objects = vec![
object1.to_vec(),
object2.to_vec(),
object3.to_vec(),
object4,
object5.to_vec(),
object6.to_vec(),
object7.to_vec(),
object8.to_vec(),
object9,
object10.to_vec(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::with_capacity(objects.len() + 1);
for object in &objects {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(format!("{:010} 65535 f\n", 0).as_bytes());
for &offset in &offsets {
bytes.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R /Info 5 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
start_xref
)
.as_bytes(),
);
let file = fixture.as_file_mut();
file.write_all(&bytes).unwrap();
fixture
}
fn fixture_with_short_first_name_tree_pair() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let objects = [
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R /Names << /Dests << /Names [(m)] >> >> >>\nendobj\n".as_slice(),
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n".as_slice(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".as_slice(),
b"4 0 obj\n<< /Type /Outlines /First 5 0 R /Last 5 0 R /Count 1 >>\nendobj\n".as_slice(),
b"5 0 obj\n<< /Title (One) /Parent 4 0 R /Dest (m) >>\nendobj\n".as_slice(),
];
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());
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{start_xref}\n%%EOF\n").as_bytes(),
);
fixture.as_file_mut().write_all(&bytes).unwrap();
fixture
}
fn fixture_with_name_tree_repair_allocations() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let pairs = (0..33)
.map(|index| format!("(k{index:02}) [3 0 R /Fit]"))
.collect::<Vec<_>>()
.join(" ");
let objects = vec![
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R /Names << /Dests << /Kids [8 0 R] >> >> >>\nendobj\n".to_vec(),
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n".to_vec(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n".to_vec(),
b"4 0 obj\n<< /Type /Outlines /First 5 0 R /Last 5 0 R /Count 1 >>\nendobj\n".to_vec(),
b"5 0 obj\n<< /Title (One) /Parent 4 0 R /Dest (k17) >>\nendobj\n".to_vec(),
b"6 0 obj\nnull\nendobj\n".to_vec(),
b"7 0 obj\nnull\nendobj\n".to_vec(),
format!("8 0 obj\n<< /Names [{pairs}] >>\nendobj\n").into_bytes(),
];
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());
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start_xref}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
fixture.as_file_mut().write_all(&bytes).unwrap();
fixture
}
fn fixture_with_repaired_name_tree_and_stream() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let objects = [
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R /Names << /Dests << /Kids [8 0 R] >> >> >>\nendobj\n".as_slice(),
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n".as_slice(),
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 6 0 R >>\nendobj\n".as_slice(),
b"4 0 obj\n<< /Type /Outlines /First 5 0 R /Last 5 0 R /Count 1 >>\nendobj\n".as_slice(),
b"5 0 obj\n<< /Title (One) /Parent 4 0 R /Dest (shape) >>\nendobj\n".as_slice(),
b"6 0 obj\n<< /Length 0 >>\nstream\n\nendstream\nendobj\n".as_slice(),
b"7 0 obj\nnull\nendobj\n".as_slice(),
b"8 0 obj\n<< /Names [(shape) [3 0 R /Fit]] >>\nendobj\n".as_slice(),
];
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());
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start_xref}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
fixture.as_file_mut().write_all(&bytes).unwrap();
fixture
}
fn corrupt_xref_repaired_name_tree_fixture() -> tempfile::NamedTempFile {
let fixture = fixture_with_repaired_name_tree_and_stream();
let mut bytes = std::fs::read(fixture.path()).unwrap();
let xref = bytes
.windows(4)
.position(|window| window == b"xref")
.expect("fixture must contain xref");
bytes[xref + 2] = b'z';
std::fs::write(fixture.path(), bytes).unwrap();
fixture
}
fn fixture_with_unresolvable_outline() -> tempfile::NamedTempFile {
let fixture = fixture_with_metadata_outline_and_fonts();
let mut bytes = std::fs::read(fixture.path()).unwrap();
let marker = b"3 0 obj\n<< /Type /Outlines";
let start = bytes
.windows(marker.len())
.position(|window| window == marker)
.unwrap();
bytes[start + b"3 0 obj\n".len()] = b'@';
std::fs::write(fixture.path(), bytes).unwrap();
fixture
}
fn fixture_with_inline_font_dictionary() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let object1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
let object2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n";
let object3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << /Font << /FDirect << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> >> >> /MediaBox [0 0 612 792] /Contents 4 0 R >>\nendobj\n";
let content_data = b"HelloPDF\n";
let object4 = format!(
"4 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
content_data.len(),
String::from_utf8_lossy(content_data)
)
.into_bytes();
let mut offsets = Vec::new();
let objects: Vec<Vec<u8>> = vec![
object1.to_vec(),
object2.to_vec(),
object3.to_vec(),
object4.to_vec(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
for object in &objects {
offsets.push(bytes.len());
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(format!("{:010} 65535 f\n", 0).as_bytes());
for &offset in &offsets {
bytes.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
start_xref
)
.as_bytes(),
);
fixture.as_file_mut().write_all(&bytes).unwrap();
fixture
}
fn fixture_with_orphan_object() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let object1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
let object2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n";
let object3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R >>\nendobj\n";
let content_data = b"Hello PDF";
let object4 = format!(
"4 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
content_data.len(),
String::from_utf8_lossy(content_data)
)
.into_bytes();
let object5 = b"5 0 obj\n<< /Type /Orphan >>\nendobj\n";
let objects = vec![
object1.to_vec(),
object2.to_vec(),
object3.to_vec(),
object4,
object5.to_vec(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::with_capacity(objects.len() + 1);
for object in &objects {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(format!("{:010} 65535 f\n", 0).as_bytes());
for &offset in &offsets {
bytes.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
start_xref
)
.as_bytes(),
);
fixture.as_file_mut().write_all(&bytes).unwrap();
fixture
}
fn fixture_with_nested_pages() -> tempfile::NamedTempFile {
let mut fixture = tempfile::NamedTempFile::new().unwrap();
let object1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
let object2 = b"2 0 obj\n<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] /MediaBox [0 0 595.28 841.89] >>\nendobj\n";
let object3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595.28 842] /Contents 5 0 R >>\nendobj\n";
let object4 = b"4 0 obj\n<< /Type /Pages /Count 1 /Kids [6 0 R] /Rotate 90 >>\nendobj\n";
let object5 = b"5 0 obj\n<< /Length 14 >>\nstream\nBT (one) Tj ET\nendstream\nendobj\n";
let object6 = b"6 0 obj\n<< /Type /Page /Parent 4 0 R /Rotate 90 /MediaBox [0 0 200 100] /Contents 7 0 R >>\nendobj\n";
let object7 = b"7 0 obj\n<< /Length 15 >>\nstream\nBT (two) Tj ET\nendstream\nendobj\n";
let objects = vec![
object1.to_vec(),
object2.to_vec(),
object3.to_vec(),
object4.to_vec(),
object5.to_vec(),
object6.to_vec(),
object7.to_vec(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::with_capacity(objects.len() + 1);
for object in &objects {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(format!("{:010} 65535 f\n", 0).as_bytes());
for &offset in &offsets {
bytes.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
start_xref
)
.as_bytes(),
);
fixture.write_all(&bytes).unwrap();
fixture
}
fn corrupt_xref_pdf() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let obj1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n".to_vec();
let obj2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec();
let obj3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R >>\nendobj\n".to_vec();
let obj4 = b"4 0 obj\n<< /Length 0 >>\nstream\nendstream\nendobj\n".to_vec();
let mut offsets = Vec::new();
for object in &[obj1, obj2, obj3, obj4] {
offsets.push(bytes.len());
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f\n");
for offset in &offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{start_xref}\n%%EOF\n",
offsets.len() + 1
)
.as_bytes(),
);
let mut corrupted = bytes;
let Some(pos) = corrupted.windows(4).position(|window| window == b"xref") else {
unreachable!("fixture should contain xref token")
};
if let Some(byte) = corrupted.get_mut(pos + 2) {
*byte = b'z';
}
corrupted
}
fn signed_acroform_pdf() -> Vec<u8> {
let objects: Vec<&[u8]> = vec![
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n",
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
b"4 0 obj\n<< /Fields [5 0 R] /SigFlags 3 >>\nendobj\n",
b"5 0 obj\n<< /FT /Sig /T (Approval) /V 6 0 R /Rect [0 0 0 0] >>\nendobj\n",
b"6 0 obj\n<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 10 20 30] /Contents <00> >>\nendobj\n",
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for object in objects {
offsets.push(bytes.len());
bytes.extend_from_slice(object);
}
let xref_start = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!("trailer\n<< /Size 7 /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n").as_bytes(),
);
bytes
}
fn signed_perms_docmdp_pdf() -> Vec<u8> {
let objects: Vec<&[u8]> = vec![
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Perms << /DocMDP 4 0 R >> >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n",
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
b"4 0 obj\n<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 10 20 30] /Contents <00> >>\nendobj\n",
];
build_classic_pdf(&objects)
}
fn signed_widget_acroform_pdf() -> Vec<u8> {
let objects: Vec<&[u8]> = vec![
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n",
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [5 0 R] >>\nendobj\n",
b"4 0 obj\n<< /Fields [5 0 R] /SigFlags 3 >>\nendobj\n",
b"5 0 obj\n<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval) /V 6 0 R /Rect [10 20 30 40] /P 3 0 R >>\nendobj\n",
b"6 0 obj\n<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange [0 10 20 30] /Contents <00> >>\nendobj\n",
];
build_classic_pdf(&objects)
}
fn build_classic_pdf(objects: &[&[u8]]) -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for object in objects {
offsets.push(bytes.len());
bytes.extend_from_slice(object);
}
let size = offsets.len() + 1;
let xref_start = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {size}\n").as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for offset in &offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!("trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n")
.as_bytes(),
);
bytes
}
fn empty_object_json_pdf() -> Vec<u8> {
build_classic_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Probe 7 0 R >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>\nendobj\n",
b"4 0 obj\nnull\nendobj\n",
b"5 0 obj\nnull\nendobj\n",
b"6 0 obj\nnull\nendobj\n",
b"7 0 obj\nendobj\n",
])
}
fn top_level_bare_reference_json_pdf() -> Vec<u8> {
build_classic_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n",
b"3 0 obj\n<< /Answer 42 >>\nendobj\n",
b"4 0 obj\n3 0 R\nendobj\n",
])
}
fn dangling_container_json_pdf() -> Vec<u8> {
build_classic_pdf(&[
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Nested << /Drop 99 2 R /Array [99 2 R 0 0 R] >> >>\nendobj\n",
b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>\nendobj\n",
b"4 0 obj\n<< /Length 0 /Drop 99 2 R >>\nstream\nendstream\nendobj\n",
b"5 0 obj\n<< /Held 99 2 R >>\nendobj\n",
b"6 0 obj\n<< /Next 7 0 R >>\nendobj\n",
b"7 0 obj\n<< /Next 6 0 R >>\nendobj\n",
])
}
fn dangling_generation_free_json_pdf() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let objects: [(u32, u16, &[u8]); 5] = [
(
1,
0,
b"<< /Type /Catalog /Pages 2 0 R /Live 8 1 R /Stale 8 0 R /Freed 20 7 R >>",
),
(2, 0, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(
3,
0,
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>",
),
(8, 1, b"<< /Value 1 >>"),
(9, 0, b"<< /Lazy 88 4 R >>"),
];
let mut offsets = Vec::new();
for (number, generation, body) in objects {
offsets.push((number, generation, bytes.len()));
bytes.extend_from_slice(format!("{number} {generation} obj\n").as_bytes());
bytes.extend_from_slice(body);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(b"xref\n0 1\n0000000000 65535 f \n");
for (number, generation, offset) in offsets {
bytes
.extend_from_slice(format!("{number} 1\n{offset:010} {generation:05} n \n").as_bytes());
}
bytes.extend_from_slice(b"20 1\n0000000000 00007 f \n");
bytes.extend_from_slice(b"200 1\n0000000000 00007 f \n");
bytes.extend_from_slice(
format!("trailer\n<< /Size 201 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
);
bytes
}
fn trailer_dangling_json_pdf() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let objects: [(u32, u16, &[u8]); 3] = [
(1, 0, b"<< /Type /Catalog /Pages 2 0 R >>"),
(2, 0, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(
3,
0,
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>",
),
];
let mut offsets = Vec::new();
for (number, generation, body) in objects {
offsets.push((number, generation, bytes.len()));
bytes.extend_from_slice(format!("{number} {generation} obj\n").as_bytes());
bytes.extend_from_slice(body);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(b"xref\n0 1\n0000000000 65535 f \n");
for (number, generation, offset) in offsets {
bytes
.extend_from_slice(format!("{number} 1\n{offset:010} {generation:05} n \n").as_bytes());
}
bytes.extend_from_slice(b"200 1\n0000000000 00007 f \n");
bytes.extend_from_slice(
format!(
"trailer\n<< /Size 201 /Root 1 0 R /Info 99 0 R /Gen 88 4 R /Zero 0 0 R /BadGen 77 65535 R >>\nstartxref\n{xref}\n%%EOF\n"
)
.as_bytes(),
);
bytes
}
fn incremental_last_startxref(bytes: &[u8]) -> u64 {
let marker = b"startxref\n";
let start = bytes
.windows(marker.len())
.rposition(|window| window == marker)
.unwrap()
+ marker.len();
let end = bytes[start..]
.iter()
.position(|byte| *byte == b'\n')
.map(|length| start + length)
.unwrap();
std::str::from_utf8(&bytes[start..end])
.unwrap()
.parse()
.unwrap()
}
fn append_json_classic_increment(
bytes: &mut Vec<u8>,
objects: &[(u32, u16, &str)],
free_entries: &[(u32, u16)],
size: u32,
trailer_extra: &str,
previous_xref: u64,
) -> u64 {
let mut offsets = Vec::new();
for (number, generation, body) in objects {
offsets.push((*number, *generation, bytes.len()));
bytes.extend_from_slice(format!("{number} {generation} obj\n{body}\nendobj\n").as_bytes());
}
let xref = bytes.len() as u64;
bytes.extend_from_slice(b"xref\n");
for (number, generation, offset) in offsets {
bytes
.extend_from_slice(format!("{number} 1\n{offset:010} {generation:05} n \n").as_bytes());
}
for (number, generation) in free_entries {
bytes.extend_from_slice(format!("{number} 1\n0000000000 {generation:05} f \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {size} /Root 1 0 R /Prev {previous_xref} {trailer_extra} >>\nstartxref\n{xref}\n%%EOF\n"
)
.as_bytes(),
);
xref
}
fn incremental_json_base(trailer_extra: &str) -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let objects: [(u32, &[u8]); 3] = [
(1, b"<< /Type /Catalog /Pages 2 0 R >>"),
(2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>"),
];
let mut offsets = Vec::new();
for (number, body) in objects {
offsets.push((number, bytes.len()));
bytes.extend_from_slice(format!("{number} 0 obj\n").as_bytes());
bytes.extend_from_slice(body);
bytes.extend_from_slice(b"\nendobj\n");
}
let xref = bytes.len();
bytes.extend_from_slice(b"xref\n0 1\n0000000000 65535 f \n");
for (number, offset) in offsets {
bytes.extend_from_slice(format!("{number} 1\n{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!("trailer\n<< /Size 4 /Root 1 0 R {trailer_extra} >>\nstartxref\n{xref}\n%%EOF\n")
.as_bytes(),
);
bytes
}
fn multigeneration_historical_trailer_json_pdf() -> Vec<u8> {
let mut bytes = incremental_json_base(
"/Info 99 0 R /OldGen 88 4 R /Freed 20 7 R /Zero 0 0 R /BadGen 77 65535 R",
);
let oldest = incremental_last_startxref(&bytes);
let middle = append_json_classic_increment(
&mut bytes,
&[(4, 0, "null")],
&[],
5,
"/Info 60 1 R /Middle 70 3 R",
oldest,
);
append_json_classic_increment(
&mut bytes,
&[(5, 0, "null")],
&[(20, 7), (200, 7)],
201,
"/Newest 50 2 R",
middle,
);
bytes
}
fn historical_xref_stream_json_pdf_with_options(
free_generation: u16,
previous: Option<u64>,
latest_trailer_extra: &str,
) -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (number, body) in [
(1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>"),
] {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_stream_offset = bytes.len() as u32;
let mut entries = Vec::new();
for (kind, offset, generation) in [
(0u8, 0u32, u16::MAX),
(1, offsets[0], 0),
(1, offsets[1], 0),
(1, offsets[2], 0),
(1, xref_stream_offset, 0),
] {
entries.push(kind);
entries.extend_from_slice(&offset.to_be_bytes());
entries.extend_from_slice(&generation.to_be_bytes());
}
let prev = previous.map_or_else(String::new, |offset| format!("/Prev {offset} "));
bytes.extend_from_slice(
format!(
"4 0 obj\n<< /Type /XRef /Size 5 /Root 1 0 R /Info 99 0 R /Gen 88 4 R {prev}/W [1 4 2] /Index [0 5] /Length {} >>\nstream\n",
entries.len()
)
.as_bytes(),
);
bytes.extend_from_slice(&entries);
bytes.extend_from_slice(
format!("\nendstream\nendobj\nstartxref\n{xref_stream_offset}\n%%EOF\n").as_bytes(),
);
append_json_classic_increment(
&mut bytes,
&[(5, 0, "null")],
&[(4, free_generation)],
6,
latest_trailer_extra,
u64::from(xref_stream_offset),
);
bytes
}
fn historical_xref_stream_json_pdf_with_free_generation(free_generation: u16) -> Vec<u8> {
historical_xref_stream_json_pdf_with_options(free_generation, None, "")
}
fn malformed_late_prev_after_valid_sections_json_pdf() -> Vec<u8> {
let mut bytes = historical_xref_stream_json_pdf_with_options(1, Some(9), "/Middle 70 3 R");
let middle = incremental_last_startxref(&bytes);
append_json_classic_increment(
&mut bytes,
&[(6, 0, "null")],
&[],
7,
"/Newest 50 2 R",
middle,
);
bytes
}
fn historical_xref_stream_json_pdf() -> Vec<u8> {
historical_xref_stream_json_pdf_with_free_generation(1)
}
fn latest_xref_stream_json_pdf() -> Vec<u8> {
let bytes = historical_xref_stream_json_pdf();
let eof = bytes
.windows(b"%%EOF\n".len())
.position(|window| window == b"%%EOF\n")
.unwrap()
+ b"%%EOF\n".len();
bytes[..eof].to_vec()
}
fn reused_historical_xref_stream_json_pdf() -> Vec<u8> {
let mut bytes = latest_xref_stream_json_pdf();
let previous = incremental_last_startxref(&bytes);
append_json_classic_increment(
&mut bytes,
&[(4, 0, "<< /Marker /New >>"), (5, 0, "null")],
&[],
6,
"",
previous,
);
bytes
}
fn repeated_historical_xref_stream_json_pdf() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (number, body) in [
(1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>"),
] {
offsets.push(bytes.len() as u32);
bytes.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
}
let append_xref_stream = |bytes: &mut Vec<u8>,
marker: &str,
info: u32,
previous: Option<u64>| {
let xref_stream_offset = bytes.len() as u32;
let mut entries = Vec::new();
for (kind, offset, generation) in [
(0u8, 0u32, u16::MAX),
(1, offsets[0], 0),
(1, offsets[1], 0),
(1, offsets[2], 0),
(1, xref_stream_offset, 0),
] {
entries.push(kind);
entries.extend_from_slice(&offset.to_be_bytes());
entries.extend_from_slice(&generation.to_be_bytes());
}
let prev = previous.map_or_else(String::new, |value| format!("/Prev {value} "));
bytes.extend_from_slice(
format!(
"4 0 obj\n<< /Type /XRef /Size 5 /Root 1 0 R /Marker /{marker} /Info {info} 0 R {prev}/W [1 4 2] /Index [0 5] /Length {} >>\nstream\n",
entries.len()
)
.as_bytes(),
);
bytes.extend_from_slice(&entries);
bytes.extend_from_slice(
format!("\nendstream\nendobj\nstartxref\n{xref_stream_offset}\n%%EOF\n").as_bytes(),
);
u64::from(xref_stream_offset)
};
let oldest = append_xref_stream(&mut bytes, "Old", 91, None);
let nearest = append_xref_stream(&mut bytes, "Near", 92, Some(oldest));
append_json_classic_increment(&mut bytes, &[(5, 0, "null")], &[(4, 1)], 6, "", nearest);
bytes
}
fn circular_historical_trailer_json_pdf() -> Vec<u8> {
let mut bytes = incremental_json_base("/Info 99 0 R /Prev 0000000000");
let old_xref = incremental_last_startxref(&bytes);
let latest_xref =
append_json_classic_increment(&mut bytes, &[(4, 0, "null")], &[], 5, "", old_xref);
let marker = b"/Prev 0000000000";
let start = bytes
.windows(marker.len())
.position(|window| window == marker)
.unwrap()
+ b"/Prev ".len();
bytes[start..start + 10].copy_from_slice(format!("{latest_xref:010}").as_bytes());
bytes
}
fn acroform_fields_len(pdf: &mut Pdf<BufReader<File>>) -> Option<usize> {
let root_ref = pdf.root_ref()?;
let Object::Dictionary(catalog) = pdf.resolve(root_ref).ok()? else {
return None;
};
let acroform = resolve_maybe_indirect(pdf, catalog.get("AcroForm")?.clone())?;
let fields = resolve_maybe_indirect(pdf, acroform.as_dict()?.get("Fields")?.clone())?;
Some(fields.as_array()?.len())
}
fn resolve_maybe_indirect(pdf: &mut Pdf<BufReader<File>>, object: Object) -> Option<Object> {
match object {
Object::Reference(object_ref) => pdf.resolve(object_ref).ok(),
direct => Some(direct),
}
}
fn encrypted_v1_owner_password_fixture() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let obj1_offset = bytes.len();
bytes.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let obj2_offset = bytes.len();
bytes.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Count 0 >>\nendobj\n");
let xref_offset = bytes.len();
let trailer = b"trailer\n<< /Size 3 /Root 1 0 R /Encrypt << /Filter /Standard /V 1 /R 2 /Length 40 /P -3904 /O <94e8094419662a774442fb072e3d9f19e9d130ec09a4d0061e78fe920f7ab62f> /U <13f520c882d052bf57b416b747c13979bded7ea31240fe41928852aca3894c49> >> /ID [<000102030405060708090a0b0c0d0e0f><000102030405060708090a0b0c0d0e0f>] >>\nstartxref\n";
bytes.extend_from_slice(format!("xref\n0 3\n0000000000 65535 f \n{obj1_offset:010} 00000 n \n{obj2_offset:010} 00000 n \n").as_bytes());
bytes.extend_from_slice(trailer);
bytes.extend_from_slice(xref_offset.to_string().as_bytes());
bytes.extend_from_slice(b"\n%%EOF\n");
bytes
}
fn one_page_pdf_with_unused_resource() -> Vec<u8> {
let content_data = b"BT /F1 12 Tf (Hello) Tj ET";
let obj1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
let obj2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n";
let obj3_bytes = b"3 0 obj\n<< /Type /Page /Parent 2 0 R \
/Resources << /Font << /F1 4 0 R /F2 5 0 R >> >> \
/MediaBox [0 0 612 792] /Contents 6 0 R >>\nendobj\n";
let obj4 = b"4 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>\nendobj\n";
let obj5 = b"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n";
let obj6 = format!(
"6 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
content_data.len(),
String::from_utf8_lossy(content_data)
);
let objects: Vec<&[u8]> = vec![obj1, obj2, obj3_bytes, obj4, obj5, obj6.as_bytes()];
let mut bytes = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for obj in &objects {
offsets.push(bytes.len());
bytes.extend_from_slice(obj);
}
let xref_start = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for &off in &offsets {
bytes.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
bytes
}
fn two_page_pdf_with_multi_contents() -> Vec<u8> {
let obj1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
let obj2 = b"2 0 obj\n<< /Type /Pages /Count 2 /Kids [3 0 R 6 0 R] >>\nendobj\n";
let obj3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents [4 0 R 5 0 R] >>\nendobj\n";
let c1 = b"q Q";
let obj4 = format!(
"4 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
c1.len(),
String::from_utf8_lossy(c1)
);
let c2 = b"q Q";
let obj5 = format!(
"5 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
c2.len(),
String::from_utf8_lossy(c2)
);
let obj6 = b"6 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 7 0 R >>\nendobj\n";
let c3 = b"q Q";
let obj7 = format!(
"7 0 obj\n<< /Length {} >>\nstream\n{}\nendstream\nendobj\n",
c3.len(),
String::from_utf8_lossy(c3)
);
let objects: Vec<Vec<u8>> = vec![
obj1.to_vec(),
obj2.to_vec(),
obj3.to_vec(),
obj4.into_bytes(),
obj5.into_bytes(),
obj6.to_vec(),
obj7.into_bytes(),
];
let mut bytes = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for obj in &objects {
offsets.push(bytes.len());
bytes.extend_from_slice(obj);
}
let xref_start = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for &off in &offsets {
bytes.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
bytes
}
#[test]
fn rewrite_compress_streams_y_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--compress-streams=y", "--full-rewrite"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_compress_streams_n_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--compress-streams=n", "--full-rewrite"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_normalize_content_y_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--normalize-content=y"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_normalize_content_n_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--normalize-content=n"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_coalesce_contents_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, two_page_pdf_with_multi_contents()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--coalesce-contents"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn top_level_coalesce_contents_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, two_page_pdf_with_multi_contents()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--coalesce-contents"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn top_level_coalesce_contents_conflicts_with_check() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", "--coalesce-contents", "in.pdf"])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_conflicts_with_add_attachment() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--coalesce-contents",
"--add-attachment",
"attach.pdf",
"--",
"in.pdf",
"out.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_conflicts_with_copy_attachments_from() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--coalesce-contents",
"--copy-attachments-from",
"donor.pdf",
"in.pdf",
"out.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_conflicts_with_linearize() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["--linearize", "--coalesce-contents", "in.pdf", "out.pdf"])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_conflicts_with_pages() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--coalesce-contents",
"in.pdf",
"--pages",
".",
"--",
"out.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_conflicts_with_rotate() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--coalesce-contents",
"--rotate",
"+90:1",
"in.pdf",
"out.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_conflicts_with_split_pages() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--coalesce-contents",
"--split-pages",
"1",
"in.pdf",
"out.pdf",
])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_accepts_collate_alone() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, two_page_pdf_with_multi_contents()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--coalesce-contents", "--collate=1"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
}
#[test]
fn top_level_coalesce_contents_conflicts_with_empty() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["--coalesce-contents", "--empty", "in.pdf", "out.pdf"])
.assert()
.failure()
.code(2);
}
#[test]
fn top_level_coalesce_contents_with_overlay_underlay_trailing_position() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let overlay = temp.path().join("over.pdf");
let underlay = temp.path().join("under.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, two_page_pdf_with_multi_contents()).unwrap();
std::fs::write(&overlay, two_page_pdf_with_multi_contents()).unwrap();
std::fs::write(&underlay, two_page_pdf_with_multi_contents()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args([
"--static-id",
"--qdf",
"--no-original-object-ids",
"--verbose",
])
.arg(&input)
.arg(&output)
.arg("--overlay")
.arg(&overlay)
.args(["--from=", "--repeat=r2,r1", "--"])
.arg("--underlay")
.arg(&underlay)
.args(["--from=z-1", "--", "--coalesce-contents"])
.assert()
.success();
assert!(output.exists());
}
#[test]
fn rewrite_remove_unreferenced_resources_auto_accepted() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_with_unused_resource()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-unreferenced-resources=auto"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_remove_unreferenced_resources_yes_accepted() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_with_unused_resource()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-unreferenced-resources=yes"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_remove_unreferenced_resources_no_accepted() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--remove-unreferenced-resources=no"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_newline_before_endstream_y_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--newline-before-endstream=y", "--full-rewrite"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_newline_before_endstream_n_accepted_and_produces_valid_output() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--newline-before-endstream=n", "--full-rewrite"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_help_shows_compress_streams_default_y() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--help"])
.assert()
.success()
.stdout(predicate::str::contains("compress-streams"))
.stdout(predicate::str::contains("default: y"));
}
#[test]
fn rewrite_help_shows_normalize_content_default_n() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--help"])
.assert()
.success()
.stdout(predicate::str::contains("normalize-content"))
.stdout(predicate::str::contains("default: n"));
}
#[test]
fn rewrite_help_shows_remove_unreferenced_resources_default_auto() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--help"])
.assert()
.success()
.stdout(predicate::str::contains("remove-unreferenced-resources"))
.stdout(predicate::str::contains("default: auto"));
}
#[test]
fn rewrite_help_shows_newline_before_endstream_default_never() {
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--help"])
.assert()
.success()
.stdout(predicate::str::contains("newline-before-endstream"))
.stdout(predicate::str::contains("default: never"));
}
#[test]
fn rewrite_full_rewrite_with_compress_n_and_newline_n() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_bytes()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--full-rewrite",
"--compress-streams=n",
"--newline-before-endstream=n",
])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_coalesce_and_normalize_content_combination() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, two_page_pdf_with_multi_contents()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--coalesce-contents", "--normalize-content=y"])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn rewrite_normalize_and_remove_unreferenced_combination() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, one_page_pdf_with_unused_resource()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--normalize-content=y",
"--remove-unreferenced-resources=yes",
])
.arg(&input)
.arg(&output)
.assert()
.success();
assert!(output.exists());
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
const THREE_PAGE: &str = "../../tests/fixtures/compat/three-page.pdf";
const TWO_PAGE: &str = "../../tests/fixtures/compat/two-page.pdf";
fn outline_dests_three_page_pdf() -> Vec<u8> {
let c1 = b"BT /F1 12 Tf 1 1 Td (P1) Tj ET";
let c2 = b"BT /F2 12 Tf 1 1 Td (P2) Tj ET";
let c3 = b"BT /F3 12 Tf 1 1 Td (P3) Tj ET";
let mut out: Vec<u8> = b"%PDF-1.5\n".to_vec();
let mut offs: std::collections::BTreeMap<u32, u64> = std::collections::BTreeMap::new();
let emit =
|out: &mut Vec<u8>, offs: &mut std::collections::BTreeMap<u32, u64>, n: u32, body: &str| {
offs.insert(n, out.len() as u64);
out.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
};
let emit_stream = |out: &mut Vec<u8>,
offs: &mut std::collections::BTreeMap<u32, u64>,
n: u32,
data: &[u8]| {
offs.insert(n, out.len() as u64);
out.extend_from_slice(
format!("{n} 0 obj\n<< /Length {} >>\nstream\n", data.len()).as_bytes(),
);
out.extend_from_slice(data);
out.extend_from_slice(b"\nendstream\nendobj\n");
};
emit(
&mut out,
&mut offs,
1,
"<< /Type /Catalog /Pages 2 0 R /Outlines 20 0 R /Names 25 0 R >>",
);
emit(
&mut out,
&mut offs,
2,
"<< /Type /Pages /Kids [3 0 R 6 0 R 9 0 R] /Count 3 >>",
);
emit(&mut out, &mut offs, 3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /Font 5 0 R >> >>");
emit_stream(&mut out, &mut offs, 4, c1);
emit(&mut out, &mut offs, 5, "<< /F1 30 0 R >>");
emit(&mut out, &mut offs, 6, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 7 0 R /Resources << /Font 8 0 R >> >>");
emit_stream(&mut out, &mut offs, 7, c2);
emit(&mut out, &mut offs, 8, "<< /F2 31 0 R >>");
emit(&mut out, &mut offs, 9, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 10 0 R /Resources << /Font 11 0 R >> >>");
emit_stream(&mut out, &mut offs, 10, c3);
emit(&mut out, &mut offs, 11, "<< /F3 32 0 R >>");
emit(
&mut out,
&mut offs,
20,
"<< /Type /Outlines /First 21 0 R /Last 23 0 R /Count 3 >>",
);
emit(
&mut out,
&mut offs,
21,
"<< /Title (Item1) /Parent 20 0 R /Dest [3 0 R /Fit] /Next 22 0 R >>",
);
emit(
&mut out,
&mut offs,
22,
"<< /Title (Item2) /Parent 20 0 R /Dest [6 0 R /Fit] /Prev 21 0 R /Next 23 0 R >>",
);
emit(
&mut out,
&mut offs,
23,
"<< /Title (Item3) /Parent 20 0 R /Dest [9 0 R /Fit] /Prev 22 0 R >>",
);
emit(&mut out, &mut offs, 25, "<< /Dests 26 0 R >>");
emit(
&mut out,
&mut offs,
26,
"<< /Names [(d1) [3 0 R /Fit] (d2) [6 0 R /Fit] (d3) [9 0 R /Fit]] >>",
);
emit(
&mut out,
&mut offs,
30,
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
);
emit(
&mut out,
&mut offs,
31,
"<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>",
);
emit(
&mut out,
&mut offs,
32,
"<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >>",
);
let max_obj = 32u32;
let xref_start = out.len() as u64;
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", max_obj + 1).as_bytes());
for i in 1..=max_obj {
match offs.get(&i) {
Some(off) => out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes()),
None => out.extend_from_slice(b"0000000000 00000 f \n"),
}
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n",
max_obj + 1
)
.as_bytes(),
);
out
}
#[test]
fn pages_extracts_subset_top_level_syntax() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", ".", "2-3", "--"])
.arg(&output)
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-npages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("2"));
}
#[test]
fn pages_dot_shorthand_resolves_to_primary_input() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", ".", "1", "--"])
.arg(&output)
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-npages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::starts_with("1"));
}
#[test]
fn rotate_single_spec_rewrites_all_pages() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.arg(&output)
.args(["--rotate=180"])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-pages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("rotate: 180"));
}
#[test]
fn split_pages_produces_chunked_outputs() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.arg(&output)
.args(["--split-pages=2"])
.assert()
.success();
assert!(temp.path().join("out-1-2.pdf").exists());
assert!(temp.path().join("out-3-3.pdf").exists());
assert!(!output.exists(), "unsplit single file must not be written");
}
#[test]
fn collate_without_pages_is_accepted_noop() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.arg(&output)
.args(["--collate=2"])
.assert()
.success();
assert!(output.exists());
}
#[test]
fn pages_then_rotate_targets_output_page_numbering() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", ".", "2-3", "--"])
.arg("--rotate=+90:1")
.arg(&output)
.assert()
.success();
let show = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-pages", output.to_str().unwrap()])
.assert()
.success();
let stdout = String::from_utf8_lossy(&show.get_output().stdout).into_owned();
let p1 = stdout.find("page 1:").unwrap();
let p2 = stdout.find("page 2:").unwrap();
assert!(
stdout[p1..p2].contains("rotate: 90"),
"page 1 should be rotated 90: {stdout}"
);
assert!(
stdout[p2..].contains("rotate: 0"),
"page 2 should stay 0: {stdout}"
);
}
#[test]
fn pages_then_split_pages_combined() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", ".", "1-3", "--"])
.arg("--split-pages=2")
.arg(&output)
.assert()
.success();
assert!(temp.path().join("out-1-2.pdf").exists());
assert!(temp.path().join("out-3-3.pdf").exists());
}
#[test]
fn pages_same_file_repeated_is_single_source() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", ".", "1", ".", "3", "--"])
.arg(&output)
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-npages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::starts_with("2"));
}
#[test]
fn pages_same_file_spelled_differently_is_single_source() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let alt_spelling = "../../tests/fixtures/compat/./three-page.pdf";
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", alt_spelling, "1", ".", "3", "--"])
.arg(&output)
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-npages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::starts_with("2"));
}
#[test]
fn pages_extraction_remaps_outline_and_prunes_resources_via_cli() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, outline_dests_three_page_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.arg(&input)
.args(["--pages", ".", "2", "--"])
.arg(&output)
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-npages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::starts_with("1"));
let outline = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-outline", output.to_str().unwrap()])
.assert()
.success();
let outline_txt = String::from_utf8_lossy(&outline.get_output().stdout).into_owned();
assert!(
outline_txt.contains("Item1")
&& outline_txt.contains("Item2")
&& outline_txt.contains("Item3"),
"all outline items must be kept (null-out): {outline_txt}"
);
let raw = std::fs::read(&output).unwrap();
let txt = String::from_utf8_lossy(&raw);
assert!(
txt.contains("(d1)") && txt.contains("(d2)") && txt.contains("(d3)"),
"named destinations d1/d2/d3 must all be kept (null-out parity): {txt}"
);
assert!(
txt.contains("Courier"),
"kept page's font missing from output"
);
assert!(
!txt.contains("Helvetica"),
"dropped page 1 font (Helvetica) was not pruned"
);
assert!(
!txt.contains("Times-Roman"),
"dropped page 3 font (Times-Roman) was not pruned"
);
Command::cargo_bin("flpdf")
.unwrap()
.args(["--check", output.to_str().unwrap()])
.assert()
.success();
}
#[test]
fn pages_extraction_keeps_all_when_full_range_selected() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("in.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, outline_dests_three_page_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.arg(&input)
.args(["--pages", ".", "1-3", "--"])
.arg(&output)
.assert()
.success();
let outline = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-outline", output.to_str().unwrap()])
.assert()
.success();
let txt = String::from_utf8_lossy(&outline.get_output().stdout).into_owned();
assert!(txt.contains("Item1") && txt.contains("Item2") && txt.contains("Item3"));
}
#[test]
fn pages_cross_document_merge_is_rejected_actionably() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.args(["--pages", ".", "1", TWO_PAGE, "2", "--"])
.arg(&output)
.assert()
.failure()
.stderr(predicate::str::contains("cross-document"))
.stderr(predicate::str::contains("not supported"));
}
#[test]
fn empty_flag_is_rejected_actionably() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg(THREE_PAGE)
.arg("--empty")
.args(["--pages", ".", "1", "--"])
.arg(&output)
.assert()
.failure()
.stderr(predicate::str::contains("--empty"))
.stderr(predicate::str::contains("not implemented"));
}
#[test]
fn rewrite_subcommand_supports_pages() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.arg("rewrite")
.arg(THREE_PAGE)
.arg(&output)
.args(["--pages", ".", "1-2", "--"])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-npages", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::starts_with("2"));
}
#[test]
fn pages_help_text_mirrors_qpdf_terms() {
Command::cargo_bin("flpdf")
.unwrap()
.arg("--help")
.assert()
.success()
.stdout(predicate::str::contains("--pages"))
.stdout(predicate::str::contains("--rotate"))
.stdout(predicate::str::contains("--split-pages"))
.stdout(predicate::str::contains("--collate"));
}
fn minimal_pdf_temp() -> tempfile::NamedTempFile {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(include_bytes!("../../../tests/fixtures/minimal.pdf"))
.unwrap();
f
}
#[test]
fn add_attachment_default_key_is_basename() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("hello.txt");
std::fs::write(&attachment, b"hello world").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("hello.txt"));
}
#[test]
fn add_attachment_explicit_key_and_filename() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("data.bin");
std::fs::write(&attachment, b"binary data").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=mykey",
"--filename=renamed.bin",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("mykey"));
}
#[test]
fn add_attachment_non_ascii_basename_uses_ascii_fallback_and_unicode_uf() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("レポート.pdf");
std::fs::write(&attachment, b"unicode filename payload").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=unicode-key",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-attachment=unicode-key", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::eq(b"unicode filename payload" as &[u8]));
let file = File::open(&output).unwrap();
let mut pdf = Pdf::open(BufReader::new(file)).unwrap();
let entries = flpdf::embedded_files::list_embedded_files(&mut pdf).unwrap();
let (_, filespec_ref) = entries
.iter()
.find(|(key, _)| key == b"unicode-key")
.expect("unicode attachment must be present");
let fs_obj = pdf.resolve(*filespec_ref).unwrap();
let Object::Dictionary(fs_dict) = fs_obj else {
panic!("expected filespec dictionary");
};
assert_eq!(
fs_dict.get("F"),
Some(&Object::String(b"____.pdf".to_vec())),
"/F must be ASCII-safe fallback"
);
assert_eq!(
fs_dict.get("UF"),
Some(&Object::String(encode_utf16be("レポート.pdf"))),
"/UF must preserve the Unicode basename"
);
}
#[test]
fn add_attachment_subflag_mimetype_description_afrelationship() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("report.pdf");
std::fs::write(&attachment, b"%PDF-1.4 report").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=report",
"--mimetype=application/pdf",
"--description=Annual Report",
"--afrelationship=Data",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", "--verbose", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("report"));
}
#[test]
fn add_attachment_subflag_creationdate_and_moddate() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("dated.txt");
std::fs::write(&attachment, b"dated content").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=dated",
"--creationdate=D:20240101120000",
"--moddate=D:20240201130000",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", "--verbose", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("dated"));
}
#[test]
fn add_attachment_replace_flag_overwrites_existing() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("file.txt");
std::fs::write(&attachment, b"first content").unwrap();
let out1 = temp.path().join("out1.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=myfile",
"--",
out1.to_str().unwrap(),
])
.assert()
.success();
std::fs::write(&attachment, b"second content").unwrap();
let out2 = temp.path().join("out2.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
out1.to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=myfile",
"--replace",
"--",
out2.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", out2.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("myfile"));
}
#[test]
fn add_attachment_without_replace_fails_on_duplicate_key() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("file.txt");
std::fs::write(&attachment, b"content").unwrap();
let out1 = temp.path().join("out1.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=dupkey",
"--",
out1.to_str().unwrap(),
])
.assert()
.success();
let out2 = temp.path().join("out2.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
out1.to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=dupkey",
"--",
out2.to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("dupkey"))
.stderr(predicate::str::contains("--replace"));
}
#[test]
fn remove_attachment_removes_existing_key() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("removeme.txt");
std::fs::write(&attachment, b"to be removed").unwrap();
let out1 = temp.path().join("out1.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=removeme",
"--",
out1.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", out1.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("removeme"));
let out2 = temp.path().join("out2.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
out1.to_str().unwrap(),
"--remove-attachment=removeme",
out2.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", out2.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::is_empty());
}
#[test]
fn remove_attachment_errors_on_missing_key() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--remove-attachment=nosuchkey",
output.to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("nosuchkey"));
}
#[test]
fn list_attachments_empty_document() {
let input = minimal_pdf_temp();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", input.path().to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::is_empty());
}
#[test]
fn list_attachments_shows_one_entry() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("listed.txt");
std::fs::write(&attachment, b"listed content").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=listed",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("listed"));
}
#[test]
fn list_attachments_verbose_shows_extra_info() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("verbose.txt");
std::fs::write(&attachment, b"verbose content").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=verbose",
"--mimetype=text/plain",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
let plain_out = Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", output.to_str().unwrap()])
.output()
.unwrap()
.stdout;
let verbose_out = Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", "--verbose", output.to_str().unwrap()])
.output()
.unwrap()
.stdout;
assert!(
verbose_out.len() >= plain_out.len(),
"verbose output should be at least as long as plain output"
);
assert!(
String::from_utf8_lossy(&verbose_out).contains("verbose"),
"verbose output should contain the key"
);
}
#[test]
fn show_attachment_writes_to_stdout() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let payload = b"payload bytes for stdout test";
let attachment = temp.path().join("stdout.txt");
std::fs::write(&attachment, payload).unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=showme",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
let stdout_bytes = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-attachment=showme", output.to_str().unwrap()])
.output()
.unwrap()
.stdout;
assert_eq!(stdout_bytes, payload);
}
#[test]
fn show_attachment_writes_to_file_with_o_flag() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let payload = b"payload bytes for file test";
let attachment = temp.path().join("tofile.txt");
std::fs::write(&attachment, payload).unwrap();
let out_pdf = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=tofile",
"--",
out_pdf.to_str().unwrap(),
])
.assert()
.success();
let extracted = temp.path().join("extracted.txt");
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--show-attachment=tofile",
"--show-attachment-to",
extracted.to_str().unwrap(),
out_pdf.to_str().unwrap(),
])
.assert()
.success();
let read_back = std::fs::read(&extracted).unwrap();
assert_eq!(read_back, payload);
}
#[test]
fn show_attachment_errors_on_missing_key() {
let input = minimal_pdf_temp();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--show-attachment=nosuchkey",
input.path().to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("nosuchkey"));
}
#[test]
fn copy_attachments_from_copies_all_entries() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let source_input = minimal_pdf_temp();
let att1 = temp.path().join("att1.txt");
std::fs::write(&att1, b"attachment one").unwrap();
let source_with_one = temp.path().join("src1.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
source_input.path().to_str().unwrap(),
"--add-attachment",
att1.to_str().unwrap(),
"--key=att1",
"--",
source_with_one.to_str().unwrap(),
])
.assert()
.success();
let att2 = temp.path().join("att2.txt");
std::fs::write(&att2, b"attachment two").unwrap();
let source_with_two = temp.path().join("src2.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
source_with_one.to_str().unwrap(),
"--add-attachment",
att2.to_str().unwrap(),
"--key=att2",
"--",
source_with_two.to_str().unwrap(),
])
.assert()
.success();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--copy-attachments-from",
source_with_two.to_str().unwrap(),
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("att1"))
.stdout(predicate::str::contains("att2"));
}
#[test]
fn copy_attachments_from_with_prefix() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let source_input = minimal_pdf_temp();
let att = temp.path().join("original.txt");
std::fs::write(&att, b"original content").unwrap();
let source = temp.path().join("source.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
source_input.path().to_str().unwrap(),
"--add-attachment",
att.to_str().unwrap(),
"--key=original",
"--",
source.to_str().unwrap(),
])
.assert()
.success();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--copy-attachments-from",
source.to_str().unwrap(),
"--prefix=pfx-",
"--",
output.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", output.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("pfx-original"));
}
#[test]
fn attachment_round_trip_add_list_show_remove_copy() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let payload = b"round-trip payload bytes \x00\x01\x02";
let att = temp.path().join("rtrip.bin");
std::fs::write(&att, payload).unwrap();
let after_add = temp.path().join("after_add.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
att.to_str().unwrap(),
"--key=rtrip",
"--",
after_add.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", after_add.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("rtrip"));
let stdout_bytes = Command::cargo_bin("flpdf")
.unwrap()
.args(["--show-attachment=rtrip", after_add.to_str().unwrap()])
.output()
.unwrap()
.stdout;
assert_eq!(stdout_bytes, payload.to_vec());
let after_remove = temp.path().join("after_remove.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
after_add.to_str().unwrap(),
"--remove-attachment=rtrip",
after_remove.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", after_remove.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::is_empty());
let after_copy = temp.path().join("after_copy.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
after_remove.to_str().unwrap(),
"--copy-attachments-from",
after_add.to_str().unwrap(),
"--",
after_copy.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.args(["--list-attachments", after_copy.to_str().unwrap()])
.assert()
.success()
.stdout(predicate::str::contains("rtrip"));
}
#[test]
fn attachment_help_text_contains_expected_flags() {
Command::cargo_bin("flpdf")
.unwrap()
.arg("--help")
.assert()
.success()
.stdout(predicate::str::contains("--add-attachment"))
.stdout(predicate::str::contains("--remove-attachment"))
.stdout(predicate::str::contains("--list-attachments"))
.stdout(predicate::str::contains("--show-attachment"))
.stdout(predicate::str::contains("--copy-attachments-from"));
}
#[test]
fn attachment_ops_are_mutually_exclusive() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("a.txt");
std::fs::write(&attachment, b"a").unwrap();
let src = minimal_pdf_temp();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=a",
"--",
"--copy-attachments-from",
src.path().to_str().unwrap(),
"--",
output.to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("cannot be used with"))
.stderr(predicate::str::contains("panicked").not());
}
#[test]
fn add_attachment_non_ascii_date_is_clean_error_not_panic() {
let temp = tempfile::tempdir().unwrap();
let input = minimal_pdf_temp();
let attachment = temp.path().join("d.txt");
std::fs::write(&attachment, b"d").unwrap();
let output = temp.path().join("out.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.args([
input.path().to_str().unwrap(),
"--add-attachment",
attachment.to_str().unwrap(),
"--key=d",
"--creationdate=D:20240101120000",
"--",
output.to_str().unwrap(),
])
.assert()
.failure()
.stderr(predicate::str::contains("invalid PDF date"))
.stderr(predicate::str::contains("panicked").not());
}
fn corrupt_xref_with_info_pdf() -> Vec<u8> {
let mut bytes = b"%PDF-1.7\n".to_vec();
let obj1 = b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Info 5 0 R >>\nendobj\n".to_vec();
let obj2 = b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n".to_vec();
let obj3 = b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R >>\nendobj\n".to_vec();
let obj4 = b"4 0 obj\n<< /Length 0 >>\nstream\nendstream\nendobj\n".to_vec();
let obj5 = b"5 0 obj\n<< /Title (Corrupt fixture) /Creator (flpdf) >>\nendobj\n".to_vec();
let mut offsets = Vec::new();
for object in [&obj1, &obj2, &obj3, &obj4, &obj5] {
offsets.push(bytes.len());
bytes.extend_from_slice(object);
}
let start_xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n", offsets.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f\n");
for offset in &offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R /Info 5 0 R >>\nstartxref\n{start_xref}\n%%EOF\n",
offsets.len() + 1
)
.as_bytes(),
);
let mut corrupted = bytes;
let Some(pos) = corrupted.windows(4).position(|window| window == b"xref") else {
unreachable!("fixture should contain xref token")
};
if let Some(byte) = corrupted.get_mut(pos + 2) {
*byte = b'z';
}
corrupted
}
#[test]
fn top_level_no_original_object_ids_is_accepted() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let assert = Command::cargo_bin("flpdf")
.unwrap()
.args([
"--no-original-object-ids",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert.stderr(predicate::str::contains("unrecognized").not());
assert!(output.exists());
}
#[test]
fn rewrite_no_original_object_ids_is_accepted() {
let temp = tempfile::tempdir().unwrap();
let output = temp.path().join("out.pdf");
let assert = Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--no-original-object-ids",
"../../tests/fixtures/minimal.pdf",
output.to_str().unwrap(),
])
.assert()
.success();
assert.stderr(predicate::str::contains("unrecognized").not());
assert!(output.exists());
}
#[test]
fn no_original_object_ids_default_behavior_unchanged() {
let temp = tempfile::tempdir().unwrap();
let baseline = temp.path().join("baseline.pdf");
let with_flag = temp.path().join("with_flag.pdf");
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args([
"rewrite",
"--static-id",
"../../tests/fixtures/minimal.pdf",
baseline.to_str().unwrap(),
])
.assert()
.success();
Command::cargo_bin("flpdf")
.unwrap()
.env("FLPDF_STATIC_ID_QUIET", "1")
.args([
"rewrite",
"--static-id",
"--no-original-object-ids",
"../../tests/fixtures/minimal.pdf",
with_flag.to_str().unwrap(),
])
.assert()
.success();
let baseline_bytes = std::fs::read(&baseline).unwrap();
let with_flag_bytes = std::fs::read(&with_flag).unwrap();
assert_eq!(
baseline_bytes, with_flag_bytes,
"rewrite --no-original-object-ids must not change output bytes \
(no QDF-comment emission point exists yet; flpdf-9hc.6)"
);
}
#[test]
fn no_original_object_ids_conflicts_with_json() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"--json=2",
"--no-original-object-ids",
"../../tests/fixtures/minimal.pdf",
])
.assert()
.failure()
.stderr(predicate::str::contains("cannot be used with"))
.stderr(predicate::str::contains("--json"))
.stderr(predicate::str::contains("--no-original-object-ids"));
}
fn assemble_pdf(objects: &[Vec<u8>]) -> Vec<u8> {
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();
bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
bytes.extend_from_slice(b"0000000000 65535 f \n");
for &offset in &offsets {
bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
start_xref
)
.as_bytes(),
);
bytes
}
fn rotated_page_pdf() -> 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 /Rotate 90 \
/MediaBox [0 0 200 100] /Contents 4 0 R >>\nendobj\n"
.to_vec(),
b"4 0 obj\n<< /Length 14 >>\nstream\nBT (hi) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
fn tx_form_pdf_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 (field1) \
/V (Hello World) /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_form_pdf_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 (field1) \
/V (Hello) /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 tx_form_pdf_with_null_ap_n() -> 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 (field1) \
/V (Hello World) /Rect [100 700 300 720] /P 3 0 R \
/AP << /N null >> >>\nendobj\n"
.to_vec(),
b"5 0 obj\n<< /Length 14 >>\nstream\nBT (pg) Tj ET\nendstream\nendobj\n".to_vec(),
])
}
#[test]
fn rewrite_generate_appearances_replaces_null_ap_n() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("form.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_form_pdf_with_null_ap_n()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget = first_widget_ref(&mut pdf);
let mut helper = AnnotationObjectHelper::new(widget, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("widget should still have an /AP");
let n = ap.get("N").cloned();
assert!(
matches!(n, Some(Object::Reference(_)) | Some(Object::Stream(_))),
"null /AP/N must be replaced by a real appearance, got {n:?}"
);
let n_resolved = match n {
Some(Object::Reference(r)) => pdf.resolve(r).unwrap(),
Some(other) => other,
None => panic!("/N missing"),
};
assert!(
matches!(n_resolved, Object::Stream(_)),
"/AP/N must resolve to a Form XObject stream"
);
}
#[test]
fn rewrite_flatten_rotation_removes_rotate() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("rotated.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, rotated_page_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--flatten-rotation"])
.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 page = pdf.resolve(page_refs[0]).unwrap();
let Object::Dictionary(dict) = page else {
panic!("page is not a dictionary");
};
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:?}"
);
}
#[test]
fn rewrite_generate_appearances_adds_ap_n() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("form.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_form_pdf_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--generate-appearances"])
.arg(&input)
.arg(&output)
.assert()
.success();
let mut pdf = Pdf::open(BufReader::new(File::open(&output).unwrap())).unwrap();
let widget = first_widget_ref(&mut pdf);
let mut helper = AnnotationObjectHelper::new(widget, &mut pdf);
let ap = helper
.appearance()
.unwrap()
.expect("widget should have an /AP after --generate-appearances");
assert!(
ap.get("N").is_some(),
"widget /AP should carry an /N normal appearance"
);
}
#[test]
fn rewrite_flatten_annotations_all_removes_widget_from_annots() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("form.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_form_pdf_with_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--flatten-annotations=all"])
.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(),
"flattened widget should be removed from /Annots, found {} annotation(s)",
annots.len()
);
}
#[test]
fn rewrite_generate_then_flatten_cooperate() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("form.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, tx_form_pdf_without_ap()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--generate-appearances",
"--flatten-annotations=all",
])
.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(),
"widget should be generated-then-flattened away, found {} annotation(s)",
annots.len()
);
}
#[test]
fn rewrite_flatten_annotations_rejects_invalid_mode() {
Command::cargo_bin("flpdf")
.unwrap()
.args([
"rewrite",
"--flatten-annotations=bogus",
"../../tests/fixtures/minimal.pdf",
"/tmp/flpdf-flatten-invalid-out.pdf",
])
.assert()
.failure()
.stderr(predicate::str::contains("flatten-annotations"));
}
#[test]
fn rewrite_linearize_with_flatten_is_rejected() {
let temp = tempfile::tempdir().unwrap();
let input = temp.path().join("rotated.pdf");
let output = temp.path().join("out.pdf");
std::fs::write(&input, rotated_page_pdf()).unwrap();
Command::cargo_bin("flpdf")
.unwrap()
.args(["rewrite", "--linearize", "--flatten-rotation"])
.arg(&input)
.arg(&output)
.assert()
.failure()
.stderr(predicate::str::contains("--linearize cannot be combined"));
}