Search code examples
phpexportfpdf

FPDF - Define page for position XY


I can not define which pages to put my values ​​on with FPDF, SetXY () and $ pdf-> Write

I have a 5-page pdf template that I import, then export and I would like to place variables in separate positions before exporting this file.

ex: How to put the text 'toto' on page 3 of my PDF, or 'titi' on page 5?

Thanks for your help

$pdf = new FPDI('P', 'cm', 'A4');
$pdf->SetFont('Arial','',10); 
$file_name = "export_test.pdf"; 
$pageCount = $pdf->setSourceFile("exportPDF/exportRapo.pdf");

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

$pdf->SetXY(20, 20);
$pdf->Write(0, 'Text de test');

header("Content-type:application/pdf");
header('Content-Length: '.filesize($file_name));
header('Content-Disposition: attachment; filename="' .$file_name. '"');

readfile($file_name);

Solution

  • for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
        $tplIdx = $pdf->importPage($pageNo);
        $pdf->AddPage();
    
        if($pageNo == 1)
        { 
          $pdf->SetXY(20, 20);
          $pdf->Write(0, 'Toto');
        }
    
        if($pageNo == 2)
        {
           $pdf->SetXY(10, 20);
           $pdf->Write(0, 'Titi');
        }
        ..........
        ..........
        $pdf->useTemplate($tplIdx);
    }
    

    According to your current code, this seems to be a way. This seems a little naive, but if somehow you can figure the content for page according to the page no, it would be easier/efficient, rather than putting multiple if condditons for each page.