问题场景
在用itext开发完PDF之后,有要求Apache要部署到Linux下,也可能部署到windows下,由于笔者在Windows下开发的,字体没问题;但是Linux未必安装了字体,关于如何在Linux下安装字体请自行Google或者点击这里,那么代码也要扩展。
代码
需导入的jar包:itext-pdfa-5.5.6.jar、itext-xtra-5.5.6.jar、itext-5.5.6.jar、itext-asian.jar
/**
* 适应Linux,Windows的字体测试
* @param path "E://TESTPDF/test.pdf"
* @throws IOException
*/
public static void test(String path) throws IOException {
Document document = new Document();
try {
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));
document.open();
String prefixFont = "";
String os = System.getProperties().getProperty("os.name");
if (os.startsWith("win") || os.startsWith("Win")) {
prefixFont = "C:\\Windows\\Fonts" + File.separator;
} else {
prefixFont = "/usr/share/fonts/chinese" + File.separator;
}
BaseFont baseFont1 = BaseFont.createFont(prefixFont + "MSYH.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font yahei12 = new Font(baseFont1, 12f); //微软雅黑 小四
document.newPage();
document.add(new Paragraph("test", yahei12));
document.close();
pdfWriter.close();
} catch (DocumentException e){
e.printStackTrace();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}