Monday, October 18, 2010

Add Text to an Existing PDF Using PHP

I am finishing up on a project right now that fills out a PDF application for a merchant account. The software helps the user through the application process by asking more targeted questions and filling in fields that are known. In order to do this I had found two PHP libraries that work quite well.

The first is FPDF. It is a free PHP library that allows you to create PDFs. It is not a module or binary code, just a straight up PHP script library. Color me impressed. You can download it at http://www.fpdf.org/

The second bit of code you need is called FPDI. This will import a PDF as a template and allow you to overlay text. It worked quite well for my project as I was taking an existing PDF and filling in fields on top of it. Just like FPDF, it is super easy to install because all it is is a collection of PHP script files. You can download it at http://www.setasign.de/products/pdf-php-solutions/fpdi/

Here is a quick demo by FPDI on how to use these two modules together.

To make it all work I created a flat, PDF version of the template PDF. I removed all of the form fields using Adobe Acrobat. The first run I got an error: "probably uses a compression technique which is not supported". This was easily fixed by saving the PDF as PDF/A using Adobe Acrobat. (Update below.)

If you have any questions, please let me know. I'd be glad to share more of what I learned.

Update (10/22/10): I've learned that saving the PDf as a PDF/A doesn't always solve the error I explained above. What has worked, however, is running Adobe Pre-Flight on the document. If you go to "Advanced" > "Print Production" > "Preflight" and then click on "Analyze and fix", Adobe will work some magic on the document and make it work with FPDI.

Update (1/27/11): FPDI, the free version of the PDF parser, requires the PDF to be version 1.4 or below. To save a PDF in this format, open the document in Adobe Acrobat, click "Save As" and then select the type "PDF, Optimized" then click the "Settings" button and select "Adobe Acrobat 5.0". This will save the PDF in version 1.4, which was last used in Adobe Acrobat 5.0!

3 comments:

Error said...

Hi Eric,
I'm trying to use FPDI and FPDF to do search and replace (text field only) in existing PDF file. Can you give me some ideas (only use PHP)? Thank you.

Eric said...

Sorry, not sure if this is even possible... Any one else know?

Atik Khan said...

Thanks it's helpful. Now i can create pdf file using php.