【发布时间】:2018-10-21 05:59:33
【问题描述】:
我有一个带有 utf8 编码和中文字符的数据库。我把这些数据变成一个字符串,然后将它传递给库的单元格,一切都很好,除了当我使用中文字符时它们没有显示出来,我试过这个:
public String testEncoding(String str) {
String result = "";
for(char ch : str.toCharArray())
result += "\\u" + Integer.toHexString(ch | 0x10000).substring(1);
return result;
}
还使用 notosans 和 arial uni 字体,将字符串转换为 unicode,当我打印时,它会显示 pdf \u6b98\u528d 中的 unicode,而不是中文字符,但是当我将其粘贴到字符串中时
String text = "\u6b98\u528d";
并将它传递给它显示正常的短语的单元格! 这是我使用的代码:
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;
}
有什么想法吗?我做错了什么?我在这里看到了很多示例,但是与我的示例不同,它们正在读取文本文件并直接传递 unicode 字符串。
【问题讨论】:
-
目前你的代码示例中有太多的
trys、catches 和ifs,因此可能出错的地方太多(例如找不到字体、不满足条件)由于未知原因,...)。出于测试目的简化您的代码,并使“不工作”的代码尽可能小。 -
谢谢你,先生,感谢这个很棒的库,实际上代码工作正常,是服务器失败导致无法识别路径,我只是使用 spring 类来获取路径和工作正常!
-
如果您将解决方案作为答案发布,那就太好了。
-
好的,我要发布它!
-
好的,谢谢!我赞成你的回答。它可能对其他开发人员有帮助。
标签: java spring itext pdf-generation asianfonts