Archive for January 2012

Merging PDFs while retaining the fill able forms inside them

My previous post was about merging the PDF files into single file using PDFBox, the limitation of that approach was if you had fill able form inside any PDF file it was lost, to over come that issue here is an updated version of the same post using iText library.







import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfReader;

/**
 * Merges the PDF files while retaining the fillable forms within them. It also
 * renames form field (to avoid conflicts) which can have an impact if form is
 * submitted to server but for printing purpose should be OK.
 * 
 * @author Munish Gogna
 * 
 */
public class PDFMerge {
 private static int counter = 0;

 public static void merge(List<InputStream> sourcePDFs,
   OutputStream targetPDF) throws Exception {
  if (sourcePDFs != null && targetPDF != null) {
   PdfCopyFields copy = new PdfCopyFields(targetPDF);

   for (InputStream stream : sourcePDFs) {
    PdfReader pdfReader = new PdfReader(stream);
    renameFields(pdfReader.getAcroFields());
    copy.addDocument(pdfReader);
    stream.close();
   }
   copy.close();
  }
 }

 private static void renameFields(AcroFields fields) {
  Set<String> fieldNames = fields.getFields().keySet();
  String prepend = String.format("_%d.", counter++);

  for (String fieldName : fieldNames) {
   fields.renameField(fieldName, prepend + fieldName);
  }
 }

 public static void main(String[] args) {
  try {
   List<InputStream> pdfs = new ArrayList<InputStream>();
   pdfs
     .add(new URL(
       "http://thewebjockeys.com/TheWebJockeys/Fillable_PDF_Sample_from_TheWebJockeys_vC5.pdf")
       .openStream());
   pdfs
     .add(new URL(
       "http://help.adobe.com/en_US/Acrobat/9.0/Samples/interactiveform_enabled.pdf")
       .openStream());
   OutputStream output = new FileOutputStream("merged.pdf");

   merge(pdfs, output);

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

The iText jar can be downloaded here

Thanks.
Sunday, January 15, 2012
Posted by Munish Gogna

Popular Post

Labels

enums (1) java (2) JAX-RS (1) JPA (1) mysql (1) request 2 (1) RESTful (1) sphinx (1) tomcat (1) web service (2) ws (2)