具有多页的FPDI

hit*_*202 4 html php pdf fpdf fpdi

我是PHP的新手,在插入多个页面时使用FPDI有点困难.

我有一个.pdf文件,包含3页.我最终将第1页保存为3中的单独页面并且与我的代码一起使用,但这是因为我的代码仅适用于1页.当我将其更改回3页文件时,它会给我一个内部服务器错误.

这是我正在使用的代码:

<?php

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

// initiate FPDI
$pdf = new FPDI();

// add a page
$pdf->AddPage();

// set the source file
$pdf->setSourceFile("apps/Par.pdf");

// import page 1
$tplIdx = $pdf->importPage(1);

// use the imported page and place it at point 10,10 with a width of 100 mm
$pdf->useTemplate($tplIdx, null, null, 0, 0, true);

// font and color selection
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(200, 0, 0);

// now write some text above the imported page
$pdf->SetXY(40, 83);
$pdf->Write(2, 'THIS IS JUST A TEST');


$pdf->Output();
Run Code Online (Sandbox Code Playgroud)

我不知道如何将此代码转换为能够查看所有3个页面.请帮助我谁谁可以.

Jan*_*bon 17

setSourceFile()方法将返回你设置文档的页数.只需遍历此页面并逐页导入即可.所有页面的示例如下所示:

<?php
require_once('prog/fpdf.php');
require_once('prog/fpdi.php');

// initiate FPDI
$pdf = new FPDI();

// set the source file
$pageCount = $pdf->setSourceFile("apps/Par.pdf");

for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
    $tplIdx = $pdf->importPage($pageNo);

    // add a page
    $pdf->AddPage();
    $pdf->useTemplate($tplIdx, null, null, 0, 0, true);

    // font and color selection
    $pdf->SetFont('Helvetica');
    $pdf->SetTextColor(200, 0, 0);

    // now write some text above the imported page
    $pdf->SetXY(40, 83);
    $pdf->Write(2, 'THIS IS JUST A TEST');
}

$pdf->Output();
Run Code Online (Sandbox Code Playgroud)

关于"内部服务器",您应该启用错误报告:

error_reporting(E_ALL);
ini_set('display_errors', 1);
Run Code Online (Sandbox Code Playgroud)

...或者只是检查您的PHP错误日志以获取详细信息.

  • 更新:在最新版本的 FPDI (2.2) 上,`useTemplate()` 的参数顺序发生了变化。使用:`$pdf-&gt;useTemplate($tplIdx, 0, 0, null, null, true);` (2认同)

小智 6

这个对我有用:

<?php

require_once('fpdf/fpdf.php');
require_once('fpdi/src/autoload.php');

use \setasign\Fpdi\Fpdi;

$pdf = new FPDI();
// get the page count
$pageCount = $pdf->setSourceFile('pdf_file.pdf');
// 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[0] > $size[1]) {
        $pdf->AddPage('L', array($size[0], $size[1]));
    } else {
        $pdf->AddPage('P', array($size[0], $size[1]));
    }

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

    $pdf->SetFont('Helvetica');
    $pdf->SetXY(5, 5);
    $pdf->Write(8, 'A complete document imported with FPDI');
}

$pdf->Output();
Run Code Online (Sandbox Code Playgroud)

将 array($size['w'], $size['h']) 更改为 array($size[0], $size[1])