Search code examples
pdffpdf

dynamic fpdf table creation only works on first page


i'm using fpdf for the first time and i've managed to create a function that makes tables in pdf dynamically and adjusts the height of the table rows according to text in the cells. it works a charm on the first page but on all other pages it looks strange, with stray cells and text floating around (how do i attach files to this?).

my code is as such:

$pdf=new PDF();
$pdf->AddPage('P', '', 'A4');
$pdf->SetLineWidth(0,2);
$pdf->SetFont('Arial','B',14);
$pdf->Cell(75,25,$pdf->Image($imgurl, $pdf->GetX(100), $pdf->GetY(), 40),0,0);
$pdf->Cell(250,25,$kw[555],0,1);
//this is the function that makes the table
$pdf->CreateDynamicTable($array,$finalData);
$pdf->Output();


class PDF extends FPDF{
public $padding = 10;
function CreateDynamicTable($array,$data){
    $this->SetFillColor(191, 191, 191);
    $this->SetFont('Arial', 'B', 9);
    foreach($array AS $name => $confs){
        $this->Cell($confs['width'],10,$confs['header'],1,0,'C', true);
    }
    $this->Ln();
    $x0=$x = $this->GetX();
    $y = $this->GetY();
    foreach($data as $rows=>$key){
        $yH = $this->getTableRowHeight($key,$array);
        foreach($array AS $name => $confs){
            if(isset($key[$name])){
                $this->SetXY($x, $y);
                $this->Cell($confs['width'], $yH, "", 'LRB',0,'',false);
                $this->SetXY($x, $y);
                $this->MultiCell($confs['width'],6,$key[$name],0,'C');
                $x =$x+$confs['width'];
            }
        }
        $y=$y+$yH; //move to next row
        $x=$x0; //start from first column
    }
}
public function getTableRowHeight($key,$array){
    $yH=5; //height of the row
    $temp = array();
    foreach($array AS $name => $confs){
        if(isset($key[$name])){
            $str_w = $this->GetStringWidth($key[$name]);
            $temp[] = (int) $str_w / $confs['width'];
        }
    }
    $m_str_w = max($temp);
    if($m_str_w > 1){
        $yH *= $m_str_w;

    }
    $yH += $this->padding;
    return $yH;
}
}

Solution

  • I think this is because of the use of Cell and MultiCell. Sometimes you will have a cell whose height will exceed the page and AutoPageBreak will just throw that data onto the next page.

    Try $pdf -> SetAutoPageBreak( false ); and use AddPage() when you know that you are at the bottom of the page. To get the proper height if the cells, you will need to get the max height for all the cells in the row first and then decide if you are going to output on the current page or the next.