项目场景:html转换成pdf
大部分项目都会遇到将展示的数据导入到本地,转换成word或者是转换成pdf.最近就分配到一个任务任务,html转pdf并输出字节流,供前端展示及下载。
功能实现
代码提示:
-
主要是通过拿到的html字符串通过ConverterProperties
转换成pdf。 -
fontPath是通过getPath方法得到的字体路径。
public byte[] DataExport(Map<String, Object> params) { List<Map<String, Object>> content = jdbcTemplate.queryForList("select title,content from xtyw.rpt_traffic_info where reportid = '" + params.get("reportid") + "'"); if (null != content && content.size() > 0) { byte[] content1 = (byte[]) content.get(0).get("content"); String title = (String) content.get(0).get("title"); String html = new String(content1, StandardCharsets.UTF_8).replace("<title>分析报告浏览</title>","<title>"+title+"</title>"); try ( ByteArrayOutputStream os = new ByteArrayOutputStream(); PdfWriter writer = new PdfWriter(os); PdfDocument pdf = new PdfDocument(writer) ) { //转换器属性设置 ConverterProperties props = new ConverterProperties(); //字体 props.setFontProvider(new FontProvider()); String fontPath = getfontPath(); props.getFontProvider().addFont(fontPath); //HtmlConverter.convertToDocument Document document = HtmlConverter.convertToDocument(html, pdf, props); //设置字体 PdfFont pdfFont = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H,true); document.setFont(pdfFont); //页边距 document.setMargins(0, 0, 0, 0); document.close(); System.out.println("html转换pdf操作成功..."); return os.toByteArray(); } catch (IOException e) { System.out.println("html转换pdf操作异常..." + e.getMessage()); return null; } } return null; } /** * 获取字体路径 * */ public String getfontPath() { String url = ""; try { ApplicationHome applicationHome = new ApplicationHome(JtfxypApplication.class); url = applicationHome.getSource().getParentFile().toString(); //windows读取resources下的字体 if (StringUtils.indexOf(System.getProperty("os.name").toLowerCase(), "windows") > -1) url += "\\classes\\font\\simfang.ttf"; //linux读取项目中配置的字体 else if (StringUtils.indexOf(System.getProperty("os.name").toLowerCase(), "linux") > -1) url += "/font/simfang.ttf"; logger.info("---字体路径:" + url); } catch (Exception e) { e.printStackTrace(); } finally { return url; } }
拓展分析:
html中包含图片
1.若是可通过src指向其保存路径。
2.若是前端通过vue框架echar生成的可将标签替换成,通 过getdateurl()方法生成图片base64编码,再将src指定编码即可。