Saturday, 12 March 2022

Java: PdfBox: split pdf file page by page

In this post, I am going to explain how to convert every page of pdf file to a new pdf file. Suppose, if your pdf files has 5 pages, I want to split this file into 5 small pdf file, where each page in the original pdf file will become a new file.

 

Step 1: Load the pdf file.

PDDocument pdfDocument = PDDocument.load(inputPdfFile)

Step 2: Get Splitter instance.

 

Splitter splitter = new Splitter();
splitter.setSplitAtPage(1);

 

‘setSplitAtPage’ method specifies where to split the pages.  The default is 1, so every page will become a new document.  If it was two then each document would contain 2 pages.  If the source document had 5 pages it would split into 3 new documents, 2 documents containing 2 pages and 1 document containing one page.

 

Step 3: Split the pdf file.

List<PDDocument> documents = splitter.split(pdfDocument);

Step 4: Write the split documents to separate file.

splitDocument.save(new File(destinationFolder, splitFileName));
splitDocument.close();



Find the below working application.

 

SplitPdfDocument.java

package com.sample.app;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;

public class SplitPdfDocument {

	public static void splitPdf(File inputPdfFile, File destinationFolder, String outputFileName) throws IOException {
		try (PDDocument pdfDocument = PDDocument.load(inputPdfFile)) {

			Splitter splitter = new Splitter();

			splitter.setSplitAtPage(1);

			List<PDDocument> documents = splitter.split(pdfDocument);

			int count = 1;
			
			for (PDDocument splitDocument : documents) {
				String splitFileName = String.format("%s%04d.pdf", outputFileName, count);
				splitDocument.save(new File(destinationFolder, splitFileName));
				splitDocument.close();
				count++;
			}

		}
	}

	public static void main(String[] args) throws IOException {
		splitPdf(new File("/Users/Shared/personal/test.pdf"), new File("/Users/Shared/personal"), "demo");
	}
}




 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment