Monday, September 19, 2011

Using Java, iText fill Abode LiveCycle Designer Form

my project need get data from database and fill PDF Form created by using Adobe LiveCycle designer ES2.

I do it by following step.

1. first, create a XML schema, which contains all the field used in the form.
2. open Adobe LiveCycle, click 'file', then select 'New...', and follow screen instruction to create a new form.
3. click 'File', then click 'New Data Connection...', then give it a name, and choice 'XML Schema', then following screen instruction to import the XML schema.
4. You can drag the data tree from the Data View panel to form. form consists of fields that are organized in subforms, click subforms, select 'Object', then click 'Subform' tab, set 'Content' to 'Flow', and check 'Allow page break'.

5. then select 'request' in data panel, then select 'Object' , then click 'Subform' tab, set 'Content' to 'Position', and check 'Allow page break'.

6. arrange all the fields as you need. save the PDF form.

to get data and fill form, we use Java language and iText API.

1. we get data from data and write to a XML file, the xml file should follow the schema.

 DocumentBuilderFactory domFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

   Document newDoc = domBuilder.newDocument();
   Element rootElement = newDoc.createElement("requests");
   newDoc.appendChild(rootElement);


...add other element.....  

 // write to file
   TransformerFactory tranFactory = TransformerFactory.newInstance();
   Transformer aTransformer = tranFactory.newTransformer();
   Source src = new DOMSource(newDoc);
   Result dest = new StreamResult(new File(destname));
   aTransformer.transform(src, dest);


2. using iText to fill form.
// src is the PDF form name,
// xml is the xml file name created last step,
// dest is the output PDF file name

public   void manipulatePdf(String src, String xml, String dest)
   throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   PdfStamper stamper =
   new PdfStamper(reader, new FileOutputStream(dest));
   AcroFields form = stamper.getAcroFields();
   XfaForm xfa = form.getXfa();
   xfa.fillXfaForm(new FileInputStream(xml));
   stamper.close();
   }



other things,

1. as we don't want user fill the form, I set all the field in the PDF form to 'Read only', to do it, in LiveCycle, select the field, click 'Object', then click 'Value', then select 'Read only' as type.