html文件转换成pdf和word

1、html文件转成pdf

采用jar包有itext-asian.jar、itextpdf-5.5.5.jar、itext-pdfa-5.5.5.jar、itext-xtra-5.5.5.jar,为了保持html页面的全部格式,需要进行相关设置,代码如下:

private boolean convert2Pdf(InputStream htmlInputStream, String pdfFile, String padding) throws FileNotFoundException, DocumentException { String[] paddings = padding.split(","); float a1 = (float) (Float.valueOf(paddings[0]) * 0.77); //为了设置pdf的上下左右页边距 float a2 = (float) (Float.valueOf(paddings[1]) * 0.77); float a3 = (float) (Float.valueOf(paddings[2]) * 0.77); float a4 = (float) (Float.valueOf(paddings[3]) * 0.77); com.itextpdf.text.Document document = new com.itextpdf.text.Document( PageSize.A4, a1, a2, a3, a4); PdfWriter pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile)); document.open(); CSSResolver cssResolver = new StyleAttrCSSResolver(); // HTML XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontProvider.register("resources/garial.ttf", "Linrial"); //前面的ttf字体需要系统支持,后一个参数是html文件中的字体格式 fontProvider.register("resources/fzst_gb18030_20101201.ttf", "FZSongTi_GB18030"); fontProvider.register("resources/fzfangsong.ttf", "FZFangSong"); fontProvider.register("resources/fzheiti.ttf", "FZHeiTi"); fontProvider.register("resources/fzkaiti.ttf", "FZKaiTi"); fontProvider.register("resources/gtimes.ttf", "LinTimes"); CssAppliers cssAppliers = new CssAppliersImpl(fontProvider); HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers); htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory()); final String IMG_PATH = pdfFile.substring(0, pdfFile.indexOf("/temp")) + "temp/"; //指定html文件的图片路径 htmlContext.setImageProvider(new AbstractImageProvider() { public String getImageRootPath() { return IMG_PATH; } }); // Pipelines PdfWriterPipeline pdf = new PdfWriterPipeline(document, pdfwriter); HtmlPipeline html = new HtmlPipeline(htmlContext, pdf); CssResolverPipeline css = new CssResolverPipeline(cssResolver, html); // XML Worker XMLWorker worker = new XMLWorker(css, true); XMLParser p = new XMLParser(worker); try { p.parse(htmlInputStream, Charset.forName("UTF-8")); } catch (IOException e) { e.printStackTrace(); return false; } finally { document.close(); } return true; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzdywx.html