Merge Two PDF Files Java Itext Example

In this tutorial, we will provide a working Java Code example, that will explain how to merge multiple PDF documents in Java. Joining PDF files is a very common requirement and the latest iText implementation provides a straightforward and simpler way to combine PDF documents. I will be using iText 3.0 version for this simple example and I would request the reader to download itext 3.0 to work this out.

Before you follow the step by step instructions to combine PDF documents using Java iText, make sure you have two PDF files to try the example provided in this guide. Follow the procedure provided below, after you have the necessary input files. For explaining this merging, I will be using two PDF documents, each containing one page as shown below; (The final Merged PDF document must contain two pages, as expected) [ Note: If you do a Google search for Merging PDF files, you can find two examples already. I found them to be little complex and thought of following a different approach ]

Java Combine Merge PDF Files Example
Contents inside Input File for Merging Example

Step -1: We define a string array that will hold the input files that needs to be combined into a Single PDF. We will also declare a Document object that will hold the final joined PDF document.Refer to the code snippet below;
          String[] files = { "File1.pdf", "File2.pdf" };
          Document PDFCombineUsingJava = new Document();
Step-2: We will create a PdfCopy object by passing the Document object created in Step 1 and provide the name of the final merged PDF document as a FileOutputStream to the constructor.Needless to say, we will open the Document object for writing after this step. You can do this as given below;
          PdfCopy copy = new PdfCopy(PDFCombineUsingJava, new FileOutputStream("CombinedPDFDocument.pdf"));
          PDFCombineUsingJava.open();
Step-3: For reading contents from existing PDF files, we need a PdfReader object. For each input file in the String array, we get the file into the PdfReader object. We then use "getNumberofPages" method to find the number of pages in the input PDF file. Using this information, we use the "addPage" method of PdfCopy object and invoke "getImportedPage" to combine the contents to new PDF. Sounds complex? Don't worry..follow the code below, which will make it look very easy;
          int number_of_pages;
          for (int i = 0; i < files.length; i++) {
                  ReadInputPDF = new PdfReader(files[i]);
                  number_of_pages = ReadInputPDF.getNumberOfPages();
                  for (int page = 0; page < number_of_pages; ) {
                          copy.addPage(copy.getImportedPage(ReadInputPDF, ++page));
                        }
          }
          PDFCombineUsingJava.close();

You need to do only this much to combine PDF documents Using Java Itext library. This has been made really simple by using the PdfCopy object. When you run this code, you can find the final Merged PDF document sitting inside the same folder where you have placed your input files. With this method, you can also combine and join more than two PDF documents. The complete code example for this tutorial is provided below for your understanding;
import java.io.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
public class MergePDF {  
     public static void main(String[] args){
        try {
          String[] files = { "File1.pdf", "File2.pdf" };
          Document PDFCombineUsingJava = new Document();
          PdfCopy copy = new PdfCopy(PDFCombineUsingJava, new FileOutputStream("CombinedPDFDocument.pdf"));
          PDFCombineUsingJava.open();
          PdfReader ReadInputPDF;
          int number_of_pages;
          for (int i = 0; i < files.length; i++) {
                  ReadInputPDF = new PdfReader(files[i]);
                  number_of_pages = ReadInputPDF.getNumberOfPages();
                  for (int page = 0; page < number_of_pages; ) {
                          copy.addPage(copy.getImportedPage(ReadInputPDF, ++page));
                        }
          }
          PDFCombineUsingJava.close();
        }
        catch (Exception i)
        {
            System.out.println(i);
        }
    }
}
Got a problem? Post it, we will have a look.

4 comments:

  1. Hi,
    I have a pdf document with the footer and page number as 1 of 3, 2 of 3 etc. Now I have added 2 pages to the existing pdf document. I am not able to rewrite the new page count in the footer section..I should get it as 1 of 5 , 2 of 5 etc.
    Can you please help on this.

    ReplyDelete
    Replies
    1. Save Tabular PDF into TXT using java :
      Generally when we do it all the pdf format get worst and all data are compressed form where we've problem to extract the data from it.
      But you can be do it with great and pleasure ways.

      Delete
  2. How to append the data instead of adding the pages at the end of first PDF?

    For example , In the first PDF i have 2 1/2 pages data and my second pdf should start exactly after 2 1/2 pages.. Will this be possible?

    ReplyDelete
  3. This is the "correct" method. Works with iText 2.x. Thanks.

    ReplyDelete