How can I flatten a PDF with pre-filled formfields in PHP?

310 Views Asked by At

I need to flatten a pre-filled PDF form before sending it to an external signing service using PHP. I have tried using the php-pdftk library (https://github.com/mikehaertl/php-pdftk), but it did not work for me.

Here's the code I have tried:

<?php

require __DIR__ . '/vendor/autoload.php';

use mikehaertl\pdftk\Pdf;

($pdf = new Pdf('/app/pdf-prefilled.pdf'))->flatten()->saveAs('/app/pdf-flat.pdf');

echo $pdf->getError();

This leads to the following error:

Unhandled Java Exception in create_output():
java.lang.ClassCastException: class pdftk.com.lowagie.text.pdf.PdfString cannot be cast to class pdftk.com.lowagie.text.pdf.PdfDictionary (pdftk.com.lowagie.text.pdf.PdfString and pdftk.com.lowagie.text.pdf.PdfDictionary are in unnamed module of loader 'app')
        at pdftk.com.lowagie.text.pdf.PdfStamperImp.flatFields(PdfStamperImp.java:738)
        at pdftk.com.lowagie.text.pdf.PdfStamperImp.close(PdfStamperImp.java:163)
        at pdftk.com.lowagie.text.pdf.PdfStamperImp.close(PdfStamperImp.java:304)
        at com.gitlab.pdftk_java.filter.create_output_filter(filter.java:424)
        at com.gitlab.pdftk_java.TK_Session.create_output(TK_Session.java:1445)
        at com.gitlab.pdftk_java.pdftk.main_noexit(pdftk.java:192)
        at com.gitlab.pdftk_java.pdftk.main(pdftk.java:163)
There was a problem with pdftk-java. Please report it at
https://gitlab.com/pdftk-java/pdftk/issues
including the message above, the version of pdftk-java (3.2.2), and if possible steps to reproduce the error.Xdebug: [Step Debug] Time-out connecting to debugging clien

I also tried using the tcpdi library (https://github.com/kulbakin/tcpdi), which successfully flattens the PDF but does not retain the pre-filled data. Unfortunately, it also does not support parsing the form fields yet.

<?php

use TCPDI;

$pdf = new TCPDI();
$pagecount = $pdf->setSourceData($data);
for ($i = 1; $i <= $pagecount; $i++) {
    $tplidx = $pdf->importPage($i);
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);
    $pdf->AddPage();
    $pdf->importAnnotations($i);
    $pdf->useTemplate($tplidx);
}
$data = $pdf->Output('', 'S');

Are there any other ways to flatten a pre-filled PDF form in PHP while retaining the pre-filled data? Any help would be greatly appreciated

0

There are 0 best solutions below