Home > Java Core > Java I/O > Merge PDF Files in Java Using iText API

Merge PDF Files in Java Using iText API


Java programme to merge different PDF files. This uses the iText API to read and merge PDF files

What is iText?
iText is a library that allows you to create and manipulate PDF documents. It enables developers looking to enhance web and other applications with dynamic PDF document generation and/or manipulation. You can create PDF documents from scratch with data from database, an XML file, or any other data source.

Steps to follow –

1. Download iText-5.0.4.jar file.
2. Read the input PDF files using java.io.FileInputStream.
3. Create a list of input PDF files.
4. Iterate over the list and for every PDF, using com.itextpdf.text.pdf.PdfReader import all the pages and add them to the output PDf file.
5. Add these import PDF files using com.itextpdf.text.pdf.PdfWriter.

package com.jkoder.java.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class MergePdf {
    public static void main(String[] args) {
        List list = new ArrayList();
        try {
            //input source pdf files
            list.add(new FileInputStream(new File("/opt/dev/input-files1.pdf")));
            list.add(new FileInputStream(new File("/opt/dev/input-files2.pdf")));

            //output pdf files
            OutputStream out = new FileOutputStream(new File("/opt/dev/result.pdf"));

            mergeFiles(list, out);

        } catch (FileNotFoundException e) {
        } catch (DocumentException e) {
        } catch (IOException e) {

	 * Merge pdf files, iterate over the input files list and then import pages
	 * from every files and add in the output pdf file.
	 * @param list
	 * @param outputStream
	 * @throws DocumentException
	 * @throws IOException
    public static void mergeFiles(List list, OutputStream outputStream)
            throws DocumentException, IOException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        PdfContentByte cb = writer.getDirectContent();
        for (InputStream in : list) {
            PdfReader reader = new PdfReader(in);
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                PdfImportedPage page = writer.getImportedPage(reader, i);
                cb.addTemplate(page, 0, 0);