March 30, 2022

Merging PDFs in Java Using iText

In this post we’ll see a Java program to merge two PDF documents using iText library.

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

Merging PDFs using iText

In iText there is a PDFMerger class that can be used for merging PDFs. Using this class you can merge a number of existing documents into one.

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

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;

public class MergePDF {
  public static final String SRC_PDF1 = "F://knpcode//PDF1.pdf";
  public static final String SRC_PDF2 = "F://knpcode//PDF2.pdf";
  public static final String MERGED_PDF = "F://knpcode//result//Merged.pdf";
  public static void main(String[] args) throws IOException{
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(MERGED_PDF));               
    PdfMerger merger = new PdfMerger(pdfDoc);
    PdfDocument PDF1 = new PdfDocument(new PdfReader(SRC_PDF1));
    PdfDocument PDF2 = new PdfDocument(new PdfReader(SRC_PDF2));
    merger.merge(PDF1, 1, PDF1.getNumberOfPages());
    merger.merge(PDF2, 1, PDF2.getNumberOfPages());

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