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

Posted

技术标签:

【中文标题】PHP - 如何在 PDF 文件中设置字段的值,然后保存?【英文标题】:PHP - How to set the value of a field inside a PDF file, then save? 【发布时间】:2013-06-18 21:13:39 【问题描述】:

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

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

(表单已经使用 Adob​​e Acrobat 使用表单字段进行编程,并且具有唯一的字段名称。我需要做的就是使用字段名称作为键更新几个现有字段)

例子-

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"

【问题讨论】:

PDF Editing in PHP?的可能重复 不完全。我不是在尝试更改 PDF 文件上的文本,而是在 PDF 上设置表单字段的值。 【参考方案1】:

这很笨重,但可以完成工作: 使用 createXFDF.php 然后使用 PDFTK 两次。 确保您的模板 pdf 在 Adob​​e Reader 中具有扩展功能。 使用您将用于填充 PDF 的数据创建一个 XFDF 文件 - 请记住,pdf 中的字段名称必须与 xfdf 中的字段名称匹配。数据是字段名称、字段值的数组。 将 PDFTK 与模板 pdf 和 XFDF 一起使用以创建新的中间 PDF。不要使用 FLATTEN - 这将删除可编辑性。 现在将 PDFTK cat 与新的中间 PDF 一起使用来创建最终 PDF - 它以某种方式摆脱了 Adob​​e 数字签名(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 */

【讨论】:

以上是关于PHP - 如何在 PDF 文件中设置字段的值,然后保存?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 play 2.4 中的 scala 模板中设置类型列表字段的值?

如何在 JSP 页面中设置我自己的值的字段?

如何在 iframe 中设置 base64 pdf 的文件名?

如何根据文本字段 Material UI 中设置的值将对象设置为状态

PDFBox 设置字段值不起作用

Pydantic:根据其他字段的值在验证器中设置字段 None