Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FPDF height of a MultiCell Element

Tags:

php

fpdf

I use the FPDF library to export some document files as PDF. One document includes a list of strings which have a different length. I print all strings as $pdf->MultiCell(). Now I would like to have the current height of that MultiCell to have the same line spacing in case that they have just one line or more.

Code Example:

//MySQL Query
while($row = mysql_fetch_array($res) {
   $pdf->SetXY(18, $x);
   $pdf->MultiCell(80, 5, $rowr['text']); //text has one or more lines
   $x = $x + 10; // Here I would prefer a solution to say: $x = $x + 2 + height of the MultiCell()
}
like image 475
Thomas1703 Avatar asked Aug 21 '13 11:08

Thomas1703


1 Answers

I'm coding in golang so I'll show some pseudo-code. I hope the accessible methods are the same in php as in golang.

There is a method called pdf.SplitLines(text, width). You will pass your string content and the desired width and it will return an array of strings that represents the lines that'll be computed to display that content.

With that its easy. In pseudo-code it could look like:

fontSize = 10;
lineHeight = 12;
targetWidth = 50;
pdf.SetFontSize(fontSize)
nLines = length(pdf.SplitLines(content, targetWidth));

multiCellHeight = nLines * lineHeight;
pdf.Multicell(targetWidth, lineHeight, content, ...) 

The rendered MultiCell will have the exact same size as stored in multiCellHeight. This way you'll get the hight before rendering.

This is working because the passed height for the MultiCell is the lineHeight of each row. If you know the rows before rendering, you'll get the total height.


I'm sorry if this fails for any reason for php. Just let me know if that's the case.

like image 57
C4d Avatar answered Oct 13 '22 17:10

C4d