public abstract class BasePdf { public static class MyFontsProvider extends XMLWorkerFontProvider { public MyFontsProvider() { super(null, null); } @Override public Font getFont(final String fontname, String encoding, float size, final int style) { String fntname = fontname; if (fntname == null) { fntname = "宋體"; } //網上通常沒有這段代碼,致使系統沒有宋體的狀況中文不顯示,要把宋體文件放到資源文件裏 registerFamily("宋體","宋體","/simsun.ttf"); return super.getFont(fntname, encoding, size, style); } } public static ElementList parseToElementList(String html, String css) throws IOException { // CSS CSSResolver cssResolver = new StyleAttrCSSResolver(); if (css != null) { CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(css.getBytes())); cssResolver.addCss(cssFile); } // HTML MyFontsProvider fontProvider = new MyFontsProvider(); CssAppliers cssAppliers = new CssAppliersImpl(fontProvider); HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); htmlContext.autoBookmark(false); // Pipelines ElementList elements = new ElementList(); ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null); HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end); CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline); // XML Worker XMLWorker worker = new XMLWorker(cssPipeline, true); XMLParser p = new XMLParser(worker); html = html.replace("<br>", "").replace("<hr>", "").replace("<img>", "").replace("<param>", "") .replace("<link>", ""); p.parse(new ByteArrayInputStream(html.getBytes())); return elements; } }