Wednesday, September 16, 2009

How to Write and Populate XML data into a PDF - Only on the Client.

I am currently on a project where a user will have very limited internet access, and they need the ability to enter form data which in the end, populates a PDF file and writes the PDF to their system (OS). One tends to think the only way to do this is with Java libraries or LiveCycle, but this is not the case. Both xdp and pdfxml are viable solutions.

The end solution I ended up going with is pdfxml. First, you need to install the Adobe Mars plugin for your Adobe Reader or Acrobat (I highly recommend using Reader/Pro version 9+).

In short, you take a PDF form, open it in Acrobat 9 Pro (I used the trial version), and click menu Forms->Add/Edit Fields. Here you can add fields using the field names you chose. Because you installed the Mars plugin for Acrobat 9, you will now see the option in File->Save As for a type "pdfxml". Save it.

Now, in your AIR Flex Builder project, add the pdfxml file to a 'pdfs' directory in your main 'src' directory, so it's included in the AIR file, and load the file like so:

var pdfxmlFile : File = File.applicationDirectory.resolvePath("pdfs/myFile.pdfxml");
mars = new MarsPackage(pdfxmlFile, this); //this being the mxml this code sits on

The MarsPackage class is from the Adobe examples source code. Adobe doesn't explicitly give you the Actionscript to parse out the XML, but I was able to piece it together. I would post the code, but I don't want to step on Adobe's toes since it's 99% their code.

To really understand how PDFXML works, install Adobe's PDFXML Inspector air app. Run the app and click File->Open and open either the pdfxml you created in Acrobat Pro or one of the sample pdfxml files from the Mars website. Click the 'form' node on the tree and then the 'form_data.xdfd' node. You'll see the XML data load to the right. If you don't see any data (fields) for the pdfxml you created, open your pdfxml in Pro, add a blank space or data, re-save it, and then re-open it in the PDFXML Inspector.

From this AIR app, you can udpate the data, and if you re-open the pdfxml in Reader/Pro..you'll see the data. No server needed!!

Note: If you add the fields with the LiveCycle Designer, the data instead is saved as xml...which I have had a lot of inconsistency with opening properly in Reader. Sometimes it works, sometimes it doesn't. Either way, use the 'Edit Fields' in Acrobat Pro and avoid Livecycle Designer and you will be worry free.

No comments: