Concatenate two pdf files

In this section, you will read how to concatenate two pdf files in java.

Concatenate two pdf files

In this section, you will read how to concatenate two pdf files in java.

Concatenate two pdf files

Concatenate two pdf files

     

In this program we are going to concatenate two pdf files into a  pdf file through java program. The all data of files  are concatenated into
the pdf. You can concentrate only two  files into a single file. 

In this example we need iText.jar file, without this jar file we never compile our application . The package we need to import are java.io. FileOutputStream,j com.lowagie.text.pdf.PdfCopy,com.lowagie.text.pdf.PdfReader,

The java.io.FileOutputStream  class is used to create file.T. com. lowagie.text.pdf.PdfCopy  class is used to make copies of  PDF documents and It extends PdfWriter. The com.lowagie.text.pdf.PdfReader class is used to read pdf from specified file. PdfReader class throws an IOException  and extends Object class

To make the program for concatenate pdf  files  firstly we will make a class Concanenate. Remember the name of the file should be such that, if any other person sees the example then just by seeing the name of the program he can understand what the program is going to do without seeing the code. 
The steps to execute this program:

  1. Makes minimum two pdf file.
  2. Download the  iTex.jar file .
  3. Copy iText.jar into lib directory and Set the class.
  4.  Make or Download the source code of program.
  5. Put the source code and pdf files into same directory.
  6. Compile the source code.
  7. Press enter to execute your program. 


Inside this class declare the main method which must throws Exception. After that follow the simple steps find the version:

  1. Makes two object of  PdfReader to read the files.
  2. Create object of  PdfCopyFields to create new pdf file where we copy two pdf files.
  3. add the two pdf into copy object by using addDocument() method.
  4.  close the copy object

The code of the program is given below:

import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfReader;
public class Concatenate2PDF {
public static void main(String[] args)throws Exception {
System.out.println("Concatenate Two PDF"); 
PdfReader reader1 = new PdfReader("1PDF.pdf");
PdfReader reader2 = new PdfReader("2PDF.pdf");
PdfCopyFields copy =
new PdfCopyFields(new FileOutputStream("concatenatedPDF.pdf"));
copy.addDocument(reader1);
copy.addDocument(reader2);
copy.close();
}
}

Download file1 example.

Download file2 example.

The output of the program is given below:

Download this example.