使用 PHP/FPDI 合并 PDF 文件

pge*_*e70 3 php pdf pdf-generation fpdi

我正在尝试使用FPDI合并两个文件 ,但得到的错误是:“TCPDF 错误:文件已加密!”,但是,文件未加密,至少文件是可打印、可查看等,并且不需要密码。

我想合并两个文件:

http://www.nps.org.au/__data/cmi_pdfs/CMI7412.pdf http://www.nps.org.au/__data/cmi_pdfs/CMI6656.pdf

将文件复制到服务器并将文件名存储在具有绝对文件路径的数组($files)中后,我的代码是:

if (count ($files) > 0 )
{
    $pdf = new FPDI();
    $pdf->setPrintHeader(FALSE);
    $pdf->setPrintFooter(FALSE);
    foreach ($files as $file)
    {
        for ($i = 0; $i < count($files); $i++ )
        {
            $pagecount = $pdf->setSourceFile($files[$i]);
            for($j = 0; $j < $pagecount ; $j++)
            {
                $tplidx = $pdf->importPage(($j +1), '/MediaBox');
                $specs = $pdf->getTemplateSize($tplidx);
                if ( $specs['h'] > $specs['w'] )
                {
                    $orientation = 'P';
                }
                else
                {
                    $orientation = 'L';
                }
                $pdf->addPage($orientation,'A4');
                $pdf->useTemplate($tplidx, 0, 0, 0, 0, TRUE);
            }
        }
        $output = $pdf->Output('', 'S');
        foreach ( $files as $file )
        {
            delete_file($file);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我还尝试使用 Ghostscript 合并文件,但没有成功。我尝试了 acrobat pro,它需要一个文件的密码,但当我使用 mac 预览时,我导出了该文件,并且能够使用 acrobat 合并它,没有任何问题。ie mac 预览版毫无问题地删除了保护。那么,文件 CMI7412.pdf 停止合并但不导出、查看、打印是怎么回事?我该如何解决它?

小智 5

我已经尝试过类似的问题并且效果很好,请尝试一下。它可以处理 PDF 之间的不同方向。

    // array to hold list of PDF files to be merged
    $files = array("a.pdf", "b.pdf", "c.pdf");
    $pageCount = 0;
    // initiate FPDI
    $pdf = new FPDI();

    // iterate through the files
    foreach ($files AS $file) {
        // get the page count
        $pageCount = $pdf->setSourceFile($file);
        // iterate through all pages
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            // import a page
            $templateId = $pdf->importPage($pageNo);
            // get the size of the imported page
            $size = $pdf->getTemplateSize($templateId);

            // create a page (landscape or portrait depending on the imported page size)
            if ($size['w'] > $size['h']) {
                $pdf->AddPage('L', array($size['w'], $size['h']));
            } else {
                $pdf->AddPage('P', array($size['w'], $size['h']));
            }

            // use the imported page
            $pdf->useTemplate($templateId);

            $pdf->SetFont('Helvetica');
            $pdf->SetXY(5, 5);
            $pdf->Write(8, 'Generated by FPDI');
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • `getTemplateSize` 已更改。它返回“width”和“height”,而不是“w”和“h”,并且现在还返回“orientation”,因此您不需要检查宽度是否更大。只需使用 `$pdf-&gt;AddPage($size['orientation'], array($size['width'], $size['height']));` (2认同)