Question

I'm using the "Form Filling" script from fpdf.org to fill some fields on a PDF Form I created. This appears to work properly.

I want the resulting PDF form to be flattened so users can not edit the form fields. I'm using PDFTK for that. However, when I try to flatten the PDF, I get a PDF with the form fields empty.

Any suggestions on how to get the PDF flattened (using PHP) would be appreciated. Thanks!

Here's my code:

<?php
require('fpdm.php');
$fields = array("Name" => "John Doe", 
                "Address" => "123 White Lane", 
                "Age" => "30", 
                "Phone" => "123-1234");
$pdf = new FPDM("templates/Test.pdf");
$pdf->Load($fields, true);
$pdf->Merge();
$pdf->Output("cache/Filled1.pdf","F");

exec("pdftk cache/Filled1.pdf output cache/Filled1Flat.pdf flatten");
?>

Download original Test.pdf file: Test.pdf

Download Filled1.pdf file (displays pdf form correctly with data visible): Filled1.pdf

Download Filled1Flat.pdf file (displays flattened pdf form with no form data visible): Filled1Flat.pdf

Was it helpful?

Solution

Blatant self promotion: Try my php-pdftk package. If you have pdftk installed, it's very easy to use.

composer require mikehaertl/php-pdftk

<?php
use mikehaertl/pdftk/Pdf;

$pdf = new Pdf('form.pdf');
// Fill in UTF-8 compliant form data!
$pdf->fillForm(array('name' => 'Any char: ÄÖÜ'))
    ->saveAs('filled.pdf');

// Alternatively: Send to browser for download...
$pdf->send('filled.pdf');

// ... or inline display
$pdf->send();

OTHER TIPS

I was able to find another process to fill a PDF form and then flatten it. I still don't know why using the "Form Filling" script from fpdf.org did not work.

I followed the steps outlined here:

1) Get the field names if they are not already known

exec("pdftk templates/Test.pdf dump_data_fields >cache/testfields.txt");

2) Create a FDF file with the field names and field values and save it as Test.fdf

%FDF-1.2
1 0 obj<</FDF<< /Fields[
<</T(Name)/V(John Doe)>>
<</T(Address)/V(123 White Lane)>>
<</T(Age)/V(30)>>
<</T(Phone)/V(123-1234)>>
] >> >>
endobj
trailer
<</Root 1 0 R>>
%%EOF

3) Then fill the form and flatten it

exec("pdftk templates/Test.pdf fill_form templates/Test.fdf output cache/FilledFDF.pdf flatten");

Download resulting PDF (filled and flattened): FilledPDF.pdf

With Dhek PDF template editor, there is a PHP snippet to fill data into an existing PDF using FPDF/FPDI, according JSON mappings (to know where to put texts/checkboxes). https://github.com/applicius/dhek

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top