Wednesday, 22 February 2017

Merging PDF files in Java Using Apache PDFBox

The codes below illustrate how to merge all PDF files and create new one.

We will user Apache PDFBox with Java to merge all PDF files and create new one. To use Apache PDFBox we need to download required jar or add dependency if using Maven build tool.
Here we will add dependency in project POM.xml file.

1. Add Maven dependency for Apache PDFBox.
<dependency>
              <groupId>org.apache.pdfbox</groupId>
              <artifactId>pdfbox</artifactId>
              <version>2.0.4</version>
</dependency>

2. code:

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;

public class PDFMerger {

    public static void main(String[] args){
       File file1 = new File("D:\\pdf\\filePDF1.pdf");
       File file2 = new File("D:\\pdf\\filePDF2.pdf");
       File file3 = new File("D:\\pdf\\filePDF2.pdf");
      
       File[] pdfFiles = {file1,file2,file3};
      
       PDDocument pdDocument = null;
       PDFMergerUtility pdfMergerUtil = new PDFMergerUtility();
      
       try {
           for (File pdf : pdfFiles) {
              PDDocument pdDoc = null;
              try {
                  if(null == pdDocument){
                     pdDocument = PDDocument.load(pdf);
                  }else{
                     pdDoc = PDDocument.load(pdf);
                     pdfMergerUtil.appendDocument(pdDocument, pdDoc);
                  }
              } catch (InvalidPasswordException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                  if (pdDoc != null) {
                     pdDoc.close();
                  }
              }
           }
           System.out.println("PDF merging done....");
           pdDocument.save("D:\\pdf\\merged.pdf");
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
              if (pdDocument != null) {
                  pdDocument.close();
              }
           } catch (IOException ioe) {
              ioe.printStackTrace();
           }
       }
    }
   

}

No comments:

Post a Comment