How to calculate the string width in iText?

点点圈 提交于 2019-11-27 21:12:56

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

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
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!