处理word转pdf中文缺失时遇到的问题
异常信息:com.lowagie.text.DocumentException: Font ‘STSong-Light’ with ‘UniGB-UCS2-H’
版本问题,用的是com.lowagie.text1.0.6处理中文字体 版本较低适配不了STSong-Light字体
可以将STSong-Light更换为simsun.ttf "UniGB-UCS2-H"替换为BaseFont.IDENTITY_H 就可以了
问题代码:
PdfOptions options = PdfOptions.create();
// 中文字体处理
options.fontProvider(new IFontProvider() {
@Override
public Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, style, color);
if (familyName != null)
fontChinese.setFamily(familyName);
return fontChinese;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
});
PdfConverter.getInstance().convert(doc, targetStream, options);
更改后代码 亲测可行
PdfOptions options = PdfOptions.create();
// 中文字体处理
options.fontProvider(new IFontProvider() {
@Override
public Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {
try {
BaseFont bfChinese = BaseFont.createFont("simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, style, color);
if (familyName != null)
fontChinese.setFamily(familyName);
return fontChinese;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
});
PdfConverter.getInstance().convert(document, out, options);
注意:
字体需要自己下载 放在项目的resources内