I am trying to do some precise alignment with iTextSharp, but I keep falling short as I can't figure out a way to get a width / height value for a chunk or paragraph. If I create a paragraph that is a certain font and size and text, then its dimensions should be known, right?
I know that the default left/right/center alignments will do the trick for me mostly, but I have scenarios where knowing the dimensions will be most useful. Any ideas?
You can get a chunk's width using GetWidthPoint()
and the height of a chunk is generally the font's size unless you're using only lowercase letters. If so then you can manually measure characters using BaseFont.GetCharBBox()
.
Paragraphs are flowable items, however, and they depend on the context that they are written into so measuring them is harder. (Chunks don't automatically wrap but Paragraphs do.) The best way to measure a paragraph is to write it to a PdfCell
and then measure the PdfCell
. You don't have to actually add the PdfCell
to the document. The link below explains it a little more.
http://itext-general.2136553.n4.nabble.com/Linecount-td2146114.html
Use below code for exact size
Font font = ...;
BaseFont baseFont = font.BaseFont;
float width = baseFont.GetWidthPoint(text, fontSize);
float height = baseFont.GetAscentPoint(text, fontSize) - baseFont.GetDescentPoint(text, fontSize);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With