无法使用 FPDI 编辑现有的 PDF 文件

Can't edit a existing PDF file with FPDI

我正在尝试学习如何使用 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, 0, 0, 0, 0, true); 
      $this->pdf->SetFont('Arial', '', '13'); 
      $this->pdf->SetTextColor(0,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 and extracted it in my hosting file server. Then I downloaded FPDI from setasign.com 网站下载了 FPDF .zip 文件,并将此 .zip 文件上传到我的托管商在线网络服务器。然后我将它解压缩到同一个 fpdf 文件夹中。 (我的服务器启用了 zlib 扩展)。

一个。 FPDI 下载

https://github.com/Setasign/FPDI 下载 fpdi 后,请使用以下命令启动 fpdi:

require_once 'FPDI-master/src/autoload.php';
require_once('FPDI-master/src/fpdi.php');


以下是我过去使用过的完整示例供您参考(我使用过TCPDF,但我已改为使用fpdf):

乙。测试 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文件link:

http://www.createchhk.com/SO/pdfpack_20June2021.zip

之后,将文件解压缩并上传到您的网络服务器PHP文件夹,然后使用浏览器运行 testgen.php查看效果。 (php会在原ok.pdf文件的每一页上添加文字Appendix 1(new),然后下载文件)

C。处理加密 PDF 时出现问题

最后但同样重要的是,请注意 FPDI 不支持导入加密的 PDF 文档 请参阅以下内容 link:

https://www.setasign.com/support/faq/fpdi/can-fpdi-import-encrypted-pdf-documents/

根据我的经验,要处理加密的pdf,您可以使用类似pdf995的东西来“打印”加密的pdf以生成正常的pdf,然后后者的pdf可以由FPDI处理。