A game of OpenTTD is in progress...

Posted by

FPDF: Calculating the height of a MultiCell

FPDF is a great tool to easily create PDF documents. The automatic line-breaking feature is great, but leaves something to be desired. For instance, if a MultiCell is too tall to fit in the remainder of a page, the element gets split up.

Unfortunately, there is no built-in method to calculate what the height of a MultiCell would be.

One solution to this issue posted on StackOverflow utilizes GetStringWidth() to try and approximate what the height would be. I tried it out, but it doesn’t quite hit the nail on the head. It would produce inaccurate results due to spacing and newline issues. I wanted an exact height, not an estimated guess.

I ended up cloning the MultiCell() function within the FPDF class, gutting it, and re-purposing it to return an accurate height. Every time the function made a call to Cell(), I replaced the call with a line of code to add the height of the Cell to the total height of the MultiCell. I also removed a few things such as any code relating to the border.

Using a conditional statement, I then checked the height of the MultiCell against the remaining space on the page:

$spaceleft =  $pdf->h - $pdf->GetY() - $pdf->bMargin

if ($pdf->GetMultiCellHeight(args) > $spaceleft)


You can get a copy of my function here: https://gist.github.com/4089627. Don’t trust random code on the internet? I wouldn’t either. View the diff against the original MultiCell() function here: http://diffchecker.com/99S1TJ8b.

7 Responses to “FPDF: Calculating the height of a MultiCell”

  1. Nils writes:

    Thanks for this helpful post!

  2. Matt writes:

    Fantastic… exactly what I was needing… thank you very much!

  3. etienne writes:

    Hello, you may retrive the multicell height that way :

    Let assume you used :
    $x = 10;
    $y = 10;
    $pdf->setXY($x, $y);

    You can get the multiCell height by doing :

    $multiCellHeight = $pdf->y - $y;


  4. Anderson writes:

    thank you very much you helped me!
    all the best!

  5. Rulex writes:

    Thanks! :=)

  6. Isuru writes:

    Thanks.. this is what I was searhcing…

  7. Steve writes:

    Thank you :-)

Leave a Reply