这很笨重,但它完成了工作:使用 createXFDF.php,然后使用 PDFTK 两次。确保您的模板 pdf 在 Adobe Reader 中具有扩展功能。使用您将用于填充 PDF 的数据创建一个 XFDF 文件 - 请记住,pdf 中的字段名称必须与 xfdf 中的字段名称匹配。数据是字段名称、字段值的数组。将 PDFTK 与模板 pdf 和 XFDF 一起使用以创建新的中间 PDF。不要使用 FLATTEN - 这将删除可编辑性。现在将 PDFTK cat 与新的中间 PDF 一起使用来创建最终 PDF - 它以某种方式摆脱了 Adobe 数字签名(在填充 pdftk 后保持 pdf 表单可编辑- 请参阅 Marco 的答案)。
示例代码:
$data = array();
$field_name = "account_directory";
$field_value = "john_smith";
$data[$field_name] = $field_value;
/* Make $data as big as you need with as many field names/values
as you need to populate your pdf */
$pdf_template_url = 'http://yoursite.com/yourpath/yourtemplate.pdf';
include 'createXFDF.php';
$xfdf = createXFDF( $pdf_template_url, $data );
/* Set up the temporary file name for xfdf */
$filename = "temp_file.xfdf";
/* Create and write the XFDF for this application */
$directory = $_SERVER['DOCUMENT_ROOT']."/path_to_temp_files/";
$xfdf_file_path = $directory.$filename ; /* needed for PDFTK */
// Open the temp xfdf file and erase the contents if any
$fp = fopen($directory.$filename, "w");
// Write the data to the file
fwrite($fp, $xfdf);
// Close the xfdf file
fclose($fp);
/* Write the pdf for this application - Temporary, then Final */
$pdf_template_path = '/yourpath/yourtemplate.pdf';
$pdftk = '/path/to/pdftk'; /* location of PDFTK */
$temp_pdf_file_path = substr( $xfdf_file_path, 0, -4 ) . 'pdf';
$command = "$pdftk $pdf_template_path fill_form $xfdf_file_path output $temp_pdf_file_path";
/* Note that the created file is NOT flattened so that recipient
can edit form - but this is not enough to allow edit with
Adobe Reader: will also need to remove the signature with PDFTK cat */
exec( $command, $output, $ret );
/* Workaround to get editable final pdf */
$pdf_path_final = $directory. "your_final_filename.pdf" ;
$command2 = "$pdftk $temp_pdf_file_path cat output $pdf_path_final";
exec( $command2, $output2, $ret2 );
/* Your pdf is now saved
/* Remember to UNLINK any files you don't want to save - the .xfdf and the temporary pdf */