use crate::pages::page_refs;
use crate::writer::{write_pdf, write_pdf_with_options, WriteOptions};
use crate::{Error, Object, ObjectRef, Pdf, Result};
use std::fs::File;
use std::io::{BufWriter, Cursor};
use std::path::{Path, PathBuf};
pub fn split_pages(
src_bytes: &[u8],
chunk_size: usize,
output_template: &Path,
deterministic_id: bool,
) -> Result<()> {
if chunk_size == 0 {
return Err(Error::Unsupported(
"split_pages: chunk_size must be >= 1".to_string(),
));
}
let mut pdf = Pdf::open(Cursor::new(src_bytes))?;
let all_page_refs = page_refs(&mut pdf)?;
let total_pages = all_page_refs.len();
if total_pages == 0 {
return Err(Error::Missing("document has no pages"));
}
let catalog_ref = pdf.root_ref().ok_or(Error::Missing("/Root"))?;
let catalog_obj = pdf.resolve_borrowed(catalog_ref)?;
let Some(catalog_dict) = catalog_obj.as_dict() else {
return Err(Error::Unsupported(
"document catalog is not a dictionary".to_string(),
));
};
let pages_root_ref = catalog_dict
.get_ref("Pages")
.ok_or(Error::Missing("/Pages"))?;
let width = digit_width(total_pages as u32);
let mut chunk_start = 0usize; while chunk_start < total_pages {
let chunk_end = (chunk_start + chunk_size).min(total_pages);
let first_page = (chunk_start + 1) as u32;
let last_page = chunk_end as u32;
let out_path = chunk_output_path(output_template, first_page, last_page, width, chunk_size);
let chunk_refs: Vec<ObjectRef> = all_page_refs[chunk_start..chunk_end].to_vec();
write_chunk(
src_bytes,
pages_root_ref,
&chunk_refs,
&out_path,
deterministic_id,
)?;
chunk_start = chunk_end;
}
Ok(())
}
pub fn split_output_path(
template: &Path,
first_page: u32,
last_page: u32,
width: usize,
) -> PathBuf {
let (parent, stem, ext) = split_template(template);
let new_filename = format!(
"{stem}-{:0>width$}-{:0>width$}{ext}",
first_page,
last_page,
width = width
);
join_parent(parent, new_filename)
}
fn split_template(template: &Path) -> (&Path, String, String) {
let parent = template.parent().unwrap_or(Path::new(""));
let filename = template
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let (stem, ext) = match filename.rfind('.') {
Some(dot_pos) => {
let (s, e) = filename.split_at(dot_pos);
(s.to_string(), e.to_string()) }
None => (filename.clone(), String::new()),
};
(parent, stem, ext)
}
fn join_parent(parent: &Path, filename: String) -> PathBuf {
if parent == Path::new("") {
PathBuf::from(filename)
} else {
parent.join(filename)
}
}
fn chunk_output_path(
template: &Path,
first_page: u32,
last_page: u32,
width: usize,
chunk_size: usize,
) -> PathBuf {
if chunk_size != 1 {
return split_output_path(template, first_page, last_page, width);
}
let (parent, stem, ext) = split_template(template);
let new_filename = format!("{stem}-{first_page:0>width$}{ext}", width = width);
join_parent(parent, new_filename)
}
pub 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
}
fn write_chunk(
src_bytes: &[u8],
pages_root_ref: ObjectRef,
chunk_refs: &[ObjectRef],
out_path: &Path,
deterministic_id: bool,
) -> Result<()> {
let mut pdf = Pdf::open(Cursor::new(src_bytes))?;
let pages_obj = pdf.resolve_borrowed(pages_root_ref)?;
let Some(mut pages_dict) = pages_obj.as_dict().cloned() else {
return Err(Error::Unsupported(
"document /Pages root is not a dictionary".to_string(),
));
};
let new_kids: Vec<Object> = chunk_refs.iter().map(|&r| Object::Reference(r)).collect();
pages_dict.insert("Kids", Object::Array(new_kids));
pages_dict.insert("Count", Object::Integer(chunk_refs.len() as i64));
pdf.set_object(pages_root_ref, Object::Dictionary(pages_dict.clone()));
for &page_ref in chunk_refs {
let page_obj = pdf.resolve_borrowed(page_ref)?;
if let Some(mut page_dict) = page_obj.as_dict().cloned() {
page_dict.insert("Parent", Object::Reference(pages_root_ref));
pdf.set_object(page_ref, Object::Dictionary(page_dict));
}
}
let file = File::create(out_path).map_err(Error::Io)?;
let mut writer = BufWriter::new(file);
if deterministic_id {
let options = WriteOptions {
full_rewrite: true,
deterministic_id: true,
..WriteOptions::default()
};
write_pdf_with_options(&mut pdf, &mut writer, &options)?;
} else {
write_pdf(&mut pdf, &mut writer)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[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_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_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_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_splits_at_last() {
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(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 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 page_count_of(bytes: &[u8]) -> usize {
let mut pdf = Pdf::open(Cursor::new(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_pages(&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_pages(&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_pages(&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_pages(&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_pages(&src, 1, &d1.path().join("out.pdf"), true).expect("split should succeed");
split_pages(&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_pages(&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_pages(&src, 0, &template, false);
assert!(result.is_err(), "chunk_size=0 should return an error");
}
}