Split PDF Files in Java
Contents
[
Hide
]
Splitting a PDF into separate files is useful when you need to export each page for review, storage, or downstream processing.
Live Example
Aspose.PDF Splitter is a free online application for testing PDF splitting in a browser.
This example uses the Document class to open a PDF file and iterate through its pages. For each Page, it creates a new document, adds the page to it, and saves the result as a separate PDF file.
To split a PDF into individual page files in Java:
- Open the source PDF with the Document constructor.
- Iterate through the Page objects returned by
document.getPages(). - Create a new empty Document for each page.
- Add the current Page to the new Document.
- Save the new Document with a unique file name.
- Close both Document objects when processing is complete.
Split PDF into single-page files
The following Java example is based on SplitDocumentExamples.java and saves pages as Page_1.pdf, Page_2.pdf, and so on.
public static void splitDocument(Path inputFile, Path outputDir) {
Document document = new Document(inputFile.toString());
try {
int pageCount = 1;
for (Page page : document.getPages()) {
Document newDocument = new Document();
try {
newDocument.getPages().add(page);
newDocument.save(outputDir.resolve("Page_" + pageCount + ".pdf").toString());
} finally {
newDocument.close();
}
pageCount++;
}
} finally {
document.close();
}
}
