July 14, 2022

Merging PDFs in Java Using PDFBox

In this post we’ll see a Java program to merge PDFs using PDFBox library.

To know more about Apache PDFBox library and PDF examples in Java using PDFBox check this post- Generating PDF in Java Using PDFBox Tutorial

Merging PDFs using PDFBox

  1. To merge PDFs, PDFBox library provides PDFMergerUtility class which takes a list of pdf documents and merge them, saving the result in a new document.
  2. Add the PDF files that are to be merged using addSource() method of the PDFMergerUtility class.
  3. Add the destination PDF file name using the setDestinationFileName() method of the PDFMergerUtility class.

Following Java program shows how two PDF documents can be merged using PDFBox.

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;

public class PDFMerger {
  public static final String MERGED_PDF = "F://knpcode//result//PDFBox//Merged.pdf";
  public static void main(String[] args) {
    // Source PDFs as a list
    List<String> fileList = Arrays.asList("F://knpcode//PDF1.pdf", "F://knpcode//PDF2.pdf");
    PDFMergerUtility pdfMerger = new PDFMergerUtility();
    pdfMerger.setDestinationFileName(MERGED_PDF);
    try {
      // iterate list and add files to PDFMergerUtility
      for(String filePath : fileList) {			
        pdfMerger.addSource(filePath);
      }
      // Merge documents
      pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
    }catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }		
  }
}

That's all for the topic Merging PDFs in Java Using PDFBox. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment