Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split PDF Files in Java
// Open document
Document pdfDocument = new Document("input.pdf");
// Create array lists for even and odd pages
List<Page> evenPages = new ArrayList<Page>();
List<Page> oddPages = new ArrayList<Page>();
// Loop through all the pages
for (Page pdfPage : pdfDocument.getPages())
{
if(pdfPage.getNumber()%2==0)
{
evenPages.add(pdfPage);
}
else
{
oddPages.add(pdfPage);
}
}
// Save even pages as PDF
Document newDocument = new Document();
newDocument.getPages().add(evenPages);
newDocument.save("split_even_Pages.pdf");
// Save odd pages as PDF
newDocument = new Document();
newDocument.getPages().add(oddPages);
newDocument.save("split_odd_Pages.pdf");
// Open document
Document pdfDocument = new Document("input.pdf");
// For page counter
int pageCount = 1;
// Loop through all the pages
for (Page pdfPage : pdfDocument.getPages()) {
// Create a new document
Document newDocument = new Document();
// Add page to the document
newDocument.getPages().add(pdfPage);
// Save as PDF
newDocument.save("page_" + pageCount + "_out" + ".pdf");
pageCount++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment