How to fill PDF form in php

Sohail picture Sohail · Feb 4, 2012 · Viewed 56.2k times · Source

I have many PDF forms, I would need to fill them each in php with the data I already have.

Here is just a sample PDF form , I want to fill this form using php. The data I already have in DB. I just want to fill this form and save it.

I am working in PHP Zend Framework.

All I want is when I would download those forms from my site, it would pre-fill all the fields in the pdf form with the information I already have.

Please help me.

Answer

Richard Ayotte picture Richard Ayotte · Feb 4, 2012

Calling pdftk is a nice way to accomplish this. I'll assume that you know how to execute an external program and leave that out.

First, create an FDF file from your PDF.

pdftk form.pdf generate_fdf output data.fdf

You can now use that as template. The sample that you provided looks like this:

%FDF-1.2
%<E2><E3><CF><D3>
1 0 obj 
<<
/FDF 
<<
/Fields [
<<
/V ()
/T (Date)
>> 
<<
/V /
/T (CheckBox2)
>> 
<<
/V /
/T (CheckBox3)
>> 
<<
/V /
/T (CheckBox4)
>> 
<<
/V /
/T (CheckBox5)
>> 
<<
/V ()
/T (Your_Last_Name)
>> 
<<
/V ()
/T (Your_First_Name)
>> 
<<
/V /
/T (CheckBox1)
>>]
>>
>>
endobj 
trailer

<<
/Root 1 0 R
>>
%%EOF

The fields are lines that start with /V (). Enter your desired values into those fields. For example:

%FDF-1.2
%<E2><E3><CF><D3>
1 0 obj 
<<
/FDF 
<<
/Fields [
<<
/V (February 4, 2012)
/T (Date)
...

Finally, merge the FDF with the PDF. Execute the command:

pdftk form.pdf fill_form data.fdf output form_with_data.pdf

If you don't need to keep the FDF and generated PDF files, you can simply pipe the data via stdin and stdout instead of using temp files.