In the comment section, Funkystein wrote that the problem you describe is typical when
- you are using a font which doesn't have that glyph. or
- you aren't using the right encoding.
I have written an example that illustrates this: RupeeSymbol
public static final String DEST = "results/fonts/rupee.pdf";
public static final String FONT1 = "resources/fonts/PlayfairDisplay-Regular.ttf";
public static final String FONT2 = "resources/fonts/PT_Sans-Web-Regular.ttf";
public static final String FONT3 = "resources/fonts/FreeSans.ttf";
public static final String RUPEE = "The Rupee character u20B9 and the Rupee symbol u20A8";
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(DEST));
document.open();
Font f1 = FontFactory.getFont(FONT1, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
Font f2 = FontFactory.getFont(FONT2, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
Font f3 = FontFactory.getFont(FONT3, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 12);
Font f4 = FontFactory.getFont(FONT3, BaseFont.WINANSI, BaseFont.EMBEDDED, 12);
document.add(new Paragraph(RUPEE, f1));
document.add(new Paragraph(RUPEE, f2));
document.add(new Paragraph(RUPEE, f3));
document.add(new Paragraph(RUPEE, f4));
document.close();
}
The RUPEE
constant is a String
that contains the Rupee character as well as the Rupee symbol: "The Rupee character ? and the Rupee symbol ?"
.
The characters are stored as Unicode values, because if we store the characters otherwise, they may not be rendered correctly. For instance: if you retrieve the values from a database as Winansi, you will end up with incorrect characters.
I test three different fonts (PlayfairDisplay-Regular.ttf, PT_Sans-Web-Regular.ttf and FreeSans.ttf)
and I use IDENTITY_H
as encoding three times. I also use WINANSI
a fourth time to show that it goes wrong if you do.
The result is a file named rupee.pdf:
As you can see, the first two fonts know how to draw the Rupee character. The third one doesn't. The first two fonts don't know how to draw the Rupee symbol. The third one does. However, if you use the wrong encoding, none of the fonts draw the correct character or symbol.
In short: you need to find a font that knows how to draw the characters or symbols you need, then you have to make sure that you are using the correct encoding (for the String
as well as the Font
).
You can download the full sample code here.