首先,我知道以前有人问过这个问题。但是,对于这个复杂的问题,我想出了自己的解决方案。我是来征求意见的,看看有没有可以改进的地方。此解决方案假定 pdf 已包含可填写字段并生成模板文件以供重复使用(生成一次,多次填写)。
//explicit path to pdftk (if not in your environment PATH)
$pdftk = '/opt/pdflabs/pdftk/bin/pdftk';
//Step 1
//Specify the target pdf
$pdfFile = 'example.pdf';
$fdfFile = substr_replace($pdfFile , 'fdf', strrpos($pdfFile , '.') +1); //same name, switch extension to fdf
$fdfTemplateFile = substr($fdfFile, 0, strrpos($fdfFile, '.')) . '_template.fdf';
$pdfExampleFile = substr($pdfFile, 0, strrpos($pdfFile, '.')) . '_example.pdf';
//This generates the "FDF" file as a sample using Adobe's format with a key/value pair entry for each field
passthru($pdftk . ' ' . $pdfFile . ' generate_fdf output ' . $fdfFile . ' 2> generate_fdf.log');
//Step 2
//Using the newly created fdf file, we need to scan through the file for "/V (þÿ)" which is
//Adobe's default empty value (note: at least in my experience). We want to scan through
//and replace them with dummy values. I'm going to use numeric values, but you could also pull
//the /T (þÿ F I E L D _ N A M E). The keys will need to be massaged to format correctly as a
//key, but nevertheless it should work
function field_replace($matches)
{
static $n = 0;
++$n;
return '/V (:Field' . $n . ':)';
}
$fdfContents = file_get_contents($fdfFile);
$fdfReplacedContents = preg_replace_callback('|\/V \(.+\)|', 'field_replace', $fdfContents);
file_put_contents($fdfTemplateFile, $fdfReplacedContents);
//Step 3
//To generate an example pdf in order to examine which fields correspond to which values,
//use pdftk to combine the fdf file with the original pdf to fill it with the dummy values
//that we generated
passthru($pdftk . ' ' . $pdfFile . ' fill_form ' . $fdfTemplateFile . ' output ' . $pdfExampleFile . ' 2> fill_form.log');
//You should now have a working example file with which you can map key/value pairs using an array
//and str_replace (or preg_replace). Once you have this template fdf file and the original pdf, all you
//need to do is load the template fdf into memory, replace all of the fields (including blank values to eliminate)
//the dummy if there is nothing to output), save to a temporary fdf file, then use pdftk's fill_form
//function to generate the new pdf with your values.
?>