PHP -如何设置PDF文件中字段的值,然后保存


PHP - How to set the value of a field inside a PDF file, then save?

我正在构建一个应用程序,以帮助协助设置我的网站的PDF表单。我有自己使用的标准表单,但每次将标准表单添加到新帐户时,都需要更改PDF文件中的一些隐藏字段。

使用PHP如何更新PDF文件中字段的值,然后保存该文件?我假设我需要使用某种PHP-PDF库,所以一个免费的会很有帮助。

(这些表单已经使用adobeacrobat编写了表单字段,并且具有唯一的字段名称。所有我需要做的是更新一对现有的字段使用字段名作为一个键)

,

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"

这是笨拙的,但它完成了工作:使用createXFDF.php,然后使用PDFTK两次。确保您的pdf模板在adobereader中具有扩展功能。使用将用于填充PDF的数据创建一个XFDF文件—请记住,PDF中的字段名必须与XFDF中的字段名匹配。数据是字段名,字段值的数组。使用PDFTK与模板pdf和XFDF一起创建一个新的中间pdf。不要使用FLATTEN——那会删除可编辑性。现在使用PDFTK cat与您的新中间PDF创建您的最终PDF -它以某种方式摆脱了Adobe数字签名(保持PDF表单可编辑后填写PDFTK -见马可的回答)。

示例代码:

$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 */