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\r\\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 判斷優先級,依次篩選

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM