iText自带是不支持中文的,需要引入第三方中文包itext-asian才行,但是在itext-asian中可使用的中文也只有宋体,显示太low,表现形式太差,不能接收。
现通过引入TTF字体文件形式的方式在项目中使用其他字体中文,比如华文细黑、雅黑等等。 关于中文字体可以在windows下的C:/WINDOWS/Fonts下找到。
Linux下,推荐放到字体目录下即可,比如:/usr/share/fonts/
BaseFont bfChinese = BaseFont.createFont(“C:/WINDOWS/Fonts/STXIHEI.TTF”, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(bfChinese, 8, Font.BOLD);
另外,参考iText包中的com.itextpdf.text.pdf.BaseFont类,我们发现他的createFont方法可以发现:
if (isBuiltinFonts14 || name.toLowerCase().endsWith(".afm") || name.toLowerCase().endsWith(".pfm")) {
fontBuilt = new Type1Font(name, encoding, embedded, ttfAfm, pfb, forceRead);
fontBuilt.fastWinansi = encoding.equals(CP1252);
}
else if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0) {
if (encoding.equals(IDENTITY_H) || encoding.equals(IDENTITY_V))
fontBuilt = new TrueTypeFontUnicode(name, encoding, embedded, ttfAfm, forceRead);
else {
fontBuilt = new TrueTypeFont(name, encoding, embedded, ttfAfm, false, forceRead);
fontBuilt.fastWinansi = encoding.equals(CP1252);
}
}
除了TTF字体外,还有其他几种字体文件支持。
ref:
https://my.oschina.net/mobinchao/blog/524112