问题描述
我正在尝试学习如何使用 PHP 语言使用 FPDF 和 FPDI 编辑 PDF 文件。我有这个 sample PDF file 想要插入一些值。如果我要使用 FPDF 创建 PDF 文件,一切正常。但是,如果我尝试使用 FPDI 编辑现有的 PDF 文件,则会出现以下错误消息:This page isn’t working. Failed to load resource: the server responded with a status of 500 ( ). crbug/1173575,non-JS module files deprecated.
下面显示了用于编辑 PDF 文件的两个程序。第一个有效,第二个失败。
<?PHP
//This program works and create a new PDF file.
require('fpdf.PHP');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
以下用于编辑现有 PDF 文件的程序失败:
<?PHP
require_once('fpdf.PHP');
//This second line of code fails.
require_once('../fpdf183/FPDI/FPDI-2.3.6/src/Fpdi.PHP'); //This path is correct. I have tested it out with a simple echo “hello world”; file.
//I assume I didn’t install fpdi correctly. I have tried replacing /Fpdi.PHP part with autoload.PHP as well.
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile('testfile.pdf');
$tplIdx = $this->pdf->importPage(1); // import page 1
$this->pdf->useTemplate($tplIdx,true);
$this->pdf->SetFont('Arial','','13');
$this->pdf->SetTextColor(0,0);
$this->pdf->SetXY(20,20); //set position in pdf document
$this->pdf->Write(0,'Some texts will go in here');
$this->pdf->Output('newfile.pdf','D');//force the browser to download the output
?>
首先,我从 fpdf.org 下载了 FPDF .zip 文件并将其解压缩到我的托管文件服务器中。然后我从 setasign.com 网站下载了 FPDI 并将这个 .zip 文件上传到我的托管商在线网络服务器。然后我将它解压缩到同一个 fpdf 文件夹中。 (zlib 扩展在我的服务器中启用)。
解决方法
A. FPDI 下载
从 https://github.com/Setasign/FPDI 下载 fpdi 后,请使用以下命令启动 fpdi:
require_once 'FPDI-master/src/autoload.php';
require_once('FPDI-master/src/fpdi.php');
以下是我过去使用过的完整示例供您参考(我使用过 TCPDF,但我已更改为使用 fpdf):
B.测试 PHP:testgen.php
<?php
require_once 'vendor/autoload.php';
//require_once('tcpdf/tcpdf.php');
require_once('fpdf/fpdf.php');
require_once('vendor/setasign/fpdi/fpdi.php');
$pdf = new FPDI();
$pagecount = $pdf->setSourceFile('ok.pdf');
for ($n = 1; $n <= $pagecount; $n++) {
$pdf->AddPage();
$tplIdx = $pdf->importPage($n);
$pdf->useTemplate($tplIdx);
$pdf->SetFont('Helvetica','B',10);
$pdf->SetXY(150,10);
$pdf->Write(0,"Appendix 1(new)");
}
$pdf->Output("output_sample_ken.pdf","D");
?>
为了方便您进一步测试,您可以从以下链接下载 fpdf / fpdi 文件:
http://www.createchhk.com/SO/pdfpack_20June2021.zip
之后,将文件解压并上传到您的网络服务器PHP文件夹,然后使用浏览器运行testgen.php查看效果。 (php会在原Appendix 1(new)
文件的每一页添加文字ok.pdf
,然后下载文件)
C.处理加密 PDF 的问题
最后但并非最不重要的一点,请注意FPDI 不支持导入加密的 PDF 文档,请参阅以下链接:
https://www.setasign.com/support/faq/fpdi/can-fpdi-import-encrypted-pdf-documents/
根据我的经验,要处理加密的pdf,您可以使用pdf995之类的东西来“打印”加密的pdf以生成正常的pdf,然后FPDI可以处理后者。