"Upload only the result page." "Attach pages 2–4 of your bank statement." Online forms ask for this all the time, and people end up installing an app or uploading private documents to some random server just to cut a PDF in two.
You don't need a server for this. pdf-lib can do it in the browser, and the whole feature is about 40 lines. Here's how the Split PDF tool on my site works.
1. Load the file and count pages
const buf = await file.arrayBuffer();
let src;
try {
src = await PDFLib.PDFDocument.load(buf, { ignoreEncryption: true });
} catch (e) {
showError('This PDF could not be opened (maybe password-protected).');
return;
}
const count = src.getPageCount();
Wrap load in a try/catch. Real-world PDFs are messy, and you want a human message instead of a stack trace in the console. I pre-fill the range box with 1-<count> so people can see how many pages they have.
2. Parse what the user types
Users type things like 1-3, 5, 7, or 2-3, 8-9. A tiny parser turns that into zero-based page indices:
function parse(s, count) {
const out = [];
s.split(',').forEach(part => {
const m = part.trim().match(/^(\d+)\s*(?:-\s*(\d+))?$/);
if (!m) return; // ignore junk like "abc"
let a = +m[1], b = m[2] ? +m[2] : a;
if (a > b) [a, b] = [b, a]; // "5-2" means 2-5
for (let i = a; i <= b; i++)
if (i >= 1 && i <= count) out.push(i - 1);
});
return out;
}
Three small decisions matter here:
-
Out-of-range pages are skipped silently. Typing
1-20on a 12-page file gives you 12 pages, not an error. -
Reversed ranges get flipped. Nobody means "zero pages" when they type
5-2. -
Order is kept as typed.
5, 1gives page 5 first. That turned out to be a handy way to reorder pages without a separate tool.
3. Copy pages into a new document
async function make(src, indices) {
const out = await PDFLib.PDFDocument.create();
const pages = await out.copyPages(src, indices);
pages.forEach(p => out.addPage(p));
return new Blob([await out.save()], { type: 'application/pdf' });
}
copyPages copies the page objects as they are, fonts and images included. Nothing is rasterised or re-compressed, so the output looks identical to the input. That's the main advantage over "print to PDF" tricks, which re-render everything.
4. Two modes, same function
-
Extract pages: call
make(src, parse(input))once and download a single file. -
Every page separately: loop
ifrom0tocount - 1and callmake(src, [i])for each page, giving one download per page.
I add the size of each blob to its label, because the usual reason someone splits a PDF is that the portal rejected a file for being too big.
Things to watch
- Load once and reuse. If you re-parse a big file for every page in "every page" mode, it gets slow on phones.
- Revoke object URLs when the user picks a new file, or memory grows on long sessions.
- Encrypted PDFs won't behave. Tell users to remove the password in their reader first, rather than pretending it worked.
That's the whole thing, and the file never leaves the browser tab. If you're building any document tool, check whether it really needs a backend. Surprisingly often it doesn't.
I run 14FreeTools, a set of free browser-based tools. The same pdf-lib approach powers the Merge PDF tool.
Top comments (0)