PDF Split — Rust source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! pdf-split — split one PDF into many by page plan with lopdf (crates.io).
//! Authored snippet mirroring src/lib/pdf-split.ts: the planner
//! (parse_page_ranges + plan_names) is a pure port of the TS grammar —
//! 'all', 'N/chunk', or comma-separated 'a-b' ranges and single pages
//! (1-based, inclusive). Each planned group is written out by merging that
//! group's pages into a fresh document (lopdf has no one-call split, so each
//! output is assembled document-at-a-time via Document::merge).
use std::collections::BTreeMap;
use std::fmt;
/// Load failure kind: Encrypted (password-protected) or Invalid (unparseable).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
Encrypted,
Invalid,
}
/// The Rust twin of the TS PdfToolError class.
#[derive(Debug)]
pub struct PdfToolError {
pub kind: ErrorKind,
pub message: String,
}
impl fmt::Display for PdfToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for PdfToolError {}
fn invalid(message: impl Into<String>) -> PdfToolError {
PdfToolError { kind: ErrorKind::Invalid, message: message.into() }
}
/// Pure classifier — encrypted vs invalid, from the raw error message.
fn classify_load_error(msg: &str) -> ErrorKind {
let lower = msg.to_ascii_lowercase();
if lower.contains("encrypt") || lower.contains("password") {
ErrorKind::Encrypted
} else {
ErrorKind::Invalid
}
}
fn map_error(e: lopdf::Error) -> PdfToolError {
match e {
lopdf::Error::InvalidPassword => PdfToolError {
kind: ErrorKind::Encrypted,
message: "This PDF is password-protected. Unlock it first.".into(),
},
other => {
let kind = classify_load_error(&other.to_string());
let message = if kind == ErrorKind::Encrypted {
"This PDF is password-protected. Unlock it first.".into()
} else {
"Not a readable PDF file.".into()
};
PdfToolError { kind, message }
}
}
}
/// Split output: the planned file name, its bytes, and its page count.
pub struct SplitOutput {
pub name: String,
pub bytes: Vec<u8>,
pub page_count: usize,
}
fn range_pages(a: usize, b: usize) -> Vec<usize> {
(a..=b).collect()
}
/// Pure planner — grammar (mirrors parsePageRanges in src/lib/pdf-split.ts):
/// 'all' -> [[1], [2], .., [page_count]]
/// 'N/chunk' -> groups of N pages in order (last group may be short)
/// 'a-b,c-d,e' -> explicit groups (1-based, inclusive)
pub fn parse_page_ranges(spec: &str, page_count: usize) -> Result<Vec<Vec<usize>>, PdfToolError> {
let trimmed = spec.trim();
if trimmed.is_empty() {
return Err(invalid("Enter a page range first."));
}
if trimmed == "all" {
return Ok((1..=page_count).map(|p| vec![p]).collect());
}
if let Some(rest) = trimmed.strip_suffix("/chunk") {
let size: usize = rest
.parse()
.map_err(|_| invalid("\"{}\" is not a page, a-b range, \"all\", or \"N/chunk\".", trimmed))?;
if size < 1 || size > page_count {
return Err(invalid(format!("Chunk size must be between 1 and {page_count}.")));
}
let mut groups = Vec::new();
let mut start = 1;
while start <= page_count {
groups.push(range_pages(start, (start + size - 1).min(page_count)));
start += size;
}
return Ok(groups);
}
let mut groups = Vec::new();
for token in trimmed.split(',') {
let t = token.trim();
if let Ok(page) = t.parse::<usize>() {
if page < 1 || page > page_count {
return Err(invalid(format!("Page {page} is out of range (1–{page_count}).")));
}
groups.push(vec![page]);
continue;
}
if let Some((a, b)) = t.split_once('-') {
let (Ok(a), Ok(b)) = (a.trim().parse::<usize>(), b.trim().parse::<usize>()) else {
return Err(invalid(format!(
"\"{t}\" is not a page, a-b range, \"all\", or \"N/chunk\"."
)));
};
if b < a {
return Err(invalid(format!("Range {a}-{b} descends — use a-b with a ≤ b.")));
}
if a < 1 || b > page_count {
return Err(invalid(format!("Range {a}-{b} is out of range (1–{page_count}).")));
}
groups.push(range_pages(a, b));
continue;
}
return Err(invalid(format!(
"\"{t}\" is not a page, a-b range, \"all\", or \"N/chunk\"."
)));
}
Ok(groups)
}
/// Chunk-shaped = partition of 1..n into equal runs of ≥2 pages (last may be
/// short). Size-1 "chunks" are indistinguishable from 'all' — those stay page-N.
fn chunk_shaped(groups: &[Vec<usize>]) -> bool {
if groups.len() < 2 {
return false;
}
let size = groups[0].len();
if size < 2 {
return false;
}
let mut next = 1;
for (i, g) in groups.iter().enumerate() {
if g[0] != next {
return false;
}
next = g[g.len() - 1] + 1;
if i < groups.len() - 1 && g.len() != size {
return false;
}
if i == groups.len() - 1 && g.len() > size {
return false;
}
}
true
}
/// Pure naming pass: single page -> 'page-N.pdf'; chunk-shaped plan ->
/// 'chunk-K.pdf'; contiguous group -> 'pages-A-B.pdf'; else 'pages-A,B.pdf'.
pub fn plan_names(groups: &[Vec<usize>]) -> Vec<String> {
let chunk = chunk_shaped(groups);
groups
.iter()
.enumerate()
.map(|(i, g)| {
if chunk {
format!("chunk-{}.pdf", i + 1)
} else if g.len() == 1 {
format!("page-{}.pdf", g[0])
} else if g[g.len() - 1] - g[0] + 1 == g.len() {
format!("pages-{}-{}.pdf", g[0], g[g.len() - 1])
} else {
let joined: Vec<String> = g.iter().map(|p| p.to_string()).collect();
format!("pages-{}.pdf", joined.join(","))
}
})
.collect()
}
/// One output PDF per group: the source is loaded once, then each group is
/// extracted as a single-page-per-step sub-document chain merged back
/// together (the lopdf analogue of pdf-lib's copyPages + save). Mirrors
/// splitPdf() in src/lib/pdf-split.ts.
pub fn split_pdf(bytes: &[u8], groups: &[Vec<usize>]) -> Result<Vec<SplitOutput>, PdfToolError> {
if groups.is_empty() {
return Err(invalid("Nothing to split — plan at least one page."));
}
let src = lopdf::Document::load_mem(bytes).map_err(map_error)?;
let total = src.get_pages().len();
let names = plan_names(groups);
let mut outs = Vec::with_capacity(groups.len());
for (i, group) in groups.iter().enumerate() {
for &page in group {
if page < 1 || page > total {
return Err(invalid(format!("Page {page} is out of range (1–{total}).")));
}
}
// Each single group becomes its own document: clone the source and
// drop every page outside the group, then prune the orphaned objects.
let mut out = src.clone();
let keep: BTreeMap<u32, (u32, u16)> = src
.get_pages()
.into_iter()
.filter(|(num, _)| group.contains(&(*num as usize)))
.collect();
let all: Vec<u32> = src.get_pages().keys().copied().collect();
for num in all {
if !keep.contains_key(&num) {
out.delete_pages(&[num]);
}
}
out.prune_objects();
let page_count = out.get_pages().len();
let mut bytes_out = Vec::new();
out.save_to(&mut bytes_out).map_err(map_error)?;
outs.push(SplitOutput { name: names[i].clone(), bytes: bytes_out, page_count });
}
Ok(outs)
}
/// Page count for UI display — the Rust twin of the TS countPages() helper.
pub fn count_pages(bytes: &[u8]) -> Result<usize, PdfToolError> {
let doc = lopdf::Document::load_mem(bytes).map_err(map_error)?;
Ok(doc.get_pages().len())
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →