PDF Split — Java source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-split — split one PDF into many by page plan with Apache PDFBox.
//
// Language: Java (17+), Apache PDFBox (display-only — the PDFBox API is
// called the way a real build would link it; this snippet is never compiled
// against the jar here)
// CosmoDev polyglot showcase port of the `pdf-split` tool.
// Ported from src/lib/pdf-split.ts — display source, part of CosmoDev's
// polyglot tool pages.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
/** Load failure kind: "encrypted" (password-protected) or "invalid" (unparseable). */
final class PdfSplit {
/** The Java twin of the TS PdfToolError class from src/lib/pdf-errors.ts. */
static final class PdfToolError extends RuntimeException {
final String code; // "encrypted" | "invalid"
PdfToolError(String code, String message) {
super(message);
this.code = code;
}
}
/** Split output: the planned file name, its bytes, and its page count. */
record SplitOutput(String name, byte[] bytes, int pageCount) {}
private static final Pattern CHUNK = Pattern.compile("^(\\d+)/chunk$");
private static final Pattern SINGLE = Pattern.compile("^\\d+$");
private static final Pattern SPAN = Pattern.compile("^(\\d+)-(\\d+)$");
/** Pure classifier — encrypted vs invalid, from the raw error message. */
static String classifyLoadError(String message) {
return message != null && message.toLowerCase().matches(".*(encrypt|password).*")
? "encrypted"
: "invalid";
}
/** Map a thrown load failure to a user-facing PdfToolError. */
static PdfToolError mapError(Exception e) {
return "encrypted".equals(classifyLoadError(e.getMessage()))
? new PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.")
: new PdfToolError("invalid", "Not a readable PDF file.");
}
/** The inclusive 1-based range [a..b] (the TS range() helper). */
private static List<Integer> spanRange(int a, int b) {
List<Integer> pages = new ArrayList<>(b - a + 1);
for (int p = a; p <= b; p++) pages.add(p);
return pages;
}
/**
* Pure planner — no PDFBox on this path. Grammar (mirrors parsePageRanges
* in src/lib/pdf-split.ts):
*
* <pre>
* 'all' -> [[1], [2], ..., [pageCount]]
* 'N/chunk' -> groups of N pages in order (last group may be short)
* 'a-b,c-d,e' -> [[a..b], [c..d], [e]] (1-based, inclusive)
* </pre>
*
* @throws PdfToolError code "invalid" on empty specs, unparseable tokens,
* descending ranges, and any page outside 1..pageCount
*/
static List<List<Integer>> parsePageRanges(String spec, int pageCount) {
String trimmed = spec.strip();
if (trimmed.isEmpty()) {
throw new PdfToolError("invalid", "Enter a page range first.");
}
if (trimmed.equals("all")) {
List<List<Integer>> groups = new ArrayList<>(pageCount);
for (int p = 1; p <= pageCount; p++) groups.add(List.of(p));
return groups;
}
Matcher chunk = CHUNK.matcher(trimmed);
if (chunk.matches()) {
int size = Integer.parseInt(chunk.group(1));
if (size < 1 || size > pageCount) {
throw new PdfToolError("invalid", "Chunk size must be between 1 and " + pageCount + ".");
}
List<List<Integer>> groups = new ArrayList<>();
for (int start = 1; start <= pageCount; start += size) {
groups.add(spanRange(start, Math.min(start + size - 1, pageCount)));
}
return groups;
}
List<List<Integer>> groups = new ArrayList<>();
for (String token : trimmed.split(",", -1)) {
String t = token.strip();
if (SINGLE.matcher(t).matches()) {
int page = Integer.parseInt(t);
if (page < 1 || page > pageCount) {
throw new PdfToolError("invalid", "Page " + page + " is out of range (1–" + pageCount + ").");
}
groups.add(List.of(page));
continue;
}
Matcher span = SPAN.matcher(t);
if (span.matches()) {
int a = Integer.parseInt(span.group(1));
int b = Integer.parseInt(span.group(2));
if (b < a) {
throw new PdfToolError("invalid", "Range " + a + "-" + b + " descends — use a-b with a ≤ b.");
}
if (a < 1 || b > pageCount) {
throw new PdfToolError("invalid", "Range " + a + "-" + b + " is out of range (1–" + pageCount + ").");
}
groups.add(spanRange(a, b));
continue;
}
throw new PdfToolError("invalid", "\"" + t + "\" is not a page, a-b range, \"all\", or \"N/chunk\".");
}
return 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.
*/
private static boolean chunkShaped(List<List<Integer>> groups) {
if (groups.size() < 2) return false;
int size = groups.get(0).size();
if (size < 2) return false;
int next = 1;
for (int i = 0; i < groups.size(); i++) {
List<Integer> g = groups.get(i);
if (g.get(0) != next) return false;
next = g.get(g.size() - 1) + 1;
if (i < groups.size() - 1 && g.size() != size) return false;
if (i == groups.size() - 1 && g.size() > size) return false;
}
return 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'.
*/
static List<String> planNames(List<List<Integer>> groups) {
boolean chunk = chunkShaped(groups);
List<String> names = new ArrayList<>(groups.size());
for (int i = 0; i < groups.size(); i++) {
List<Integer> g = groups.get(i);
if (chunk) {
names.add("chunk-" + (i + 1) + ".pdf");
} else if (g.size() == 1) {
names.add("page-" + g.get(0) + ".pdf");
} else if (g.get(g.size() - 1) - g.get(0) + 1 == g.size()) {
names.add("pages-" + g.get(0) + "-" + g.get(g.size() - 1) + ".pdf");
} else {
names.add("pages-" + String.join(",", g.stream().map(String::valueOf).toList()) + ".pdf");
}
}
return names;
}
/**
* One output PDF per group: the source is loaded once with PDFBox's
* Loader, then each planned page is imported into a fresh PDDocument and
* saved (the PDFBox analogue of pdf-lib's copyPages). Mirrors splitPdf()
* in src/lib/pdf-split.ts.
*/
static List<SplitOutput> splitPdf(byte[] pdf, List<List<Integer>> groups) {
if (groups.isEmpty()) {
throw new PdfToolError("invalid", "Nothing to split — plan at least one page.");
}
try (PDDocument src = Loader.loadPDF(pdf)) {
if (src.isEncrypted()) {
throw new PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.");
}
int total = src.getNumberOfPages();
List<String> names = planNames(groups);
List<SplitOutput> outs = new ArrayList<>(groups.size());
for (int i = 0; i < groups.size(); i++) {
for (int page : groups.get(i)) {
if (page < 1 || page > total) {
throw new PdfToolError("invalid", "Page " + page + " is out of range (1–" + total + ").");
}
}
PDDocument out = new PDDocument();
for (int page : groups.get(i)) {
// importPage deep-copies the page and appends it to out.
out.importPage(src.getPage(page - 1));
}
int outPages = out.getNumberOfPages();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
out.save(buffer);
out.close();
outs.add(new SplitOutput(names.get(i), buffer.toByteArray(), outPages));
}
return outs;
} catch (PdfToolError e) {
throw e;
} catch (IOException | IllegalArgumentException e) {
throw mapError(e);
}
}
/** Page count for UI display — the Java twin of the TS countPages() helper. */
static int countPages(byte[] pdf) {
try (PDDocument doc = Loader.loadPDF(pdf)) {
if (doc.isEncrypted()) {
throw new PdfToolError("encrypted", "This PDF is password-protected. Unlock it first.");
}
return doc.getNumberOfPages();
} catch (PdfToolError e) {
throw e;
} catch (IOException | IllegalArgumentException e) {
throw mapError(e);
}
}
}
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 →