July 12, 2022

Merging PDFs in Java Using OpenPDF

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

OpenPDF is open source software with a LGPL and MPL license. To know more about OpenPDF library and PDF examples check this post- Generating PDF in Java Using OpenPDF Tutorial

Merging PDFs using OpenPDF

  1. To merge documents you need to use PDFCopy class which makes copies of PDF documents.
  2. Using PDFReader open the source PDFs and get pages from the PDF using getImportedPage() method of the PDFCopy class.

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;

public class PDFMerge {
  public static final String MERGED_PDF = "F://knpcode//result//OpenPDF//Merged.pdf";
  public static void main(String[] args) {
    try {
      // Source PDFs as a list
      List<String> fileList = Arrays.asList("F://knpcode//PDF1.pdf", "F://knpcode//PDF2.pdf");
      Document doc = new Document();
      // Output stream to target PDF document
      PdfCopy copy = new PdfCopy(doc, new FileOutputStream(MERGED_PDF));
      doc.open();
      // Iterate through PDF files. 
      for(String filePath : fileList) {
        PdfReader pdfreader = new PdfReader(filePath);
        int n = pdfreader.getNumberOfPages();
        PdfImportedPage page;
        // go through pages of PDF to copy 
        // all the pages to the  target PDF
        for (int i = 1; i <= n; i++) {
          // grab page from input document
          page = copy.getImportedPage(pdfreader, i);
          // add content to target PDF
          copy.addPage(page);
        }
        copy.freeReader(pdfreader);
      }
      doc.close();
      copy.close();
    } catch (DocumentException | IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

That's all for the topic Merging PDFs in Java Using OpenPDF. 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