Search code examples
phppdfpdftk

Filling PDF form by PHP - PDFtk not working


I have PDF form generated in SAP. There are approximately 30 fields in that form. Some are already filled. While others will fill in by an employee. Here is the sample of that form.

enter image description here

Now I am going to create a php application which can accept data from user and fill in above form and generate that PDF file. I read tutorials of filling PDF form by PDFtk Server Utility. So I download and install this tool in my windows 7. Before creating my PHP application I thought that I have to try to fill the form manually on my PC. So first I dump data fields using following command and try to fill one variable.

pdftk sample.pdf dump_data_fields > fields_names.txt

output :

.
.
FieldType: Text
FieldName: data[0].#pageSet[0].TimeSheet[0].CURRENTWEEK[0]
FieldNameAlt: Week
FieldFlags: 0
FieldValueDefault: 26
FieldJustification: Left
FieldMaxLength: 2
---
FieldType: Text
FieldName: data[0].#pageSet[0].TimeSheet[0].CURRENTYEAR[0]
FieldNameAlt: Year
FieldFlags: 0
FieldValueDefault: 2018
FieldJustification: Left
FieldMaxLength: 4
.
.

Then I create FDF file to fill CURRENTWEEK variable..

%FDF-1.2
%âãÏÓ
1 0 obj 
<<
/FDF 
<<
/Fields [
<</T(data[0].#pageSet[0].TimeSheet[0].CURRENTWEEK[0])/V(80)>>
]
>>
>>
endobj
trailer
<<
/Root 1 0 R
>>
%%EOF

I run this command to generate filled form

pdftk sample.pdf fill_form data.fdf output output.pdf

PDF form doesn't get filled. Still showing original PDF form. Again when I dump fields of newly created form it showing..

---
FieldType: Text
FieldName: data[0].#pageSet[0].TimeSheet[0].CURRENTWEEK[0]
FieldNameAlt: Week
FieldFlags: 0
FieldValue: 80
FieldValueDefault: 26
FieldJustification: Left
FieldMaxLength: 2
---

FieldValue:80 get added but there is no data in form. Showing same 26 value in field. Is there any mistake while creating FDF or running command ?


Solution

  • First u have install pdftk on your server then run this following command

    pdftk path/to/the/form.pdf dump_data_fields > field_names.txt
    

    and you get txt file for your pdf file and it's output like this

    FieldType: Text
    FieldName: data[0].#pageSet[0].TimeSheet[0].KUNNR[0]
    FieldNameAlt: User
    FieldFlags: 1
    FieldValueDefault: 65604
    FieldJustification: Left
    FieldMaxLength: 10
    FieldJustification: Left
    ---
    

    then u use following package for it

    composer require mikehaertl/php-pdftk
    

    then update composer

     use mikehaertl\pdftk\Pdf; 
    // Fill form with data array
        $pdf = new Pdf('path of your pdf');
        $pdf->fillForm([
            'data[0].#pageSet[0].TimeSheet[0].KUNNR[0]'=>'sanjay',
        ])
            ->needAppearances()
            ->saveAs('filled.pdf');
    

    it's work for me.