Saturday, 12 March 2022

PdfBox: Merge multiple pdf files into single pdf document

In this post, I am going to explain how to merge multiple pdf files into a single pdf document.

 

Step 1: Get an instance of PDFMergerUtility.

PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();

 

Step 2: Set the destination file path

pdfMergerUtility.setDestinationFileName(outputPdfFile.getPath());

Step 3: Add input source files to the merger utility.

for (File inputPdfFile : inputPdfFiles) {
	pdfMergerUtility.addSource(inputPdfFile);
}

Step 4: Merge the documents.

pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());




Find the below working application.

 

MergeMultiplePdfFiles.java

package com.sample.app;

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

public class MergeMultiplePdfFiles {

	public static void mergePdfFiles(File[] inputPdfFiles, File outputPdfFile) throws IOException {

		// Create parent directories for output file
		File parentDir = outputPdfFile.getParentFile();
		if(parentDir.getParentFile() != null) {
			parentDir.mkdirs();
		}
		
		PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
		
		pdfMergerUtility.setDestinationFileName(outputPdfFile.getPath());
		
		for (File inputPdfFile : inputPdfFiles) {
			pdfMergerUtility.addSource(inputPdfFile);
		}
		
		pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());

	}

	public static void main(String[] args) throws IOException {

		File[] inputFiles = new File[] {
				new File("/Users/Shared/personal/demo0001.pdf"),
				new File("/Users/Shared/personal/demo0002.pdf"),
				new File("/Users/Shared/personal/demo0003.pdf"),
		};
		
		File outputPdfFile = new File("/Users/Shared/personal/demo/dest.pdf");
		
		mergePdfFiles(inputFiles, outputPdfFile);
	}

}




 

Previous                                                 Next                                                 Home

No comments:

Post a Comment