Merge Multiple PDFs to Single PDF
We can merge two or more PDFs to a single PDF using PDFBox.
In this tutorial, we will learn the steps required to merge multiple PDF documents to a single PDF.
To Merge Multiple PDFs to Single PDF, use PDFMergerUtility.mergeDocuments(File file) method. You may merge an many number of files as required.
Steps – Merge Multiple PDF Files
Following is a step by step guide to merge multiple PDF files.
Step 1: Load PDF Files
Load all the source PDF files you wish to merge.
File file1 = new File("/home/tk/sample_1.pdf");
File file2 = new File("/home/tk/sample_2.pdf");
File file3 = new File("/home/tk/sample_3.pdf");Merge Documents.
Step 2: Instantiate PDFMergerUtility
PDFMergerUtility Class contains routines to merge PDFs.
PDFMergerUtility pdfMerger = new PDFMergerUtility();
Step 3: Set Destination
Set path to destination file using PDFMergerUtility.setDestinationFileName(String fileName) method.
pdfMerger.setDestinationFileName("/home/tk/sample_pdf.pdf");
Step 4: Add all PDFs
Add all the source PDF files to be merged, to PDFMergerUtility using PDFMergerUtility.addSource() method.
pdfMerger.addSource(file1);
pdfMerger.addSource(file2);
pdfMerger.addSource(file3);
Add all the source pdf files one by one in the sequence you would like to find in the final merged PDF file.
Step 5: Merge Documents
And finally call the method PDFMergerUtility.mergeDocuments() to merge all the documents.
pdfMerger.mergeDocuments(null);
Complete Java Program
MergePDFsExample.java
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.io.File;
import java.io.IOException;
public class MergePDFsExample {
public static void main(String[] args) throws IOException {
// load pdf files to be merged
File file1 = new File("/home/tk/sample_1.pdf");
File file2 = new File("/home/tk/sample_2.pdf");
File file3 = new File("/home/tk/sample_3.pdf");
// instantiatE PDFMergerUtility class
PDFMergerUtility pdfMerger = new PDFMergerUtility();
// set destination file path
pdfMerger.setDestinationFileName("/home/tk/sample_pdf.pdf");
// add all source files, to be merged, to pdfMerger
pdfMerger.addSource(file1);
pdfMerger.addSource(file2);
pdfMerger.addSource(file3);
// merge documents
pdfMerger.mergeDocuments(null);
System.out.println("PDF Documents merged to a single file");
}
}
Output
PDF Documents merged to a single file