Merging of multiple PDF’s can be easily done using PDFMergerUtility class of PDFBox. Lets see an example on how to Merge multiple pdf using Apache PDFBox.
The important methods that we will use of the PDFMergerUtility are:
a) addSource(String source)
Add a source file to the list of files to merge.
b) setDestinationFileName(String destination)
Set the name of the destination file
c) mergeDocuments(MemoryUsageSetting memUsageSetting)
Merge the list of source documents, saving the result in the destination file.
Example
We had already created 3 PDF’s from our previous posts, so we will use them and merge those into one pdf.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.kscodes.examples.pdfbox; import java.io.IOException; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.multipdf.PDFMergerUtility; public class PdfMergerExample { public static void main(String args[]) { try { // Initalize the PDFMergerUtility class PDFMergerUtility pdfMerger = new PDFMergerUtility(); // Add the PDF's that need to be merged pdfMerger.addSource("K:\\Kscodes\\pdf\\fontExample.pdf"); pdfMerger.addSource("K:\\Kscodes\\pdf\\rectangleSample.pdf"); pdfMerger.addSource("K:\\Kscodes\\pdf\\imageSample.pdf"); // Set a destination file for merging pdfMerger.setDestinationFileName("K:\\Kscodes\\pdf\\merged.pdf"); // Merge the documents pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); System.out.println("PDF merger completed !!!"); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output
You will see a new file created that has contents of all the three files.