FPDF / FPDI addPage() Orientation
Asked Answered
T

3

8

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?

Tattoo answered 29/8, 2012 at 20:13 Comment(0)
T
20

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'); 
Tattoo answered 30/8, 2012 at 7:2 Comment(1)
How about $pdf->addPage($tplidx['orientation']) ?Pantie
I
3

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'] ]
);
Inelegancy answered 5/2, 2016 at 17:32 Comment(0)
C
2

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);
}
Caldeira answered 20/2, 2017 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.