Unable to show extended characters in a PDF using iText

Adobe’s PDF readers come with 14 standard fonts built-in to the reader software. Most third-party reader offer these too. Not surprisingly iText lets you select the standard fonts and use them in the PDFs you create.

If you are finding that you are not able to display extended characters in your PDFs – and by extended characters I mean characters that are not in the Basic Latin Unicode chart – then this could be because you are using one of the 14 built-in fonts and they do not support the character you want to display.

To find out which characters are in the Basic Latin Unicode, look here: http://unicode.org/charts/

You will need to find a font that supports the characters you want to print. For an open-source replacement for the built-in Times New Roman, Arial or Courier you could try Liberation Fonts. We’ve used the Times Liberation font and it does look a bit different that the built-in but its metric compatible and, in my opinion, looks nicer.

Getting text width using 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!