0

我有两个代码,一个用于编辑已上传的 pdf,第二个用于使用密码保护已上传的 pfd

这是代码片段

1) 用于 pdf 编辑

require_once('fpdf.php');  
require_once('fpdi.php');  

$pdf = new FPDI();  
$filen="upload/json_tutorial.pdf";
$pageCount = $pdf->setSourceFile($filen);  

// iterate through all pages
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
 // import a page
    $tplidx = $pdf->importPage($pageNo);
    $pdf->addPage();  
    $pdf->useTemplate($tplidx, 0, 0, 220,270);  
    $pdf->SetFont('Helvetica');
    $pdf->SetTextColor(0, 0, 255);
    $pdf->SetXY(5, 5);
    $cur_page_no=$pdf->PageNo();
    $min=2;
    $max=10;

if((($pdf->PageNo())>=$min) && (($pdf->PageNo())<=$max))
{
    $author="AuthorName";
    $pdf->Cell(320,10,$author,0,0,'C');
}    
}

$pdf->Output('newpdf.pdf', 'D');

2) 用于密码保护

function pdfEncrypt ($origFile, $password, $destFile)
{

    require_once('FPDI_Protection.php');
    $pdf =& new FPDI_Protection();
    $pagecount = $pdf->setSourceFile($origFile);

    for ($loop = 1; $loop <= $pagecount; $loop++) 
    {
    $tplidx = $pdf->importPage($loop);
    $pdf->addPage();
    $pdf->useTemplate($tplidx);
    }

    $pdf->SetProtection(array(), $password,'');
    $pdf->Output($destFile, 'D');
    return $destFile;
 }
 $password = "pass123";
 $origFile = "json_tutorial.pdf";
 $destFile ="pd_protected.pdf";

 pdfEncrypt($origFile, $password, $destFile );

两个代码都可以正常工作。但是当我尝试将它们结合起来时。它们中的任何一个都无法正常工作,因为代码 1 使用较新的库,而代码 2 使用较旧的库。我尝试使用新库处理代码 2,但给出文件无法加载有点错误。

我已将代码 1 的功能添加到代码 2 中,如下所示:

function pdfEncrypt ($origFile, $password, $destFile)
{
    require_once('FPDI_Protection.php');
    $pdf =& new FPDI_Protection();
    $pagecount = $pdf->setSourceFile($origFile);
    for ($pageNo = 1; $pageNo <= $pagecount; $pageNo++) 
    {
    $tplidx = $pdf->importPage($pageNo);
    $pdf->addPage();  
    $pdf->useTemplate($tplidx, 0, 0, 220,270);  
    $pdf->SetFont('Helvetica');
    $pdf->SetTextColor(0, 155, 255);
    $pdf->SetXY(5, 5);
    $min=2;
    $max=10;

    if((($pdf->PageNo())>=$min) && (($pdf->PageNo())<=$max))
    {
        $author="KomalD";
        $pdf->Cell(320,10,$author,0,0,'C');
    }
    }
    $pdf->SetProtection(array(), $password,'');
    $pdf->Output($destFile, 'D');

    return $destFile;
}
$password = "pass123";
$origFile = "json_tutorial.pdf";
$destFile ="pd_protected.pdf";

pdfEncrypt($origFile, $password, $destFile );

此代码将文件保存为受密码保护的文件,但根本不对其进行编辑。既不给出任何错误或警告。我在做什么错??

请建议。谢谢

4

1 回答 1

2

首先,您应该将所有使用的类更新到它们的当前版本: FPDFFPDI和 FPDI_Protection (参见上一个链接)。

之后,您只需要 require 所需的文件,您的最后一个脚本应该可以按预期工作:

function pdfEncrypt ($origFile, $password, $destFile)
{
    require_once('fpdf.php');
    require_once('fpdi.php');
    require_once('FPDI_Protection.php');
    $pdf = new FPDI_Protection(); // <-- remove the "&"
    $pagecount = $pdf->setSourceFile($origFile);
    ...
于 2014-06-03T06:41:24.273 回答