How to calculate/set font line distance?
I am implementing a PdfPageEventHelper
event to add a footer as shown in this code snippet:
ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase(String.format(" %d ", writer.getPageNumber()), footerFont), document.right() - 2 , document.bottom() - 20, 0);
I need to add 3 lines, but I don't find how to calculate the distance between the lines. Each line has different font size. What should I use as XXX
value in document.bottom() - XXX
?
Posted on StackOverflow on Sep 17, 2013 by Dhaval
The difference between two lines is the leading
. You can pick your own leading, but it is custom to use 1.5 times the font size. You are drawing line by line yourself, using different font sizes, so you'll have to adjust the Y value based on that font size. Note that Canvas.showTextAligned()
uses the Y value as the baseline of the text you're adding, so if you have some text with font size of 12pt, you'd need to take into account a leading of 18pt. If you have a font size 8pt, you make sure you have 12pt.
That's the easy solution: based on "convention". If you really want to know how much horizontal space some specific takes, you need to calculate the ascender and the descender. If bf
is your font (a PdfFont
object), text
is your text (a String
) and size
is your font size (a float
), then the height of your text is equal to height
:
float aboveBaseline = bf.getAscent(text, size);
float underBaseline = bf.getDescent(text, size);
float height = aboveBaseline - underBaseline;
When y
is the Y-coordinate used in showTextAligned()
make sure you keep the space between y + aboveBaseline
and y + underBaseline
free. This is the accurate solution.
Note that document.bottom() - 20
looks somewhat strange. I would expect document.bottom() + 20
as the Y-axis of the PDF coordinate system points upwards, not downwards.
Click this link if you want to see how to answer this question in iText 5.