Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itextsharp measure chunk width / height

Tags:

c#

itextsharp

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?

like image 316
A.R. Avatar asked Feb 23 '11 13:02

A.R.


2 Answers

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

like image 135
Chris Haas Avatar answered Sep 24 '22 10:09

Chris Haas


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);
like image 24
imgen Avatar answered Sep 23 '22 10:09

imgen