Search code examples
phpfpdf

Detecting when there's space left for only one row and when a new page is added with FPDF


In this project I'm using FPDF to generate PDF files with tables. I managed to get the table structure set but I want to add table head and table footer whenever is needed.

Code:

<?php
function tableTitle($pdf){

    $pdf -> SetFillColor(214, 214, 214);
    $pdf -> Cell(28, 5, utf8_decode('MATRÍCULA'), 1, 0, 'C', 1);
    $pdf -> Cell(106, 5, utf8_decode('NOME'), 1, 0, 'C', 1);
    $pdf -> Cell(28, 5, utf8_decode('CPF'), 1, 0, 'C', 1);
    $pdf -> Cell(28, 5, utf8_decode('MÉDIA'), 1, 0, 'C', 1);
    $pdf -> Ln();
}

function tableBody($pdf, $matricula, $nome, $cpf, $media) {
    
    for ($i=0; $i 100< ; $i++) { 
    //For testing purpose, data input will come later
    
    $pdf -> Cell(28, 5, utf8_decode($matricula), 1, 0, 'C');
    $pdf -> Cell(106, 5, utf8_decode($nome), 1, 0, 'C');
    $pdf -> Cell(28, 5, utf8_decode($cpf), 1, 0, 'C');
    $pdf -> Cell(28, 5, utf8_decode($media), 1, 0, 'C');
    $pdf -> Ln();

    }

}

tableTitle($pdf);
tableBody($pdf, "55555/20", "LOREM IPSUM DOLOR SIT AMET", "xxx.xxx.xxx-xx", 10.00);


$pdf -> Output();
?>

The tableTitle() is function that creates the row that I need to be added.


Solution

  • This is how I detect whether or not a table row is going to spill to the next page:

    if (($ourpdf->GetY() + ($linecount * 5)) > $ourpdf->pagebreak) {  // data won't fit on this page
    
        $ourpdf->AddPage();   // page break
        pcs_Header($ourpdf);  // add the table header
        $fill = true;         // force next row of table to be filled
    
    }  // end of not enough room for the data on this page
    

    And this is the pcs_Header function that is called to output a fresh table header when needed.

    function pcs_Header($ourpdf) {
    
        $ourpdf->SetWidths([43,28,25,20,30,25,13,23]);
        $ourpdf->SetAligns(['C','C','C','C','C','C','C','C']);
        $fill = false;
        $ourpdf->SetFont('','',10);
        $ourpdf->Row(['PCS Name'        ,
                      'PCS ID'          ,
                      'PCS Type'        ,
                      'PCS Risk Rating' ,
                      'Street Address'  ,
                      'City'            ,
                      'Zip'             ,
                      'County'],0,true);
    
    }  // end of the pcs_Header function