Search code examples
phppdffpdf

Generating a PDF with sequential order images FPDF


I'm trying to generate a pdf with some images using PhP FPdf. I need 4 (four) images per page and 2 (two) images per row. The documentation seems to be pretty simple but I still don't get why it's not working. First time working with this library, so sorry if I made some newbe mistake. If anyone could suggest me a better way to do I will appreciate. Here's my code.

$imagesPerPage = 1;
$imagesPerRow = 0;

    if ($itens !== false) {
        //Add a page if there's at least a single image
        $pdf->AddPage();
        foreach ($itens as $item) {
            //if more than 4 images will generate another page
            if($imagesPerPage > 4){
                $pdf->AddPage();
                $imagesPerPage = 1;
            }

            //Set image in their cordinates into the pdf file
            $pdf->Image($item, $pdf->GetX(), $pdf->GetY(), 0);
            $imagesPerRow ++;

            //Put side by side or if the row is complete put bellow
            if($imagesPerRow === 1){
                $pdf->Cell(80, 0, "", 0, 0);            
            }else{
                $pdf->Cell(80, 0, "", 0, 2);
                $imagesPerRow = 0;
            }
            $imagesPerPage ++;
        }
    }

And heres the output I get...

enter image description here


Solution

  • When you set the new row you can use $pdf->SetXY(); to reset the location of the next row.

    $imagesPerPage = 1;
    $imagesPerRow = 0;
    if ($itens !== false) {
        //Add a page if there's at least a single image
        $pdf->AddPage();
        foreach ($itens as $item) {
            //if more than 4 images will generate another page
            if($imagesPerPage > 4){
                $pdf->AddPage();
                $imagesPerPage = 1;
            }
            //Set image in their cordinates into the pdf file
            $pdf->Image($item, $pdf->GetX(), $pdf->GetY(), 0);
            $imagesPerRow ++;
            //Put side by side or if the row is complete put bellow
            if($imagesPerRow === 1){
                $pdf->Cell(80, 0, "", 0, 0);            
            }else{
                $pdf->SetXY(15, 0);
                $pdf->Cell(80, 0, "", 0, 2);
                $imagesPerRow = 0;
            }
            $imagesPerPage ++;
        }
    }