Why does my code not work?

I want to display the special character "India Rupee Symbol" in iText,

My Code:

BaseFont rupee =BaseFont.createFont("assets/arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
createHeadings(cb,495,60,": " + edt_total.getText().toString(),12,rupee);
 
private void createHeadings(PdfContentByte cb, float x, float y, String text, int   size,BaseFont fb){
    cb.beginText();
    cb.setFontAndSize(fb, size);
    cb.setTextMatrix(x,y);
    cb.showText(text.trim());
    cb.endText();
}

Posted on StackOverflow on Jul 4, 2013 by Avanish Singh

It's never a good idea to store a Unicode character such as ? in your source code. Plenty of things can go wrong if you do so:

  • Somebody can save the file using an encoding different from Unicode, for instance, the double-byte rupee character can be interpreted as two separate bytes representing two different characters.
  • Even if your file is stored correctly, maybe your compiler will read it using the wrong encoding, interpreting the double-byte character as two separate characters.

From your code sample, it's evident that you're not familiar with the concept known as encoding. When creating a Font object, you pass the rupee symbol as encoding.

The correct way to achieve what you want in iText 7 looks like this:

PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H, true);
doc.add(new Paragraph("\u20B9 is a Rupee character").setFont(font));

Note that there are two possible Unicode values for the Rupee symbol (source Wikipedia): \u20B9 is the value you're looking for; the alternative value is \u20A8 (which looks like this: ?).

Note that it's very important to check if the font you're using knows how to draw the symbol. If it doesn't, nothing will show up on your page.

Please take a look at the RupeeSymbol example to learn more.

Click How to display indian rupee symbol? if you want to see how to answer this question in iText 5.