use super::resource_pruning::{
shared_resource_finding_message, should_remove_unreferenced_resources_with_report,
RemoveUnreferencedResources,
};
use super::QPDFJob;
use crate::page_label_document_helper::{copy_raw_page_label_entries, RawPageLabelEntry};
use crate::{
Error, PageDocumentHelper, PageInput, PageObjectHelper, Pdf, PdfWriter, Result,
WriterConfiguration,
};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub(crate) struct SplitPageOptions {
pub(crate) chunk_size: usize,
qpdf_chunk_size: Option<i32>,
pub(crate) output_template: PathBuf,
pub(crate) input_path: Option<PathBuf>,
pub(crate) deterministic_id: bool,
pub(crate) writer_configuration: WriterConfiguration,
pub(crate) verbose: bool,
remove_unreferenced_resources: RemoveUnreferencedResources,
}
impl SplitPageOptions {
#[must_use]
pub(crate) fn new(chunk_size: usize, output_template: impl Into<PathBuf>) -> Self {
Self {
chunk_size,
qpdf_chunk_size: None,
output_template: output_template.into(),
input_path: None,
deterministic_id: false,
writer_configuration: WriterConfiguration::default(),
verbose: false,
remove_unreferenced_resources: RemoveUnreferencedResources::Auto,
}
}
#[must_use]
pub(crate) fn with_qpdf_chunk_size(mut self, chunk_size: i32) -> Self {
self.qpdf_chunk_size = Some(chunk_size);
self
}
#[must_use]
pub(crate) fn with_input_path(mut self, input_path: impl Into<PathBuf>) -> Self {
self.input_path = Some(input_path.into());
self
}
#[cfg(test)]
#[must_use]
pub(crate) fn with_deterministic_id(mut self, deterministic_id: bool) -> Self {
self.deterministic_id = deterministic_id;
self
}
#[must_use]
pub(crate) fn with_writer_configuration(mut self, configuration: WriterConfiguration) -> Self {
self.writer_configuration = configuration;
self
}
#[must_use]
pub(crate) fn with_verbose(mut self, verbose: bool) -> Self {
self.verbose = verbose;
self
}
#[must_use]
pub(crate) fn with_remove_unreferenced_resources(
mut self,
mode: RemoveUnreferencedResources,
) -> Self {
self.remove_unreferenced_resources = mode;
self
}
}
fn qpdf_split_page_size(value: i32) -> Result<usize> {
usize::try_from(value).map_err(|_| {
Error::System(format!(
"integer out of range converting {value} from a {}-byte signed type to a {}-byte unsigned type",
std::mem::size_of::<i32>(),
std::mem::size_of::<usize>(),
))
})
}
impl QPDFJob {
pub(crate) fn split_pages<R: std::io::Read + std::io::Seek + 'static>(
&mut self,
source: &mut Pdf<R>,
options: SplitPageOptions,
) -> Result<Vec<PathBuf>> {
let original_suppress_warnings = source.suppress_warnings();
source.set_logger(self.logger());
source.set_suppress_warnings(self.warnings_suppressed() || original_suppress_warnings);
let result = self.split_pages_with_suppression_installed(source, options);
source.set_suppress_warnings(original_suppress_warnings);
result
}
fn split_pages_with_suppression_installed<R: std::io::Read + std::io::Seek + 'static>(
&mut self,
source: &mut Pdf<R>,
options: SplitPageOptions,
) -> Result<Vec<PathBuf>> {
if options.qpdf_chunk_size.is_none() && options.chunk_size == 0 {
return Err(Error::Unsupported(
"split_pages: chunk_size must be >= 1".to_owned(),
));
}
let remove_resources = match options.remove_unreferenced_resources {
RemoveUnreferencedResources::No => false,
RemoveUnreferencedResources::Yes => true,
RemoveUnreferencedResources::Auto => {
let verbose = options.verbose;
let logger = self.logger();
if verbose {
let mut message = Vec::new();
message.extend_from_slice(self.message_prefix_bytes());
message.extend_from_slice(b": ");
message.extend_from_slice(self.input_name_bytes());
message.extend_from_slice(b": checking for shared resources\n");
logger.info(message)?;
}
let should_remove =
should_remove_unreferenced_resources_with_report(source, |finding| {
if verbose {
logger.info(shared_resource_finding_message(finding))
} else {
Ok(())
}
})?;
if verbose && !should_remove {
let mut message = Vec::new();
message.extend_from_slice(self.message_prefix_bytes());
message.extend_from_slice(b": no shared resources found\n");
logger.info(message)?;
}
should_remove
}
};
if remove_resources {
PageDocumentHelper::new(source).remove_unreferenced_resources()?;
}
let pages = crate::pages::page_refs(source)?;
let chunk_size = options
.qpdf_chunk_size
.map_or(Ok(options.chunk_size), qpdf_split_page_size)?;
debug_assert_ne!(chunk_size, 0);
let page_count = pages.len();
let width = digit_width(u32::try_from(page_count).map_err(|_| {
Error::Unsupported("split_pages: page count exceeds qpdf's naming range".to_owned())
})?);
let has_page_labels = source.page_labels().has_page_labels()?;
let has_acro_form = source.acroform()?.has_acro_form()?;
let source_version =
crate::parse_pdf_version(source.version()).map(|version| version.get_version().0);
let source_extension_level = i64::from(source.get_extension_level()?);
let mut writer_configuration = options.writer_configuration;
let mut written = Vec::new();
for chunk_start in (0..page_count).step_by(chunk_size) {
let chunk_end = chunk_start.saturating_add(chunk_size).min(page_count);
let first_page = u32::try_from(chunk_start + 1).map_err(|_| {
Error::Unsupported("split_pages: page number exceeds qpdf's naming range".into())
})?;
let last_page = u32::try_from(chunk_end).map_err(|_| {
Error::Unsupported("split_pages: page number exceeds qpdf's naming range".into())
})?;
let output_path = chunk_output_path(
&options.output_template,
first_page,
last_page,
width,
chunk_size,
);
if let Some(input_path) = options.input_path.as_deref() {
if same_file_if_existing(input_path, &output_path)? {
return Err(Error::Unsupported(format!(
"split pages would overwrite input file with {}",
output_path.display()
)));
}
}
let mut output = Pdf::empty()?;
output.set_suppress_warnings(source.suppress_warnings());
for &page_ref in &pages[chunk_start..chunk_end] {
let rebuild = PageDocumentHelper::new(&mut output)
.add_page(PageInput::foreign(source, page_ref), false)?;
let new_page = rebuild
.new_kids
.last()
.copied()
.ok_or(Error::Missing("split output page"))?;
if has_acro_form {
let source_page = source.get_object_handle(page_ref);
PageObjectHelper::new(new_page, &mut output)
.fix_copied_annotations_from(source_page, source)?; }
}
if has_page_labels {
let start = i64::try_from(chunk_start).map_err(|_| {
Error::Unsupported("split_pages: label start exceeds i64".to_owned())
})?;
let end = i64::try_from(chunk_end - 1).map_err(|_| {
Error::Unsupported("split_pages: label end exceeds i64".to_owned())
})?;
let source_id = source.unique_id();
let mut raw_entries = Vec::new();
source
.page_labels()
.get_labels_for_page_range(start, end, 0, &mut raw_entries)?;
let entries = raw_entries
.into_iter()
.map(|(output_index, label)| {
Ok(RawPageLabelEntry {
index: output_index,
source_id,
source_is_primary: false,
label,
})
})
.collect::<Result<Vec<_>>>()?;
let entries = copy_raw_page_label_entries(&mut output, &entries)?;
output
.page_labels()
.write_reconstructed_labels_raw(&entries)?;
}
let mut writer = PdfWriter::new(&mut output);
writer.set_output_file(&output_path)?;
self.prepare_writer_configuration(&mut writer_configuration)?;
writer_configuration.apply_to(&mut writer);
if let Some(version) = source_version.as_deref() {
writer.set_minimum_pdf_version(version, source_extension_level);
}
if options.deterministic_id {
writer.set_deterministic_id(true);
}
self.configure_writer_progress(&mut writer);
writer.write()?;
if options.verbose {
let mut message = self.message_prefix_bytes().to_vec();
message.extend_from_slice(b": wrote file ");
message.extend_from_slice(&path_bytes(&output_path));
message.push(b'\n');
self.logger().info(message)?;
}
written.push(output_path);
}
self.record_document_warnings(source);
Ok(written)
}
}
fn same_file_if_existing(input: &Path, output: &Path) -> Result<bool> {
let output_metadata = match std::fs::metadata(output) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(Error::file_io("inspect split output", output, error)),
};
let input_metadata = match std::fs::metadata(input) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(error) => return Err(Error::file_io("inspect split input", input, error)),
};
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Ok(input_metadata.dev() == output_metadata.dev()
&& input_metadata.ino() == output_metadata.ino())
}
#[cfg(not(unix))]
{
let _ = (input_metadata, output_metadata);
Ok(std::fs::canonicalize(input)? == std::fs::canonicalize(output)?)
}
}
fn chunk_output_path(
template: &Path,
first_page: u32,
last_page: u32,
width: usize,
chunk_size: usize,
) -> PathBuf {
let suffix = if chunk_size == 1 {
format!("{first_page:0>width$}", width = width)
} else {
format!("{first_page:0>width$}-{last_page:0>width$}", width = width)
};
if let Some(path) = replace_first_percent_d(template, &suffix) {
return path;
}
if chunk_size != 1 {
return split_output_path(template, first_page, last_page, width);
}
let (parent, stem, ext) = split_template(template);
let mut new_filename = stem;
new_filename.push(b'-');
new_filename.extend_from_slice(format!("{first_page:0>width$}", width = width).as_bytes());
new_filename.extend_from_slice(&ext);
join_parent(parent, new_filename)
}
fn split_output_path(template: &Path, first_page: u32, last_page: u32, width: usize) -> PathBuf {
let range = format!(
"{:0>width$}-{:0>width$}",
first_page,
last_page,
width = width
);
if let Some(path) = replace_first_percent_d(template, &range) {
return path;
}
let (parent, stem, ext) = split_template(template);
let mut new_filename = stem;
new_filename.push(b'-');
new_filename.extend_from_slice(range.as_bytes());
new_filename.extend_from_slice(&ext);
join_parent(parent, new_filename)
}
fn split_template(template: &Path) -> (&Path, Vec<u8>, Vec<u8>) {
let parent = template.parent().unwrap_or(Path::new(""));
let filename = template
.file_name()
.map(path_component_bytes)
.unwrap_or_default();
let (stem, ext) = if filename.len() >= 4 {
let dot_pos = filename.len() - 4;
if filename[dot_pos..].eq_ignore_ascii_case(b".pdf") {
let (s, e) = filename.split_at(dot_pos);
(s.to_vec(), e.to_vec()) } else {
(filename, Vec::new())
}
} else {
(filename, Vec::new())
};
(parent, stem, ext)
}
fn join_parent(parent: &Path, filename: Vec<u8>) -> PathBuf {
let filename = path_from_bytes(&filename);
if parent == Path::new("") {
filename
} else {
parent.join(filename)
}
}
fn replace_first_percent_d(template: &Path, replacement: &str) -> Option<PathBuf> {
let template = path_bytes(template);
let position = template.windows(2).position(|window| window == b"%d")?;
let mut output = Vec::with_capacity(template.len() + replacement.len());
output.extend_from_slice(&template[..position]);
output.extend_from_slice(replacement.as_bytes());
output.extend_from_slice(&template[position + 2..]);
Some(path_from_bytes(&output))
}
fn path_component_bytes(component: &std::ffi::OsStr) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
component.as_bytes().to_vec()
}
#[cfg(not(unix))]
{
component.to_string_lossy().into_owned().into_bytes()
}
}
fn path_bytes(path: &Path) -> Vec<u8> {
path_component_bytes(path.as_os_str())
}
fn path_from_bytes(bytes: &[u8]) -> PathBuf {
#[cfg(unix)]
{
use std::ffi::OsString;
use std::os::unix::ffi::OsStringExt;
PathBuf::from(OsString::from_vec(bytes.to_vec()))
}
#[cfg(not(unix))]
{
PathBuf::from(String::from_utf8_lossy(bytes).into_owned())
}
}
fn digit_width(n: u32) -> usize {
if n == 0 {
return 1;
}
let mut w = 0;
let mut v = n;
while v > 0 {
w += 1;
v /= 10;
}
w
}
#[cfg(test)]
mod tests {
use super::*;
use crate::job::resource_pruning::SharedResourceFinding;
use crate::pages::page_refs;
use crate::pipeline::{Pipeline, PipelineHandle, PipelineResult};
use crate::{
EncryptMethod, EncryptParams, ObjectHandle, PasswordMode, Pdf, PdfOpenOptions, QPDFLogger,
};
use std::io::Cursor;
use std::sync::{Arc, Mutex};
#[test]
fn chunk_output_path_chunk_size_1_single_number() {
assert_eq!(
chunk_output_path(Path::new("out.pdf"), 1, 1, 1, 1),
PathBuf::from("out-1.pdf"),
);
assert_eq!(
chunk_output_path(Path::new("out.pdf"), 3, 3, 1, 1),
PathBuf::from("out-3.pdf"),
);
}
#[test]
fn chunk_output_path_replaces_only_the_first_percent_d() {
assert_eq!(
chunk_output_path(Path::new("literal-%d-tail.pdf"), 1, 1, 1, 1),
PathBuf::from("literal-1-tail.pdf"),
);
assert_eq!(
chunk_output_path(Path::new("literal-%d-%d.pdf"), 1, 2, 1, 2),
PathBuf::from("literal-1-2-%d.pdf"),
);
}
#[test]
fn chunk_output_path_chunk_size_1_single_number_zero_padded() {
assert_eq!(
chunk_output_path(Path::new("out.pdf"), 7, 7, 2, 1),
PathBuf::from("out-07.pdf"),
);
}
#[test]
fn chunk_output_path_chunk_size_1_single_number_no_extension() {
assert_eq!(
chunk_output_path(Path::new("out"), 2, 2, 1, 1),
PathBuf::from("out-2"),
);
}
#[test]
fn chunk_output_path_non_pdf_extension_stays_in_filename() {
assert_eq!(
chunk_output_path(Path::new("out.txt"), 2, 2, 1, 1),
PathBuf::from("out.txt-2"),
);
}
#[test]
fn chunk_output_path_chunk_size_ge_2_delegates_to_range_form() {
assert_eq!(
chunk_output_path(Path::new("out.pdf"), 1, 2, 1, 2),
split_output_path(Path::new("out.pdf"), 1, 2, 1),
);
assert_eq!(
chunk_output_path(Path::new("out.pdf"), 3, 3, 1, 2),
PathBuf::from("out-3-3.pdf"),
);
}
#[test]
fn split_output_path_basic_pdf_extension() {
assert_eq!(
split_output_path(Path::new("out.pdf"), 1, 2, 1),
PathBuf::from("out-1-2.pdf"),
);
}
#[test]
fn split_output_path_non_pdf_extension_stays_in_filename() {
assert_eq!(
split_output_path(Path::new("out.txt"), 1, 2, 1),
PathBuf::from("out.txt-1-2"),
);
assert_eq!(
split_output_path(Path::new("two.dots.txt"), 3, 3, 1),
PathBuf::from("two.dots.txt-3-3"),
);
}
#[test]
fn split_output_path_pdf_extension_is_case_insensitive() {
assert_eq!(
split_output_path(Path::new("out.PDF"), 1, 2, 1),
PathBuf::from("out-1-2.PDF"),
);
assert_eq!(
split_output_path(Path::new("out.PdF"), 3, 3, 1),
PathBuf::from("out-3-3.PdF"),
);
}
#[test]
fn split_output_path_replaces_only_the_first_percent_d() {
assert_eq!(
split_output_path(Path::new("literal-%d-tail-%d.pdf"), 1, 2, 1),
PathBuf::from("literal-1-2-tail-%d.pdf"),
);
}
#[test]
fn split_output_path_last_chunk_same_page() {
assert_eq!(
split_output_path(Path::new("out.pdf"), 5, 5, 1),
PathBuf::from("out-5-5.pdf"),
);
}
#[test]
fn split_output_path_zero_padded_width2() {
assert_eq!(
split_output_path(Path::new("out.pdf"), 1, 2, 2),
PathBuf::from("out-01-02.pdf"),
);
assert_eq!(
split_output_path(Path::new("out.pdf"), 11, 11, 2),
PathBuf::from("out-11-11.pdf"),
);
}
#[test]
fn split_output_path_zero_padded_width3() {
assert_eq!(
split_output_path(Path::new("out.pdf"), 1, 10, 3),
PathBuf::from("out-001-010.pdf"),
);
assert_eq!(
split_output_path(Path::new("out.pdf"), 91, 100, 3),
PathBuf::from("out-091-100.pdf"),
);
}
#[test]
fn split_output_path_no_extension() {
assert_eq!(
split_output_path(Path::new("out"), 1, 2, 1),
PathBuf::from("out-1-2"),
);
}
#[test]
fn split_output_path_multiple_dots_before_pdf_extension() {
assert_eq!(
split_output_path(Path::new("two.dots.pdf"), 1, 2, 1),
PathBuf::from("two.dots-1-2.pdf"),
);
}
#[test]
fn split_output_path_leading_dot_template_matches_qpdf() {
assert_eq!(
split_output_path(Path::new(".pdf"), 1, 2, 1),
PathBuf::from("-1-2.pdf"),
);
assert_eq!(
split_output_path(Path::new("/tmp/.pdf"), 3, 3, 1),
PathBuf::from("/tmp/-3-3.pdf"),
);
}
#[test]
fn split_output_path_preserves_parent_directory() {
assert_eq!(
split_output_path(Path::new("/tmp/out.pdf"), 3, 4, 1),
PathBuf::from("/tmp/out-3-4.pdf"),
);
}
#[test]
fn digit_width_small_values() {
assert_eq!(
digit_width(0),
1,
"edge case: won't occur for real page counts"
);
assert_eq!(digit_width(1), 1);
assert_eq!(digit_width(9), 1);
assert_eq!(digit_width(10), 2);
assert_eq!(digit_width(99), 2);
assert_eq!(digit_width(100), 3);
assert_eq!(digit_width(999), 3);
assert_eq!(digit_width(1000), 4);
}
#[test]
fn digit_width_matches_qpdf_observations() {
assert_eq!(digit_width(5), 1);
assert_eq!(digit_width(11), 2);
assert_eq!(digit_width(100), 3);
}
fn open_fixture(name: &str) -> Pdf<Cursor<Vec<u8>>> {
let bytes: &[u8] = match name {
"direct-outlines.pdf" => {
include_bytes!("../../../../tests/fixtures/json-diff/direct-outlines.pdf")
}
"three-page.pdf" => include_bytes!("../../../../tests/fixtures/compat/three-page.pdf"),
"inherited-resources-one-page.pdf" => {
include_bytes!("../../../../tests/fixtures/compat/inherited-resources-one-page.pdf")
}
"objstm-lin-acroform-widget-page1-page2.pdf" => include_bytes!(
"../../../../tests/fixtures/compat/objstm-lin-acroform-widget-page1-page2.pdf"
),
"acroform-sig-orphan-widget.pdf" => {
include_bytes!("../../../../tests/fixtures/compat/acroform-sig-orphan-widget.pdf")
}
_ => panic!("fixture is not registered: {name}"),
};
Pdf::open_mem_owned(bytes.to_vec()).expect("fixture must parse")
}
fn catalog(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> ObjectHandle {
pdf.root_handle().expect("catalog resolves")
}
fn first_page_annotation_count(pdf: &mut Pdf<Cursor<Vec<u8>>>) -> usize {
let page_ref = page_refs(pdf)
.expect("page references resolve")
.into_iter()
.next()
.expect("fixture has a page");
let page = pdf.get_object_handle(page_ref);
page.try_is_scalar().expect("page resolves");
if !page.try_has_key(b"/Annots").unwrap() {
return 0;
}
let annots = page.try_get_key(b"/Annots").unwrap();
annots.try_is_scalar().expect("/Annots resolves");
annots
.as_array()
.map(|annots| annots.len())
.unwrap_or_else(|| panic!("/Annots is not an array")) }
#[test]
fn split_page_options_builder_keeps_qpdf_job_inputs() {
let options = SplitPageOptions::new(2, "out-%d.pdf")
.with_input_path("input.pdf")
.with_deterministic_id(true)
.with_remove_unreferenced_resources(RemoveUnreferencedResources::No);
assert_eq!(options.chunk_size, 2);
assert_eq!(options.output_template, PathBuf::from("out-%d.pdf"));
assert_eq!(options.input_path, Some(PathBuf::from("input.pdf")));
assert!(options.deterministic_id);
assert_eq!(
options.remove_unreferenced_resources,
RemoveUnreferencedResources::No
);
}
#[test]
fn shared_resource_finding_messages_match_qpdf() {
let node = crate::ObjectRef::new(3, 0);
let resource = crate::ObjectRef::new(7, 0);
assert_eq!(
shared_resource_finding_message(SharedResourceFinding::NonLeaf { node }),
b" found resources in non-leaf page node 3 0\n"
);
assert_eq!(
shared_resource_finding_message(SharedResourceFinding::Resources {
node,
resources: resource,
}),
b" found shared resources in leaf node 3 0: 7 0\n"
);
assert_eq!(
shared_resource_finding_message(SharedResourceFinding::XObject {
node,
xobject: resource,
}),
b" found shared xobject in leaf node 3 0: 7 0\n"
);
}
#[test]
fn split_pages_honors_explicit_resource_policies() {
for mode in [
RemoveUnreferencedResources::No,
RemoveUnreferencedResources::Yes,
] {
let mut source = open_fixture("three-page.pdf");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(1, temp.path().join("out-%d.pdf"))
.with_remove_unreferenced_resources(mode);
let written = QPDFJob::new()
.split_pages(&mut source, options)
.expect("explicit resource policy should split");
assert_eq!(written.len(), 3);
}
}
#[test]
fn split_pages_auto_resource_finding_without_verbose_still_prunes() {
let mut source = open_fixture("inherited-resources-one-page.pdf");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(1, temp.path().join("out-%d.pdf"));
let written = QPDFJob::new()
.split_pages(&mut source, options)
.expect("Auto resource finding should split");
assert_eq!(written.len(), 1);
}
fn open_extension_level_overflow_fixture() -> Pdf<Cursor<Vec<u8>>> {
let mut body = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
offsets.push(body.len());
body.extend_from_slice(
b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Extensions << /ADBE << /ExtensionLevel 5000000000 >> >> >>\nendobj\n",
);
offsets.push(body.len());
body.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n");
offsets.push(body.len());
body.extend_from_slice(
b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>\nendobj\n",
);
let xref_offset = body.len();
let n = offsets.len() + 1;
let mut xref = format!("xref\n0 {n}\n0000000000 65535 f \n").into_bytes();
for offset in &offsets {
xref.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
body.extend_from_slice(&xref);
body.extend_from_slice(
format!("trailer\n<< /Size {n} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n")
.as_bytes(),
);
Pdf::open_mem_owned(body).expect("well-formed overflow fixture must parse")
}
#[test]
fn split_pages_clamps_the_source_extension_level_like_qpdf() {
let mut source = open_extension_level_overflow_fixture();
let temp = tempfile::tempdir().expect("tempdir");
let written = QPDFJob::new()
.split_pages(
&mut source,
SplitPageOptions::new(1, temp.path().join("out.pdf")),
)
.expect("split job should succeed despite the clamp warning");
assert_eq!(written.len(), 1);
assert_eq!(
source
.repair_diagnostics()
.entries()
.iter()
.filter(|entry| entry
.message_string()
.contains("requested value of integer is too big; returning INT_MAX"))
.count(),
1
);
}
#[test]
fn split_pages_with_static_id_produces_identical_chunk_ids_across_runs() {
let run = || {
let mut source = open_fixture("three-page.pdf");
let temp = tempfile::tempdir().expect("tempdir");
let mut job = QPDFJob::new();
let mut configuration = WriterConfiguration::default();
configuration.set_static_id(true);
let options = SplitPageOptions::new(1, temp.path().join("chunk-%d.pdf"))
.with_writer_configuration(configuration);
let written = job
.split_pages(&mut source, options)
.expect("split succeeds");
written
.iter()
.map(|path| std::fs::read(path).expect("chunk readable"))
.collect::<Vec<_>>()
};
assert_eq!(run(), run());
}
#[test]
fn split_pages_records_an_orphan_widget_warning_once() {
let mut source = open_fixture("acroform-sig-orphan-widget.pdf");
let temp = tempfile::tempdir().expect("tempdir");
let mut job = QPDFJob::new();
let written = job
.split_pages(
&mut source,
SplitPageOptions::new(1, temp.path().join("out.pdf")),
)
.expect("split job should succeed with a recoverable warning");
assert_eq!(written.len(), 1);
assert!(job.has_warnings());
assert_eq!(
source
.repair_diagnostics()
.entries()
.iter()
.filter(|entry| {
entry
.message_string()
.contains("this widget annotation is not reachable from /AcroForm")
})
.count(),
1
);
}
struct RecordingWarningSink(Arc<Mutex<Vec<u8>>>);
impl Pipeline for RecordingWarningSink {
fn identifier(&self) -> &str {
"split_pages warning recording sink"
}
fn write(&mut self, data: &[u8]) -> PipelineResult<()> {
self.0.lock().unwrap().extend_from_slice(data);
Ok(())
}
fn finish(&mut self) -> PipelineResult<()> {
Ok(())
}
}
#[test]
fn split_pages_retains_a_source_configured_suppress_warnings_setting() {
let bytes =
include_bytes!("../../../../tests/fixtures/compat/acroform-sig-orphan-widget.pdf")
.to_vec();
let mut source = Pdf::open_mem_owned_with_options(
bytes,
PdfOpenOptions {
suppress_warnings: true,
..PdfOpenOptions::default()
},
)
.expect("fixture should parse");
let recorded = Arc::new(Mutex::new(Vec::new()));
let logger = QPDFLogger::create();
logger.set_warn(Some(PipelineHandle::new(RecordingWarningSink(Arc::clone(
&recorded,
)))));
let temp = tempfile::tempdir().expect("tempdir");
let mut job = QPDFJob::new();
job.set_logger(logger);
job.split_pages(
&mut source,
SplitPageOptions::new(1, temp.path().join("out.pdf")),
)
.expect("split job should succeed with a recoverable, suppressed warning");
let delivered = String::from_utf8_lossy(&recorded.lock().unwrap()).into_owned();
assert!(
delivered.is_empty(),
"a source opened with suppress_warnings:true must stay suppressed \
through split_pages: {delivered:?}"
);
}
#[test]
fn split_pages_delivers_warnings_from_an_unsuppressed_source() {
let bytes =
include_bytes!("../../../../tests/fixtures/compat/acroform-sig-orphan-widget.pdf")
.to_vec();
let mut source = Pdf::open_mem_owned(bytes).expect("fixture should parse");
let recorded = Arc::new(Mutex::new(Vec::new()));
let logger = QPDFLogger::create();
logger.set_warn(Some(PipelineHandle::new(RecordingWarningSink(Arc::clone(
&recorded,
)))));
let temp = tempfile::tempdir().expect("tempdir");
let mut job = QPDFJob::new();
job.set_logger(logger);
job.split_pages(
&mut source,
SplitPageOptions::new(1, temp.path().join("out.pdf")),
)
.expect("split job should succeed with a recoverable warning");
assert!(
String::from_utf8_lossy(&recorded.lock().unwrap())
.contains("this widget annotation is not reachable from /AcroForm"),
"an unsuppressed source's orphan-widget warning must reach the job's logger"
);
}
#[test]
fn split_pages_repeats_the_unicode_password_warning_once_per_chunk() {
let src = build_n_page_pdf(3);
let mut source = Pdf::open_mem_owned(src).expect("fixture should parse");
let recorded = Arc::new(Mutex::new(Vec::new()));
let logger = QPDFLogger::create();
logger.set_error(Some(PipelineHandle::new(RecordingWarningSink(Arc::clone(
&recorded,
)))));
let temp = tempfile::tempdir().expect("tempdir");
let mut job = QPDFJob::new();
job.set_logger(logger);
job.set_password_mode(PasswordMode::Auto);
job.set_allow_weak_crypto(true);
let mut configuration = WriterConfiguration::default();
configuration.set_encryption_parameters(EncryptParams::rc4(
EncryptMethod::V2Rc4128,
"\u{1f600}not-encodable".as_bytes().to_vec(),
Vec::new(),
));
job.split_pages(
&mut source,
SplitPageOptions::new(1, temp.path().join("out.pdf"))
.with_writer_configuration(configuration),
)
.expect("split job should succeed despite the non-encodable password");
let delivered = String::from_utf8_lossy(&recorded.lock().unwrap()).into_owned();
let occurrences = delivered
.matches("WARNING: supplied password looks like a Unicode password")
.count();
assert_eq!(
occurrences, 3,
"each of the 3 one-page chunks must repeat the notice independently, \
matching qpdf's own per-chunk setEncryptionOptions call: got {delivered:?}"
);
}
#[test]
fn split_pages_uses_a_fresh_catalog_and_preserves_explicit_empty_prefix() {
let mut source = open_fixture("direct-outlines.pdf");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(1, temp.path().join("out.pdf"));
let mut job = super::super::QPDFJob::new();
let written = job
.split_pages(&mut source, options)
.expect("split job should succeed");
assert_eq!(written.len(), 30);
let mut chunk =
Pdf::open_mem_owned(std::fs::read(&written[0]).expect("first chunk should be written"))
.expect("chunk should parse");
let catalog = catalog(&mut chunk);
assert!(!catalog.try_has_key(b"/Outlines").unwrap());
assert!(!catalog.try_has_key(b"/PageMode").unwrap());
let page_labels = catalog.try_get_key(b"/PageLabels").unwrap();
page_labels.try_is_scalar().expect("PageLabels resolves");
let nums = page_labels.try_get_key(b"/Nums").unwrap();
nums.try_is_scalar().expect("PageLabels /Nums resolves");
let labels = nums.as_array().expect("PageLabels /Nums must be an array");
let label = labels.get(1).expect("first label dictionary");
label.try_is_scalar().expect("label dictionary resolves");
assert_eq!(
label.try_get_key(b"/P").unwrap().as_string(),
Some(Vec::new())
);
}
#[test]
fn split_pages_on_an_empty_source_document_writes_no_chunks() {
let mut source = Pdf::empty().expect("empty PDF should parse");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(1, temp.path().join("out.pdf"));
let mut job = super::super::QPDFJob::new();
let written = job
.split_pages(&mut source, options)
.expect("a document without pages is a no-op, not an error");
assert!(written.is_empty());
}
#[test]
#[should_panic(expected = "fixture is not registered")]
fn fixture_helper_rejects_unknown_fixture_names() {
let _ = open_fixture("unknown");
}
#[test]
fn same_file_guard_reports_metadata_errors_and_missing_input() {
let temp = tempfile::tempdir().expect("temporary directory");
let existing_output = temp.path().join("existing-output.pdf");
std::fs::write(&existing_output, b"output").expect("output should exist");
#[cfg(unix)]
{
let file_parent = temp.path().join("file-parent");
std::fs::write(&file_parent, b"not a directory").expect("parent file should exist");
let output_error = same_file_if_existing(&file_parent, &file_parent.join("output.pdf"))
.expect_err("metadata below a file must fail");
assert!(output_error.to_string().contains("inspect split output"));
let input_error =
same_file_if_existing(&file_parent.join("input.pdf"), &existing_output)
.expect_err("input metadata below a file must fail");
assert!(input_error.to_string().contains("inspect split input"));
}
#[cfg(not(unix))]
assert!(same_file_if_existing(&existing_output, &existing_output)
.expect("canonicalize should inspect an existing Windows path"));
let missing_input = temp.path().join("missing-input.pdf");
assert!(!same_file_if_existing(&missing_input, &existing_output)
.expect("a missing input is not an overwrite"));
}
#[test]
fn split_pages_keeps_only_fields_reached_by_the_chunk() {
let mut source = open_fixture("objstm-lin-acroform-widget-page1-page2.pdf");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(1, temp.path().join("out.pdf"));
let mut job = super::super::QPDFJob::new();
let written = job
.split_pages(&mut source, options)
.expect("split job should succeed");
assert_eq!(written.len(), 3);
let mut first = Pdf::open_mem_owned(std::fs::read(&written[0]).unwrap()).unwrap();
let mut second = Pdf::open_mem_owned(std::fs::read(&written[1]).unwrap()).unwrap();
let mut third = Pdf::open_mem_owned(std::fs::read(&written[2]).unwrap()).unwrap();
assert!(!first.acroform().unwrap().has_acro_form().unwrap());
assert!(second.acroform().unwrap().has_acro_form().unwrap());
assert_eq!(second.acroform().unwrap().fields().unwrap().len(), 1);
assert_eq!(first_page_annotation_count(&mut first), 0);
assert_eq!(first_page_annotation_count(&mut second), 1);
assert_eq!(first_page_annotation_count(&mut third), 1);
}
#[test]
fn split_pages_preserves_source_pdf_version_on_each_chunk() {
let mut source = open_fixture("objstm-lin-acroform-widget-page1-page2.pdf");
assert_eq!(source.version(), "1.5");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(1, temp.path().join("out.pdf"));
let mut job = super::super::QPDFJob::new();
let written = job
.split_pages(&mut source, options)
.expect("split job should succeed");
for path in written {
let bytes = std::fs::read(path).expect("chunk should be readable");
assert!(bytes.starts_with(b"%PDF-1.5\n"));
}
}
#[test]
fn split_pages_rejects_a_chunk_that_would_overwrite_the_input() {
let temp = tempfile::tempdir().expect("temporary directory");
let input = temp.path().join("out-1.pdf");
std::fs::write(
&input,
include_bytes!("../../../../tests/fixtures/compat/one-page.pdf"),
)
.expect("input should be created");
let mut source = Pdf::open_mem_owned(std::fs::read(&input).unwrap()).unwrap();
let options = SplitPageOptions::new(1, temp.path().join("out.pdf")).with_input_path(&input);
let mut job = super::super::QPDFJob::new();
let error = job
.split_pages(&mut source, options)
.expect_err("split must not overwrite its input");
assert!(error.to_string().contains("overwrite input"));
}
#[test]
fn split_pages_applies_qpdf_percent_d_to_the_first_placeholder() {
let mut source = open_fixture("three-page.pdf");
let temp = tempfile::tempdir().expect("temporary directory");
let options = SplitPageOptions::new(2, temp.path().join("literal-%d-tail-%d.pdf"));
let mut job = super::super::QPDFJob::new();
let written = job
.split_pages(&mut source, options)
.expect("split job should succeed");
assert_eq!(
written,
vec![
temp.path().join("literal-1-2-tail-%d.pdf"),
temp.path().join("literal-3-3-tail-%d.pdf"),
]
);
}
fn split(
src: Vec<u8>,
chunk_size: usize,
output_template: &Path,
deterministic_id: bool,
) -> Result<Vec<PathBuf>> {
let mut pdf = Pdf::open_mem_owned(src)?;
super::super::QPDFJob::new().split_pages(
&mut pdf,
SplitPageOptions::new(chunk_size, output_template)
.with_deterministic_id(deterministic_id),
)
}
fn build_n_page_pdf(n: u32) -> Vec<u8> {
assert!(n >= 1);
let mut pdf: Vec<u8> = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
let off2 = pdf.len() as u64;
let kids: String = (3u32..=2 + n).map(|i| format!("{i} 0 R ")).collect();
pdf.extend_from_slice(
format!("2 0 obj\n<< /Type /Pages /Kids [{kids}] /Count {n} >>\nendobj\n").as_bytes(),
);
let mut page_offsets: Vec<u64> = Vec::new();
for i in 3u32..=2 + n {
let off = pdf.len() as u64;
page_offsets.push(off);
pdf.extend_from_slice(
format!(
"{i} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n"
)
.as_bytes(),
);
}
let xref_start = pdf.len() as u64;
let total = 2 + n as usize + 1;
let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
xref.push_str(&format!("{:010} 00000 n \n", off1));
xref.push_str(&format!("{:010} 00000 n \n", off2));
for off in &page_offsets {
xref.push_str(&format!("{:010} 00000 n \n", off));
}
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn build_n_page_pdf_with_pagelabels(n: u32, nums_body: &str) -> Vec<u8> {
assert!(n >= 1);
let mut pdf: Vec<u8> = Vec::new();
pdf.extend_from_slice(b"%PDF-1.4\n");
let off1 = pdf.len() as u64;
pdf.extend_from_slice(
format!(
"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /PageLabels << /Nums {nums_body} >> >>\nendobj\n"
)
.as_bytes(),
);
let off2 = pdf.len() as u64;
let kids: String = (3u32..=2 + n).map(|i| format!("{i} 0 R ")).collect();
pdf.extend_from_slice(
format!("2 0 obj\n<< /Type /Pages /Kids [{kids}] /Count {n} >>\nendobj\n").as_bytes(),
);
let mut page_offsets: Vec<u64> = Vec::new();
for i in 3u32..=2 + n {
let off = pdf.len() as u64;
page_offsets.push(off);
pdf.extend_from_slice(
format!(
"{i} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n"
)
.as_bytes(),
);
}
let xref_start = pdf.len() as u64;
let total = 2 + n as usize + 1;
let mut xref = format!("xref\n0 {total}\n0000000000 65535 f \n");
xref.push_str(&format!("{:010} 00000 n \n", off1));
xref.push_str(&format!("{:010} 00000 n \n", off2));
for off in &page_offsets {
xref.push_str(&format!("{:010} 00000 n \n", off));
}
pdf.extend_from_slice(xref.as_bytes());
let trailer =
format!("trailer\n<< /Size {total} /Root 1 0 R >>\nstartxref\n{xref_start}\n%%EOF\n");
pdf.extend_from_slice(trailer.as_bytes());
pdf
}
fn read_nums(bytes: &[u8]) -> Vec<(i64, ObjectHandle)> {
let mut pdf = Pdf::open(Cursor::new(bytes.to_vec())).expect("should parse");
let catalog = pdf.root_handle().expect("/Root");
let page_labels = catalog.try_get_key(b"/PageLabels").unwrap();
page_labels.try_is_scalar().expect("resolve PageLabels");
let nums = page_labels.try_get_key(b"/Nums").unwrap();
nums.try_is_scalar().expect("resolve /Nums");
nums.as_array()
.expect("/Nums must be a direct array")
.chunks_exact(2)
.map(|pair| {
let idx = pair[0]
.as_integer()
.expect("expected an integer label index");
(idx, pair[1].clone())
})
.collect()
}
fn page_count_of(bytes: &[u8]) -> usize {
let mut pdf = Pdf::open_mem(Arc::from(bytes)).expect("should parse");
page_refs(&mut pdf).expect("should get page refs").len()
}
#[test]
fn split_pages_single_chunk_size_one() {
let src = build_n_page_pdf(3);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
split(src, 1, &template, false).expect("split should succeed");
let out1 = tmpdir.path().join("out-1.pdf");
let out2 = tmpdir.path().join("out-2.pdf");
let out3 = tmpdir.path().join("out-3.pdf");
assert!(out1.exists(), "chunk 1 should exist");
assert!(out2.exists(), "chunk 2 should exist");
assert!(out3.exists(), "chunk 3 should exist");
assert_eq!(page_count_of(&std::fs::read(&out1).unwrap()), 1);
assert_eq!(page_count_of(&std::fs::read(&out2).unwrap()), 1);
assert_eq!(page_count_of(&std::fs::read(&out3).unwrap()), 1);
}
#[test]
fn split_pages_chunk_size_two_with_remainder() {
let src = build_n_page_pdf(5);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
split(src, 2, &template, false).expect("split should succeed");
let out12 = tmpdir.path().join("out-1-2.pdf");
let out34 = tmpdir.path().join("out-3-4.pdf");
let out55 = tmpdir.path().join("out-5-5.pdf");
assert!(out12.exists(), "chunk 1-2 should exist: {:?}", out12);
assert!(out34.exists(), "chunk 3-4 should exist: {:?}", out34);
assert!(out55.exists(), "chunk 5-5 should exist: {:?}", out55);
assert_eq!(page_count_of(&std::fs::read(&out12).unwrap()), 2);
assert_eq!(page_count_of(&std::fs::read(&out34).unwrap()), 2);
assert_eq!(page_count_of(&std::fs::read(&out55).unwrap()), 1);
}
#[test]
fn split_pages_large_n_emits_one_file() {
let src = build_n_page_pdf(3);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
split(src, 100, &template, false).expect("split should succeed");
let out = tmpdir.path().join("out-1-3.pdf");
assert!(out.exists(), "single chunk file should exist: {:?}", out);
assert_eq!(page_count_of(&std::fs::read(&out).unwrap()), 3);
}
#[test]
fn split_pages_naming_zero_padded_for_10plus_pages() {
let src = build_n_page_pdf(11);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
split(src, 2, &template, false).expect("split should succeed");
let first = tmpdir.path().join("out-01-02.pdf");
assert!(
first.exists(),
"zero-padded first chunk should exist: {:?}",
first
);
let last = tmpdir.path().join("out-11-11.pdf");
assert!(
last.exists(),
"zero-padded last chunk should exist: {:?}",
last
);
}
#[test]
fn split_pages_deterministic_id_produces_stable_chunks() {
let src = build_n_page_pdf(3);
let d1 = tempfile::tempdir().expect("tmpdir");
let d2 = tempfile::tempdir().expect("tmpdir");
split(src.clone(), 1, &d1.path().join("out.pdf"), true).expect("split should succeed");
split(src, 1, &d2.path().join("out.pdf"), true).expect("split should succeed");
let c1 = std::fs::read(d1.path().join("out-1.pdf")).unwrap();
let c2 = std::fs::read(d2.path().join("out-1.pdf")).unwrap();
assert_eq!(
c1, c2,
"deterministic-id chunks must be byte-stable across runs"
);
assert!(
c1.windows(3).any(|w| w == b"/ID"),
"a deterministic-id chunk must carry an /ID"
);
}
#[test]
fn split_pages_propagates_chunk_write_error() {
let src = build_n_page_pdf(2);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let bad = tmpdir.path().join("no_such_subdir").join("out.pdf");
let result = split(src, 1, &bad, false);
assert!(
result.is_err(),
"a chunk write failure must propagate out of split_pages"
);
}
#[test]
fn split_pages_chunk_size_zero_is_error() {
let src = build_n_page_pdf(3);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
let result = split(src, 0, &template, false);
assert!(result.is_err(), "chunk_size=0 should return an error");
}
#[test]
fn split_pages_does_not_leave_suppression_sticky_across_jobs() {
let mut source = open_fixture("acroform-sig-orphan-widget.pdf");
let temp = tempfile::tempdir().expect("tempdir");
let mut suppressing_job = QPDFJob::new();
suppressing_job.set_suppress_warnings(true);
let error = suppressing_job
.split_pages(
&mut source,
SplitPageOptions::new(0, temp.path().join("a.pdf")),
)
.expect_err("chunk_size=0 must still error");
assert!(matches!(error, Error::Unsupported(_)));
let recorded = Arc::new(Mutex::new(Vec::new()));
let logger = QPDFLogger::create();
logger.set_warn(Some(PipelineHandle::new(RecordingWarningSink(Arc::clone(
&recorded,
)))));
let mut plain_job = QPDFJob::new();
plain_job.set_logger(logger);
plain_job
.split_pages(
&mut source,
SplitPageOptions::new(1, temp.path().join("b.pdf")),
)
.expect("split job should succeed with a recoverable warning");
assert!(
String::from_utf8_lossy(&recorded.lock().unwrap())
.contains("this widget annotation is not reachable from /AcroForm"),
"a later unsuppressed job must still observe the source's warning, not inherit \
suppression left over from an earlier, unrelated job's failed call"
);
}
#[test]
fn split_pages_reconstructs_page_labels_per_chunk() {
let src = build_n_page_pdf_with_pagelabels(5, "[0 << /S /r >> 3 << /S /D /St 1 >>]");
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
split(src, 2, &template, false).expect("split should succeed");
let chunk1 = std::fs::read(tmpdir.path().join("out-1-2.pdf")).unwrap();
let chunk2 = std::fs::read(tmpdir.path().join("out-3-4.pdf")).unwrap();
let chunk3 = std::fs::read(tmpdir.path().join("out-5-5.pdf")).unwrap();
let s = |name: &str| name.as_bytes().to_vec();
let nums1 = read_nums(&chunk1);
assert_eq!(nums1.len(), 1);
assert_eq!(nums1[0].0, 0);
assert_eq!(
nums1[0].1.try_get_key(b"/S").unwrap().as_name(),
Some(s("r"))
);
assert_eq!(
nums1[0].1.try_get_key(b"/St").unwrap().as_integer(),
Some(1)
);
let nums2 = read_nums(&chunk2);
assert_eq!(nums2.len(), 2, "roman continuation + decimal restart");
assert_eq!(nums2[0].0, 0);
assert_eq!(
nums2[0].1.try_get_key(b"/S").unwrap().as_name(),
Some(s("r"))
);
assert_eq!(
nums2[0].1.try_get_key(b"/St").unwrap().as_integer(),
Some(3)
);
assert_eq!(nums2[1].0, 1);
assert_eq!(
nums2[1].1.try_get_key(b"/S").unwrap().as_name(),
Some(s("D"))
);
assert_eq!(
nums2[1].1.try_get_key(b"/St").unwrap().as_integer(),
Some(1)
);
let nums3 = read_nums(&chunk3);
assert_eq!(nums3.len(), 1);
assert_eq!(nums3[0].0, 0);
assert_eq!(
nums3[0].1.try_get_key(b"/S").unwrap().as_name(),
Some(s("D"))
);
assert_eq!(
nums3[0].1.try_get_key(b"/St").unwrap().as_integer(),
Some(2)
);
}
#[test]
fn split_pages_without_page_labels_omits_pagelabels_key() {
let src = build_n_page_pdf(3);
let tmpdir = tempfile::tempdir().expect("tmpdir");
let template = tmpdir.path().join("out.pdf");
split(src, 1, &template, false).expect("split should succeed");
let chunk = std::fs::read(tmpdir.path().join("out-1.pdf")).unwrap();
let mut pdf = Pdf::open(Cursor::new(chunk)).expect("should parse");
let catalog = pdf.root_handle().unwrap();
assert!(
!catalog.try_has_key(b"/PageLabels").unwrap(),
"a source with no /PageLabels must not gain one"
);
}
}