0
votes

I am using FPDF http://www.fpdf.org/ and FPDI http://www.setasign.com/products/fpdi/about/

I have a 2 page pdf file. I need to import the first page to a new pdf and add two texts on that first page. Then I need to duplicate that page so that the resulting pdf may contain two pages of same content.

The code I am using is

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");

This works fine and I am getting the first page of existing pdf imported to the new pdf and is getting modified, but I am not sure how can I duplicate this modified page without duplicating the above codes. Any idea how to do it ?

1

1 Answers

0
votes

Generally you should understand that you do NOT modify a PDF document with FPDI.

You could put your code into a simple loop to get the needed result:

$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");

Another solution could be using the template feature of FPDF_TPL (part of 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");