Prompt
How do I split a PDF into separate files programmatically?
Latest observation
Oct 12, 2026
OpenAI APIWeb search: off
You can split a PDF programmatically in several ways, depending on your language and whether you want to split by pages, ranges, or bookmarks. Here are common approaches.
1) Python
Using pypdf
Install:
pip install pypdf
Split into single-page PDFs:
from pypdf import PdfReader, PdfWriter
input_pdf = "input.pdf"
reader = PdfReader(input_pdf)
for i, page in enumerate(reader.pages):
writer = PdfWriter()
writer.add_page(page)
output_name = f"page_{i+1}.pdf"
with open(output_name, "wb") as f:
writer.write(f)
Split into page ranges:
from pypdf import PdfReader, PdfWriter
reader = PdfReader("input.pdf")
ranges = [(0, 2), (3, 5)] # pages 1-3 and 4-6
for idx, (start, end) in enumerate(ranges, 1):
writer = PdfWriter()
for i in range(start, end + 1):
writer.add_page(reader.pages[i])
with open(f"part_{idx}.pdf", "wb") as f:
writer.write(f)
2) JavaScript / Node.js
Using pdf-lib
Install:
npm install pdf-lib
Example:
const fs = require("fs");
const { PDFDocument } = require("pdf-lib");
async function splitPdf(inputPath) {
const pdfBytes = fs.readFileSync(inputPath);
const pdfDoc = await PDFDocument.load(pdfBytes);
for (let i = 0; i < pdfDoc.getPageCount(); i++) {
const newPdf = await PDFDocument.create();
const [copiedPage] = await newPdf.copyPages(pdfDoc, [i]);
newPdf.addPage(copiedPage);
const outBytes = await newPdf.save();
fs.writeFileSync(`page_${i + 1}.pdf`, outBytes);
}
}
splitPdf("input.pdf");
3) Java
Using Apache PDFBox
Add dependency:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.30</version>
</dependency>
Split into single pages:
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
public class SplitPdf {
public static void main(String[] args) throws IOException {
try (PDDocument document = PDDocument.load(new File("input.pdf"))) {
int pageCount = document.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
try (PDDocument newDoc = new PDDocument()) {
newDoc.importPage(document.getPage(i));
newDoc.save("page_" + (i + 1) + ".pdf");
}
}
}
}
}
4) Command-line tools from code
If you’re okay calling a system tool:
pdftk
pdftk input.pdf burst output page_%02d.pdf
qpdf
qpdf input.pdf --split-pages -- page-%d.pdf
Or from a script using subprocess / exec.
Choosing an approach
- Python: easiest for quick automation
- Node.js: good for web/backend apps
- Java: robust for enterprise apps
- CLI tools: simplest if you just need a utility
If you want, I can also give you:
- a version that splits by specific page ranges,
- a version that splits by bookmarks/sections, or
- a ready-to-run script in your preferred language.