Merging multiple PDF documents into a single PDF document is done using the PDFMergerUtility class. This class will take a list of PDF documents and merge them, the result will be saved to the new document. The prerequisite of this topic is that you have already installed apache library
Follow these steps to merge multiple PDF documents:
- First we have to instantiate the PDFMergerUtility class.
- Second we have to set the destination file using the setDestinationFileName() method.
- Now we have to set the source files using the addSource() method.
- Final step we have to merge the documents using the mergeDocuments() method of the PDFMergerUtility class.
Example:
Input : PDF1 = Alice.pdf, PDF2 = Bob.pdf
Output: newMerged.pdf // merged pdf of pdf1 and pdf2
Implementation:
Java
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
public class GFG {
public static void main(String[] args)
throws IOException
{
File file1 = new File(
"/Users/piyushkumar/Desktop/Merging Pdfs/file1.pdf" );
File file2 = new File(
"/Users/piyushkumar/Desktop/Merging Pdfs/file2.pdf" );
PDFMergerUtility obj = new PDFMergerUtility();
obj.setDestinationFileName(
"/Users/piyushkumar/Desktop/Merging Pdfs/newMerged.pdf" );
obj.addSource(file1);
obj.addSource(file2);
obj.mergeDocuments();
System.out.println(
"PDF Documents merged to a single file" );
}
}
|
Before the execution of the code :

After the execution of the code :

If you check the specified path, you will see that a PDF document named newMerged.pdf has been generated which contains the pages of both the original documents.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
08 Dec, 2020
Like Article
Save Article