I was unable to find a PDF fill method in PHP that I really liked. Instead, I use PHP to generate XFDF, then I use pdftk to insert it into the fillable PDF file. (Note that this code requires your PDF fields to be named.)
Here is an example function for generating XFDF from an associative array:
function forge_xfdf($file,$info,$enc='UTF-8'){ $data='<?xml version="1.0" encoding="'.$enc.'"?>'."\n". '<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">'."\n". '<fields>'."\n"; foreach($info as $field => $val){ $data.='<field name="'.$field.'">'."\n"; if(is_array($val)){ $data.='<</T('.$field.')/V['; foreach($val as $opt) $data.='<value>'.$opt.'</value>'."\n"; }else{ $data.='<value>'.$val.'</value>'."\n"; } $data.='</field>'."\n"; } $data.='</fields>'."\n". '<ids original="'.md5($file).'" modified="'.time().'" />'."\n". '<f href="'.$file.'" />'."\n". '</xfdf>'."\n"; return $data; }
Then I write XFDF to a temporary file.
$empty_form = '/path/to/fillable/pdf/form.pdf' $fdf_filename = tempnam(PDF_TEMP_DIR, 'fdf'); $output_filename = tempnam(PDF_TEMP_DIR, 'pdf'); $fdf_data = forge_xfdf($empty_form, $data, 'UTF-8'); if($fdf_fp = fopen($fdf_fn, 'wb')){ fwrite($fdf_fp, $fdf_data); fclose($fdf_fp); $command = '/usr/local/bin/pdftk "'.$empty_form.'" fill_form "'.$fdf_filename.'" output "'.$output_file.'" dont_ask'; passthru($command); // SEND THE FILE TO THE BROWSER unlink($output_file); unlink($fdf_filename); }
If you want a non-editable PDF, add the word flatten to the command before the word dont_ask .
If you are not attached to filling out a PDF form, you can generate the form in HTML and then use dompdf to convert from HTML to PDF.
Moshe katz
source share