zoukankan      html  css  js  c++  java
  • openhtmltopdf 支持自定义字体、粗体

    一、支持自定义字体

    private static void renderPDF(String html, OutputStream outputStream) throws Exception {
            try {
                PdfRendererBuilder builder = new PdfRendererBuilder();
                addFont(builder, "D:\font\");
                builder.useUnicodeBidiSplitter(new ICUBidiSplitter.ICUBidiSplitterFactory());
                builder.useUnicodeBidiReorderer(new ICUBidiReorderer());
                builder.defaultTextDirection(TextDirection.LTR);
                builder.useSVGDrawer(new BatikSVGDrawer());
                builder.useObjectDrawerFactory(buildObjectDrawerFactory());
           //这一段可以忽略、正则处理内容(没有优化)
                String h = html.replaceAll("<!--[\w\W
    \n]*?-->", "").replaceAll("(?i)<img+([^>]*?[\s"])[(.*?)>]", "<img$1/>").replaceAll("&nbsp;", " ").replaceAll("(ng-bind="|ng-class="|ng-src="|ng-style=")(.*?)"", "");
                builder.withHtmlContent(h, TestcaseRunner.class.getResource("/testcases/").toString());
                builder.toStream(outputStream);
                builder.run();
            } finally {
                outputStream.close();
            }
        }


        /**
         * 添加字体库
         * @param builder
         * @param dir
         */
        private static void addFont(PdfRendererBuilder builder, String dir) {
            File f = new File(dir);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        String lower = name.toLowerCase();
    //                    lower.endsWith(".otf") ||  对otf库的字体支持有问题,暂时屏蔽
                        return lower.endsWith(".ttf") || lower.endsWith(".ttc");
                    }
                });
                for (File subFile:files) {
                    String fontFamily = subFile.getName().substring(0, subFile.getName().lastIndexOf("."));
                    builder.useFont(subFile, fontFamily);
                }
            }
        }

    二、支持字体粗体

    for (File subFile:files) {
                    String fontFamily = subFile.getName().substring(0, subFile.getName().lastIndexOf("."));
              //核心代码
    //自定义规则 加粗的库 含有"_"
    //
    700 为bold对应的数值、默认为400

    if(fontFamily.indexOf("_") > 0){ builder.useFont(subFile, fontFamily.substring(0, fontFamily.indexOf("_")), 700, FontStyle.NORMAL, true); }else{ builder.useFont(subFile, fontFamily); } }

    斜体等类似

    追溯源码,一种字体对应多个字体列表(常规、粗体、斜体、粗体_斜体)

    根据字体名称_粗体_style 判断优先级,依次筛选

  • 相关阅读:
    MQ 2035(MQRC_NOT_AUTHORIZED)
    C# 构造函数中调用虚方法的问题
    Oracle bug 使用max或min函数into到一个char类型报字符缓冲区太小的错误
    windows2003 64位 iis6.0 运行32位web应用程序
    .NET安装和配置Oracle数据访问组件(ODAC)
    WMS函数组:10.创建采购订单
    报表:BOM展开程序
    WMS函数组:9.交货单过帐3(BDC)
    WMS函数组: 7.交货单行项目除
    WMS函数组:1.检查ZPB2是否存在
  • 原文地址:https://www.cnblogs.com/tusheng/p/7112719.html
Copyright © 2011-2022 走看看