PDF Split — TypeScript source
Split a PDF by page, chunk size, or custom ranges — entirely in your browser. Nothing uploads.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// pdf-split — second leg of the PDF trio (FEAT-035). Mirrors pdf-merge.ts:
// statically imports pdf-lib, but only the island's dynamic import keeps it
// out of the eager ToolRouter chunk (BUG-007 pattern; the perf budget's
// jsBytes line depends on it). Error types live in pdf-errors.ts
// (pdf-lib-free) so islands never need a static path into this module.
import { PDFDocument } from 'pdf-lib';
import { mapError, PdfToolError } from './pdf-errors';
export { PdfToolError, classifyLoadError, mapError } from './pdf-errors';
export type SplitOutput = { name: string; bytes: Uint8Array; pageCount: number };
/**
* Pure planner — no pdf-lib on this path. Grammar:
* '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)
* Throws PdfToolError('invalid') on empty/whitespace specs, unparseable
* tokens, descending ranges, and any page outside 1..pageCount.
*/
export function parsePageRanges(spec: string, pageCount: number): number[][] {
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: number[][] = [];
for (let start = 1; start <= pageCount; start += size) {
const end = Math.min(start + size - 1, pageCount);
groups.push(range(start, end));
}
return groups;
}
return trimmed.split(',').map((token) => {
const t = token.trim();
const single = t.match(/^\d+$/);
if (single) {
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 range(a, b);
}
throw new PdfToolError('invalid', `"${t}" is not a page, a-b range, "all", or "N/chunk".`);
});
}
function range(a: number, b: number): number[] {
const pages: number[] = [];
for (let p = a; p <= b; p++) pages.push(p);
return pages;
}
/**
* Pure naming for a planned split — the single source of truth shared by
* splitPdf and the island's live preview. Single page → 'page-N.pdf';
* chunk-shaped plan → 'chunk-K.pdf' (K 1-based); contiguous group →
* 'pages-A-B.pdf'; otherwise 'pages-A,B.pdf' (joined).
*/
export function planNames(groups: number[][]): string[] {
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`;
});
}
/** Chunk-shaped = partition of 1..n into equal runs of ≥2 pages (last may be short). */
function chunkShaped(groups: number[][]): boolean {
if (groups.length < 2) return false;
const size = groups[0].length;
// Size-1 "chunks" are indistinguishable from 'all' — those stay page-N.
if (size < 2) return false;
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;
}
/**
* One output PDF per group, via PDFDocument.create + copyPages on the
* 0-based indices of each 1-based group. Load failures map exactly like
* pdf-merge.ts (encrypted vs invalid).
*/
export async function splitPdf(bytes: Uint8Array, groups: number[][]): Promise<SplitOutput[]> {
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: SplitOutput[] = [];
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 island's only other pdf-lib need. */
export async function countPages(bytes: Uint8Array): Promise<number> {
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 →