Wednesday, September 06, 2017

Merge PDF files using iText 5

This is an example code for a simple PDF merge using iText 5. We use three InputStreams in a List as input and merged file is written to the file system.
package com.aoj.pdf;

import java.io.FileInputStream;
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.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;

public class ItextPdfMerge {

 public static void main(String[] args) {
  List<InputStream> pdfs = new ArrayList<InputStream>();
  try (FileInputStream fis1 = new FileInputStream("c:\\test\\1.pdf");
    FileInputStream fis2 = new FileInputStream("c:\\test\\2.pdf");
    FileInputStream fis3 = new FileInputStream("c:\\test\\3.pdf");) {
   pdfs.add(fis1);
   pdfs.add(fis2);
   pdfs.add(fis3);
   OutputStream output = new FileOutputStream("c:\\test\\merge.pdf");

   // Merge PDF files.
   mergePdfs(pdfs, output);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void mergePdfs(List<InputStream> streamOfPDFFiles, OutputStream outputStream) {
  // Create Document object with PageSize set to Letter.
  Document document = new Document(PageSize.LETTER);

  try {
   // Open PdfCopy for to copy the merged document into outputStream
   PdfCopy copy = new PdfCopy(document, outputStream);

   document.open();

   for (InputStream file : streamOfPDFFiles) {
    // Create Reader for each input stream
    PdfReader reader = new PdfReader(file);

    // Merge each pdf into merged document represented by copy
    copy.addDocument(reader);
   }
   outputStream.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (document.isOpen())
    document.close();
   try {
    if (outputStream != null)
     outputStream.close();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   }
  }
 }

}
Following is the gradle build file used to run this example.
apply plugin:'application'
mainClassName = "com.aoj.pdf.ItextPdfMerge"
applicationName = 'java-pdf-examples'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.12'

}

No comments:

Post a Comment

Popular Posts