Search code examples
fpdf

Prevent cells from overlapping when the content is wider than the cell


I have this.

for($i=0; $i < $longArreglo; $i++) {    
        $this->Cell($w[0],6, $final_array[$i][0],'LR',0,'L', $fill);
        $this->Cell($w[1],6, $final_array[$i][2],'LR',0,'C', $fill);
        $this->Cell($w[2],6, $final_array[$i][3],'LR',0,'L', $fill);
        $this->Cell($w[3],6, $final_array[$i][5],'LR',0,'C', $fill);
        $this->Cell($w[4],6, $final_array[$i][6],'LR',0,'C', $fill);
        $this->Cell($w[5],6, $final_array[$i][12],'LR',0,'C', $fill);
        $this->Cell($w[6],6, $final_array[$i][13],'LR',0,'C', $fill);
        $this->Cell($w[7],6, $final_array[$i][14],'LR',0,'C', $fill);
        $this->Cell($w[8],6, $final_array[$i][15],'LR',0,'C', $fill);
        $this->Cell($w[9],6, $final_array[$i][16],'LR',0,'C', $fill);
        $this->Cell($w[10],6, $final_array[$i][17],'LR',0,'C', $fill);
        $this->Cell($w[11],6, $final_array[$i][18],'LR',0,'C', $fill);
        $this->Cell($w[12],6, $final_array[$i][19],'LR',0,'C', $fill);
        $this->Cell($w[13],6, $final_array[$i][20],'LR',0,'C', $fill);
        $this->Ln();

    }

And here: $this->Cell($w[2],6, $final_array[$i][3],'LR',0,'L', $fill); is a person name, the width of cell is 15 and if the name is most large than cell, it does this:

I need the cells to not coalesce.


Solution

  • This post might be old but I couldn't find any other solution on the internet. I've modified Hugo's post and I hope that this will be helpful to someone one day. I've created a new method in the fpdf class for this for ease of use.

    PDF Example

    function pdfText($cellWidth, $text, $pdf){
        $textWidth = $pdf->getstringwidth($text);
        while($textWidth > $cellWidth -1){
            $text       = substr($text,0,-1);
            $textWidth  = $pdf->getstringwidth($text);
        }
        return $text;
    }
    
    require_once('fpdf/fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    
    $text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint esse quia repellat cupiditate excepturi exercitationem asperiores eligendi iusto. Blanditiis sequi suscipit assumenda quibusdam aliquid quas eligendi soluta ab fugit ad.';
    
    $pdf->setFont('Arial', '', 10);
    $cellWidth = 180;
    $text = pdfText($cellWidth, $text, $pdf);
    $pdf->Cell($cellWidth,6,$text,1,1,'L',0);
    
    $pdf->setFont('Arial', '', 12);
    $cellWidth = 160;
    $text = pdfText($cellWidth, $text, $pdf);
    $pdf->Cell($cellWidth,7,$text,1,1,'L',0);
    
    $pdf->setFont('Arial', '', 14);
    $cellWidth = 140;
    $text = pdfText($cellWidth, $text, $pdf);
    $pdf->Cell($cellWidth,8,$text,1,1,'L',0);
    
    $pdf->setFont('Arial', '', 16);
    $cellWidth = 120;
    $text = pdfText($cellWidth, $text, $pdf);
    $pdf->Cell($cellWidth,9,$text,1,1,'L',0);
    
    $pdf->Output('I');