Question

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?

Was it helpful?

Solution

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()

OTHER TIPS

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());

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
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top