ITEXT-字体兼容Linux平台

14 篇文章 2 订阅

问题场景

在用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();
       }
    }
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值