How to calculate the string width in iText?
Asked Answered
B

3

24

I am using iText to write a PDF. In some cases, I need to sign the PDF with the SetVisibleSignature function. With this function, we need to designate the rectangle that we will write the content into.

But it's hard for me to calculate how wide the string will be, so that I can set the rectangle before setting a signature on the PDF.

How can I calculate the string width in iText?

Bludge answered 6/10, 2009 at 14:35 Comment(0)
L
28

You can use BaseFont.getWidthPoint(String text, float fontSize) to get the width of the string in pt.

Or put the string in a Chunk and do chunk.getWidthPoint()

Lougheed answered 26/10, 2009 at 14:16 Comment(5)
how do you retreive the basefont instance?Piglet
I would like to know the width of paragraphs in a table. It seems that the method using a chunk returns the wrong values.Piglet
How static getWidthPoint would know which font is assumed? x_XSchappe
@PavelVlasov I've removed my comment about this method being static. Obviously, it is not static and makes no sense to be static. You are right.Lougheed
Nice solution. Works perfectly for me.Astronomical
P
17

The accepted answer BaseFont.getWidthPoint, won't work in itext 5.5.4 since the method isn't static anymore. Even if it did still exist, it doesn't take into account the true font being used (its family or its bold/italics) since it's static and is receiving limited parameters.

chunk.getWidthPoint() does work with the true font as later stated, but for certain uses it is a waste to constantly create a chunk just for the width, especially if the chunk isn't planned on being used later.

This is the underlying code for chunk.getWidthPoint() to use as a standalone substitute, assuming you are not doing any horizontal scaling:

font.getCalculatedBaseFont(true).getWidthPoint(text, font.getCalculatedSize());
Principe answered 29/1, 2015 at 20:16 Comment(0)
Q
3

I ended up doing this with ColumnText.getWidth( Phrase phrase ) to size what the width of a Phrase would be before showing it with ColumnText.showTextAligned.

In this snippet, I used the ColumnText.getWidth to size the length of a string to place it top right of a page. It works in portrait A4, haven't tested it further.

Phrase phrase = new Phrase( "Bla bla bla!", new Font( FontFamily.HELVETICA, 9 ) );
float width = ColumnText.getWidth( phrase );

ColumnText.showTextAligned (
    canvas,
    Element.ALIGN_LEFT,
    phrase,
    canvas.getPdfDocument( ).right( ) - width,
    canvas.getPdfDocument( ).top( ) + 9,
    0
);
Quatrefoil answered 15/12, 2016 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.