Apache PDFBox Merge Multiple PDF Documents in Java
The following example demonstrates how to use Apache PdfBox to merge multiple PDF Documents.
Maven Dependencies
We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on the class-path.
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
Apache PDFBox Merge Multiple PDF Documents
package com.memorynotfound.pdf.pdfbox;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import java.io.File;
import java.io.IOException;
public class MergePdf {
public static void main(String[] args) throws Exception{
try {
PDFMergerUtility pdfMerger = new PDFMergerUtility();
pdfMerger.setDestinationFileName("/tmp/merged.pdf");
PDDocumentInformation documentInformation = new PDDocumentInformation();
documentInformation.setTitle("Apache PdfBox Merge PDF Documents");
documentInformation.setCreator("memorynotfound.com");
documentInformation.setSubject("Merging PDF documents with Apache PDF Box");
pdfMerger.addSource(new File("/tmp/image.pdf"));
pdfMerger.addSource(new File("/tmp/example.pdf"));
pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
} catch (IOException e){
System.err.println("Exception while trying to merge pdf document - " + e);
}
}
}
Demo
When we run the application, the two PDF documents are merged into one.
References
- Apache PdfBox Official Website
- Apache PdfBox API Javadoc
- Apache PdfBox read PDF document
- Apache PdfBox create PDF document
- PDFMergerUtility JavaDoc
- MemoryUsageSetting JavaDoc
Download
Download it – apache pdfbox merge multiple pdf document java