May 12, 2010
Kiran Kumar
I have found it hard to identify a solution for supporting Unicode(UTF-8) characters in PDF. Finally I have found a solution using which you can write Unicode characters on to PDF.
i-Text is smart enough to provide a solution for everything. Using “FontSelector” class you can write UTF-8 characters in to PDF. The below code will help you in doing so,
FontSelector fontSel = new FontSelector();
BaseFont bFont1 = null;
BaseFont bFont2 = null;
BaseFont bFont3 = null;
BaseFont bFont4 = null;
String fontDir = "C:\fonts\";
try
{
bFont1 = BaseFont.createFont(fontDir+"tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
bFont2 = BaseFont.createFont(fontDir+"chinese.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
bFont3 = BaseFont.createFont(fontDir+"japanese.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
bFont4 = BaseFont.createFont(fontDir+"korean.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font dataFont1 = new Font(bFont1,size,Font.NORMAL);
Font dataFont2 = new Font(bFont2,size,Font.NORMAL);
Font dataFont3 = new Font(bFont3,size,Font.NORMAL);
Font dataFont4 = new Font(bFont4,size,Font.NORMAL);
fontSel.addFont(dataFont1);
fontSel.addFont(dataFont2);
fontSel.addFont(dataFont3);
fontSel.addFont(dataFont4);
}
catch(Exception e)
{
e.printStackTrace();
}
After preparing the FontSelector object with the required fonts, process the text you are going to write on to the PDF using FontSelector as below,
String text = "κείμενο テキスト 文本 본문 text"; //String with combination of different languages
Phrase ph = fontSel.process(text);
Paragraph para = new Paragraph(ph);
para.setAlignment(Element.ALIGN_CENTER);
document.add(para);
You have to serve the desired fonts to the FontSelector to support all the languages. This FontSelector approach will be useful if you have mixed languages. If your data is of only language you know need to create the FontSelector. You can write the PDF by creating a single BaseFont with the desired font.