FPDF 复制修改后的页面



我正在使用 FPDF http://www.fpdf.org/和 FPDI http://www.setasign.com/products/fpdi/about/

我有一个 2 页的 pdf 文件。我需要将第一页导入新的pdf,并在第一页上添加两个文本。然后我需要复制该页面,以便生成的pdf可能包含两个相同内容的页面。

我使用的代码是

require_once ('fpdf/fpdf.php');
require_once ('fpdf/fpdi.php');
$file = "myexistingpdf.pdf";
$pdf = &new FPDI();
$pdf -> AddPage();
$pagecount = $pdf -> setSourceFile($file);
$tpl = $pdf -> importPage(1);
$pdf -> useTemplate($tpl);
$pdf -> SetY(116);
$pdf -> SetX(-300);
$pdf -> SetFont('Times', 'B', 9);
$pdf -> Cell(0, 10, "Hello World", 0, 0, 'C');
$pdf -> SetY(22);
$pdf -> SetX(-358);
$pdf -> SetFont('Times', 'B', 8);
$pdf -> Cell(0, 10, "Date:", 0, 0, 'C');
$pdf -> Output("pdf.pdf", "I");

这工作正常,我正在将现有 pdf 的第一页导入到新的 pdf 中并正在被修改,但我不确定如何在不复制上述代码的情况下复制此修改后的页面。知道怎么做吗?

通常,您应该了解您不会使用 FPDI 修改 PDF 文档。

您可以将代码放入一个简单的循环中以获得所需的结果:

$pdf = new FPDI();
$pagecount = $pdf -> setSourceFile($file);
$tpl = $pdf->importPage(1);
for ($i = 2; $i > 0; $i--) {
    $pdf->AddPage();
    $pdf->useTemplate($tpl);
    $pdf->SetY(116);
    $pdf->SetX(-300);
    $pdf->SetFont('Times', 'B', 9);
    $pdf->Cell(0, 10, "Hello World", 0, 0, 'C');
    $pdf->SetY(22);
    $pdf->SetX(-358);
    $pdf->SetFont('Times', 'B', 8);
    $pdf->Cell(0, 10, "Date:", 0, 0, 'C');
}
$pdf->Output("pdf.pdf", "I");

另一种解决方案可能是使用 FPDF_TPL(FPDI 的一部分)的模板功能:

$pdf = new FPDI();
$pagecount = $pdf -> setSourceFile($file);
$tpl = $pdf->importPage(1);
$pdf->AddPage();
// create the template
$newTpl = $pdf->beginTemplate();
$pdf->useTemplate($tpl);
$pdf->SetY(116);
$pdf->SetX(-300);
$pdf->SetFont('Times', 'B', 9);
$pdf->Cell(0, 10, "Hello World", 0, 0, 'C');
$pdf->SetY(22);
$pdf->SetX(-358);
$pdf->SetFont('Times', 'B', 8);
$pdf->Cell(0, 10, "Date:", 0, 0, 'C');
$pdf->endTemplate();
// now use the template
$pdf->useTemplate($newTpl);
// and again on the next page
$pdf->AddPage();
$pdf->useTemplate($newTpl);
$pdf->Output("pdf.pdf", "I");

最新更新