Getting text width using iText

Posted: January 9th, 2008 | Author: steve | Filed under: iText |

I love the iText library, love it. It’s so well written, it works, it’s fast. The codebase has been well thought out and exposes every piece of PDF functionality you could ever need.

As I’m back doing some stuff with iText for work I thought I’d post any code snippets that might be useful to other people.

First up, getting the text width of a string when it is rendered using a given font:


BaseFont font = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
float stringWidth = font.getWidthPoint( "your string", 12 );

I’m using this to center a watermark vertically on the left hand side of each page. So I can work out where the text needs to go by subtracting the text width from the page height (width from height because the text is being shown vertically). Like so:


PdfContentByte under = stamper.getUnderContent( i );

under.beginText();
BaseFont font = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
float watermarkWidth = font.getWidthPoint( "this is the watermark", 12 );
under.setFontAndSize( font, 12 );
float y = ( reader.getPageSize(1).getWidth() / 2 ) - watermarkWidth;
under.setTextMatrix(0, 1, -1, 0, 10, y );
under.showText( "this is the watermark" );
under.endText();

More iText goodness to follow!



Leave a Reply