I have the following problem have a database with utf8 encoding and chinese characters. i get that data into a string and then pass it to the cells of the library, all fine except that when i use chinese characters they aren't shown, I tried this:
public String testEncoding(String str) {
String result = "";
for(char ch : str.toCharArray())
result += "\\u" + Integer.toHexString(ch | 0x10000).substring(1);
return result;
}
and also use notosans and arial uni fonts, that converts the strings to unicode and when i print it shows me the unicode in the pdf \u6b98\u528d, not the chinese characters but when i paste that into a string
String text = "\u6b98\u528d";
and pass it to the cell of the pharagraph it shows fine! Here's the code i use for that:
final String PATH_FONT_ARIALUNI = "src/main/resources/fonts/NotoSansCJKsc-Regular.otf";
// FOR Chinese
BaseFont baseFont = null;
try {
baseFont = BaseFont.createFont(PATH_FONT_ARIALUNI, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Font font = new Font(baseFont, 6.8f);
Font fontNormal = new Font(FontFamily.HELVETICA, 10, Font.NORMAL, BaseColor.RED);
char[] aa = title.toCharArray();
boolean isLastChineseChar = false;
for (int j = 0; j < title.length(); j++) {
if((Character.UnicodeBlock.of(aa[j]) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS)){
isLastChineseChar = true;
/*System.out.println("Is CHINESE: " + aa[j]);*/
}
}
Phrase phrase = null;
if(isLastChineseChar){
phrase = new Phrase(title, font);
//also passing testEncoding(title) but as i say it shows unicode in the printed pdf
PdfPCell cell = new PdfPCell(phrase);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
if (align == 2) {
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
return cell;
} else {
phrase = new Phrase(title, fontNormal);
PdfPCell cell = new PdfPCell(phrase);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
if (align == 2) {
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
return cell;
}
Any ideas? what i'm doing wrong? I see lots of examples here but there are reading text files and passing the unicode strings directly not like my sample.
My code already works fine, in you have any problem in your production servers that characters aren't showing the solution is the following:
in you class add this
@Value("classpath:fonts/NotoSansCJKsc-Regular.otf")
private Resource res;
and the you import like this:
baseFont = BaseFont.createFont(res.getURI().getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
and all will be working fine!
Resource is an Spring Framework class that do this job for you