Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fpdi crop the pdf page?

Tags:

php

fpdf

fpdi

So, I'm using fpdi, version 1.2 to add some little mark to every page in my document. Here is my code:

public static function markPdf($file, $text){
    define('FPDF_FONTPATH','font/');
    require_once('fpdi/fpdf.php');
    require_once('fpdi/fpdi.php');
    try{
        $pdf = new FPDI();
        $pagecount = $pdf->setSourceFile($file);
        for($i = 1 ; $i <= $pagecount ; $i++){
            $tpl  = $pdf->importPage($i);
            $size = $pdf->getTemplateSize($tpl);

            // Here you can see that I'm setting orientation for every single page,
            // depending on the orientation of the original page
            $orientation = $size['h'] > $size['w'] ? 'P':'L';
            $pdf->AddPage($orientation);
            $pdf->useTemplate($tpl);

            $pdf->SetXY(5, 5);
            $pdf->SetTextColor(150);
            $pdf->SetFont('Arial','',8);
            $pdf->Cell(0,0,$text,0,1,'R');
        }
        $pdf->Output($file, "F");
    }catch(Exception $e){
        Logger::log("Exception during marking occurred");
        return false;
    }
    return true;
}

And everything works just fine, except for one little issue: when I have a document with first page in landscape orientation, all pages in generated document are cropped from the bottom and right (if the first page is in portrait mode, everything goes just fine, even if following pages are in landscape mode). The question is obvious: what's wrong with this function?

like image 804
aga Avatar asked Dec 15 '22 19:12

aga


1 Answers

The last argument to useTemplate() specifies whether to adjust page size. It defaults to false, but we want it to be true.

Change this call:

$pdf->useTemplate($tpl);

to (for older fpdf versions):

$pdf->useTemplate($tpl, null, null, $size['w'], $size['h'], true);

or (for newer fpdf versions):

$pdf->useTemplate($tpl, null, null, $size['width'], $size['height'], true);

Consider updating all fpdf-related libraries (fpdf, fpdf_tpl and fpdi) to the most recent versions - that's important, too.

P.S.: When pushing new version of fpdi on testing server, I found that it doesn't work with relatively old versions of PHP interpreter - it does work with version 5.3.10, but it can't work with 5.3.2 or older. So, make sure that you have an up-to-date PHP version too.

like image 63
aga Avatar answered Dec 26 '22 10:12

aga