How to calculate the height of an element?

2019-03-07 03:28发布

问题:

I am generating pdf files by XML data.

I calculate the height of a paragraph element as :

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.

Can you give me an idea?

回答1:

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. In that case, there are different possibilities. As it's not clear from your question what you want (height of chunks, width of chunks, vertical position of the baseline,...), you won't get any better answers than the ones that are already given. Please rephrase your question if the height of the glyphs in a Chunk wasn't what you expected.



回答2:

Firstly why you iterating over Chunk collection casted to Object ? If all elements of this collection are Chunk, use this:

for (Chunk c : el.getChunks()) {
    paraWidth += c.getWidthPoint();
}

What do you mean saying method does not works correctly ?