- Back to Home »
- Merging PDFs while retaining the fill able forms inside them
Posted by : Unknown
Sunday, January 15, 2012
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.
The iText jar can be downloaded here
Thanks.
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.
Hi this article is very helpful, I've learned so much! I've seen this website pdffiller.com and this service allows you to easily and effectively edit, upload or download fillable PDF forms. I find it very useful, this is the form I used (http://goo.gl/Hm9Knz). You can fill out PDF form, save it, fax it, and email it. You might want to try it.
ReplyDelete