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 判断优先级,依次筛选

  • 相关阅读:
    C++中public、protected、private的差别
    TSP问题
    Android百日程序:绘画程序-画手指路径
    DFS csu1719 Boggle
    Oracle数据库imp
    <html>
    SWIFT学习笔记05
    Xcode7 真机免证书调试Cocos2D游戏
    mycat 不得不说的缘分
    HashMap和Hashtable的差别
  • 原文地址:https://www.cnblogs.com/tusheng/p/7112719.html
Copyright © 2011-2022 走看看