How to calculate the height of an element?

Tags: fontsmeasure texttext heightascenderuser unitiText 5

I am generating PDF files from XML data. I calculate the height of a paragraph element like this:

float paraWidth = 0.0f;
for (Object o : el.getChunks()) {
    paraWidth += ((Chunk) o).getWidthPoint();
float paraHeight = paraWidth/PageSize.A4.getWidth();
But this method does not works correctly.

Posted on StackOverflow on Jul 3, 2014 by Valeri

Your question is strange. According to the header of your question, you want to know the height of a string, but your code shows that you are asking for the width of a String.

Please take a look at the FoobarFilmFestival example.

If bf is a BaseFont instance, then you can use:

float ascent = bf.getAscentPoint("Some String", 12);
float descent = bf.getDescentPoint("Some String", 12);

This will return the height above the baseline and the height below the baseline, when we use a font size of 12. As you probably know, the font size is an indication of the average height. It's not the actual height. It's just a number we work with.

The total height will be:

float height = ascent - descent;

Or maybe you want to know the number of lines taken by a Paragraph and multiply that with the leading. That's a different question, though.