ITEXT-字体兼容Linux平台

x33g5p2x  于2021-12-28 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(512)

问题场景

在用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

  1. /** * 适应Linux,Windows的字体测试 * @param path "E://TESTPDF/test.pdf" * @throws IOException */
  2. public static void test(String path) throws IOException {
  3. Document document = new Document();
  4. try {
  5. PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(path));
  6. document.open();
  7. String prefixFont = "";
  8. String os = System.getProperties().getProperty("os.name");
  9. if (os.startsWith("win") || os.startsWith("Win")) {
  10. prefixFont = "C:\\Windows\\Fonts" + File.separator;
  11. } else {
  12. prefixFont = "/usr/share/fonts/chinese" + File.separator;
  13. }
  14. BaseFont baseFont1 = BaseFont.createFont(prefixFont + "MSYH.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  15. Font yahei12 = new Font(baseFont1, 12f); //微软雅黑 小四
  16. document.newPage();
  17. document.add(new Paragraph("test", yahei12));
  18. document.close();
  19. pdfWriter.close();
  20. } catch (DocumentException e){
  21. e.printStackTrace();
  22. }catch (FileNotFoundException e){
  23. e.printStackTrace();
  24. }
  25. }

相关文章