FPDF / FPDI addPage() Orientation

28,247

Solution 1

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

Solution 2

BTW, if you can't guarantee that all your documents will be A4 (this isn't your problem, but it was my problem that led me to this Q) you can also use the size of your template to set the size of your generated file's pages, by passing the sizes as an array in the second arg:

$pdf->AddPage(
    ( $size['w'] > $size['h'] ) ? 'L' : 'P',
    [ $size['w'], $size['h'] ]
);

Solution 3

Maybe this helps the one or other, if you define den orientation and it won't work in pdf generation. I changed the width and height in landscape mode on AddPage(). Probably this should be done automatically, but in my case in combination with PDFmerger, a wrapper class for fpdf/fpdi, it doesn't.

$fpdi = new FPDI;
$count = $fpdi->setSourceFile($filename);
for($i=1; $i<=$count; $i++) {
  $template = $fpdi->importPage($i);
  $size = $fpdi->getTemplateSize($template);
  $orientation = ($size['h'] > $size['w']) ? 'P' : 'L';
  if ($orientation == "P") {
    $fpdi->AddPage($orientation, array($size['w'], $size['h']));
  } else {
    $fpdi->AddPage($orientation, array($size['h'], $size['w']));
  }
 $fpdi->useTemplate($template);
}
Share:
28,247
mmackh
Author by

mmackh

I release open source code from time to time.

Updated on July 05, 2022

Comments

  • mmackh
    mmackh almost 2 years

    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?