PDF Form filling with FPDF and then Flatten with PDFTK displays un-filled PDF

user1855093 picture user1855093 · Nov 27, 2012 · Viewed 22.2k times · Source

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

Answer

Michael H&#228;rtl picture Michael Härtl · Jul 11, 2014

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();