Monday, December 30, 2024
Google search engine
HomeLanguagesJavaMerging PDFs using Java

Merging PDFs using Java

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:

  1. First we have to instantiate the PDFMergerUtility class.
  2. Second we have to set the destination file using the setDestinationFileName() method.
  3. Now we have to set the source files using the addSource() method.
  4. 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




// Merging multiple pdf documents here
  
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
    {
  
        // loading all the pdf files we wish to merge
  
        File file1 = new File(
            "/Users/piyushkumar/Desktop/Merging Pdfs/file1.pdf");
        File file2 = new File(
            "/Users/piyushkumar/Desktop/Merging Pdfs/file2.pdf");
  
        // Instantiating PDFMergerUtility class
  
        PDFMergerUtility obj = new PDFMergerUtility();
  
        // Setting the destination file path
  
        obj.setDestinationFileName(
            "/Users/piyushkumar/Desktop/Merging Pdfs/newMerged.pdf");
  
        // Add all source files, to be merged
  
        obj.addSource(file1);
        obj.addSource(file2);
  
        // Merging documents
  
        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.

RELATED ARTICLES

Most Popular

Recent Comments