FPDF / FPDI addPage() Orientation

mmackh picture mmackh · Aug 29, 2012 · Viewed 26.4k times · Source

I'm using the following code to add a new page to my existing PDF document and save it.

require('addons/fpdf.php');
require('addons/fpdi.php');

$pdf = new FPDI();                      
$pagecount = $pdf->setSourceFile($orgpdfpath);
for($i = 1; $i <=  $pagecount; $i++){
    $pdf->addPage();
    $tplidx = $pdf->importPage($i);
    $pdf->useTemplate($tplidx);
}
$pdf->addPage($pdforientation);
$pdf->Image($imgpath,$pdfxaxis,$pdfyaxis,$pdfwith,$pdfheight);

$pdf->Output($orgpdfpath,'F'); 

It works fine if I have a document that is A4, Page 1: portrait, Page 2: portrait, Page 3: portrait, etc.

It also works if I add a landscape A4 Page. However, after I have added a landscape page and try to add a portrait, the landscape is shifted back to a portrait and the whole formatting of the document breaks.

I suspect that this has to do something with addPage() inside the loop. Why does does it not rotate appropriately when applying ->useTemplate?

Answer

mmackh picture mmackh · Aug 30, 2012

I oversaw that there was a function called ->getTemplateSize(). Here's a working snippet:

$pdf = new FPDI();                      
$pagecount = $pdf->setSourceFile($orgpdfpath);
for($i = 1; $i <=  $pagecount; $i++){

    $tplidx = $pdf->importPage($i);
    $specs = $pdf->getTemplateSize($tplidx);
    $pdf->addPage($specs['h'] > $specs['w'] ? 'P' : 'L');
    $pdf->useTemplate($tplidx);
}

$pdf->addPage($pdforientation);
$pdf->Image($imgpath,$pdfxaxis,$pdfyaxis,$pdfwith,$pdfheight);

$pdf->Output($orgpdfpath,'F');