我正在构建一个应用程序来帮助我为我的网站设置PDF表单。我有自己使用的标准表单,但每次将标准表单添加到新帐户时都需要更改PDF文件中的一些隐藏字段。
使用PHP如何更新PDF文件中字段的值,然后保存文件? 我假设我需要使用某种PHP-PDF库,所以一个免费的将是有用的。
(表单已经使用Adobe Acrobat编写了表单字段,并且具有唯一的字段名称。我需要做的就是使用字段名称作为键更新几个现有字段) < / p>
实施例 -
PDF File Location = www.mysite.com/accounts/john_smith/form.pdf
PDF Field to update (Field Name) = "account_directory"
PDF Field value to be set = "john_smith"
答案 0 :(得分:0)
这很笨重,但它完成了工作: 使用createXFDF.php,然后使用PDFTK两次。 确保您的模板pdf在Adobe Reader中具有扩展功能。 使用将用于填充PDF的数据创建XFDF文件 - 请记住,pdf中的字段名称必须与xfdf中的字段名称匹配。数据是字段名称,字段值的数组。 将PDFTK与模板pdf和XFDF一起使用以创建新的中间PDF。不要使用FLATTEN - 这将删除可编辑性。 现在使用PDFTK cat和你的新中间PDF来创建你的最终PDF - 它以某种方式摆脱了Adobe数字签名(Keep a pdf form editable after filling it with pdftk - 请参阅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 */