Skip to main content
Skip table of contents

How to calculate the height of an element?

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.

Click this link if you want to see how to answer this question in iText 7.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.