PDF Split — JavaScript source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-split — split one PDF into many by page plan with pdf-lib (npm), the
// plain-JS twin of src/lib/pdf-split.ts. Same planner grammar: 'all',
// 'N/chunk', or comma-separated 'a-b' ranges and single pages (1-based,
// inclusive), with the same naming rules for each output file.
import { PDFDocument } from 'pdf-lib';
/** Load failure kind: 'encrypted' (password-protected) or 'invalid' (unparseable). */
export class PdfToolError extends Error {
constructor(code, message) {
super(message);
this.code = code;
}
}
/** Pure classifier — encrypted vs invalid, from the raw error message. */
export function classifyLoadError(msg) {
return msg && /encrypt|password/i.test(msg) ? 'encrypted' : 'invalid';
}
/** Map a thrown load/parse error to a user-facing PdfToolError. */
function mapError(e) {
const msg = e instanceof Error ? e.message : String(e);
const kind = classifyLoadError(msg);
throw new PdfToolError(
kind,
kind === 'encrypted'
? 'This PDF is password-protected. Unlock it first.'
: 'Not a readable PDF file.',
);
}
function rangePages(a, b) {
const pages = [];
for (let p = a; p <= b; p++) pages.push(p);
return pages;
}
/**
* Pure planner — grammar: 'all' → one page per group; 'N/chunk' → groups of
* N pages in order (last may be short); 'a-b,c-d,e' → explicit groups.
* Throws PdfToolError('invalid') on bad specs or out-of-range pages.
*/
export function parsePageRanges(spec, pageCount) {
const trimmed = spec.trim();
if (!trimmed) throw new PdfToolError('invalid', 'Enter a page range first.');
if (trimmed === 'all') {
return Array.from({ length: pageCount }, (_, i) => [i + 1]);
}
const chunk = trimmed.match(/^(\d+)\/chunk$/);
if (chunk) {
const size = Number(chunk[1]);
if (size < 1 || size > pageCount) {
throw new PdfToolError('invalid', `Chunk size must be between 1 and ${pageCount}.`);
}
const groups = [];
for (let start = 1; start <= pageCount; start += size) {
groups.push(rangePages(start, Math.min(start + size - 1, pageCount)));
}
return groups;
}
return trimmed.split(',').map((token) => {
const t = token.trim();
if (/^\d+$/.test(t)) {
const page = Number(t);
if (page < 1 || page > pageCount) {
throw new PdfToolError('invalid', `Page ${page} is out of range (1–${pageCount}).`);
}
return [page];
}
const span = t.match(/^(\d+)-(\d+)$/);
if (span) {
const a = Number(span[1]);
const b = Number(span[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}).`);
}
return rangePages(a, b);
}
throw new PdfToolError('invalid', `"${t}" is not a page, a-b range, "all", or "N/chunk".`);
});
}
/** Chunk-shaped = partition of 1..n into equal runs of ≥2 pages (last may be short). */
function chunkShaped(groups) {
if (groups.length < 2) return false;
const size = groups[0].length;
if (size < 2) return false; // size-1 "chunks" are indistinguishable from 'all'
let next = 1;
for (let i = 0; i < groups.length; i++) {
const g = groups[i];
if (g[0] !== next) return false;
next = g[g.length - 1] + 1;
if (i < groups.length - 1 && g.length !== size) return false;
if (i === groups.length - 1 && g.length > 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'.
*/
export function planNames(groups) {
const chunk = chunkShaped(groups);
return groups.map((g, i) => {
if (chunk) return `chunk-${i + 1}.pdf`;
if (g.length === 1) return `page-${g[0]}.pdf`;
const a = g[0];
const b = g[g.length - 1];
if (b - a + 1 === g.length) return `pages-${a}-${b}.pdf`;
return `pages-${g.join(',')}.pdf`;
});
}
/** One output PDF per group, via copyPages on the 0-based group indices. */
export async function splitPdf(bytes, groups) {
if (groups.length === 0) throw new PdfToolError('invalid', 'Nothing to split — plan at least one page.');
try {
const src = await PDFDocument.load(bytes, { ignoreEncryption: false });
const total = src.getPageCount();
const names = planNames(groups);
const outs = [];
for (let i = 0; i < groups.length; i++) {
for (const page of groups[i]) {
if (page < 1 || page > total) {
throw new PdfToolError('invalid', `Page ${page} is out of range (1–${total}).`);
}
}
const out = await PDFDocument.create();
const pages = await out.copyPages(src, groups[i].map((p) => p - 1));
pages.forEach((p) => out.addPage(p));
const saved = await out.save({ useObjectStreams: true });
outs.push({ name: names[i], bytes: saved, pageCount: out.getPageCount() });
}
return outs;
} catch (e) {
if (e instanceof PdfToolError) throw e;
mapError(e);
}
}
/** Page count for UI display — the tool's only other pdf-lib need. */
export async function countPages(bytes) {
try {
const doc = await PDFDocument.load(bytes, { ignoreEncryption: false });
return doc.getPageCount();
} catch (e) {
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 →