使用IText+Freemarker生成PDF文件 |
您所在的位置:网站首页 › freemarker生成pdf › 使用IText+Freemarker生成PDF文件 |
最近公司有个打印文件的需求,既然是打印,为了格式统一肯定使用PDF文件比较好,查了一下JAVA中大部分是使用IText创建PDF的,学习了下他人的方法,最终实现根据Freemarker模板生成PDF的方法 依赖 org.freemarker freemarker 2.3.28 com.itextpdf itextpdf 5.5.11 com.itextpdf.tool xmlworker 5.5.11 复制代码实际代码freemarker模板文件 template.ftl Title body { font-family: SimHei; } .blue { color: blue; } 你好111,${name} ${o.uuid} 复制代码根据freemarker模板生成HTML public static String freeMarkerRender(Map data, String url, String htmlTmp) { Writer out = new StringWriter(); try { freemarkerCfg.setDirectoryForTemplateLoading(new File(url)); freemarkerCfg.setDefaultEncoding("UTF-8"); // 获取模板,并设置编码方式 Template template = freemarkerCfg.getTemplate(htmlTmp); template.setEncoding("UTF-8"); // 合并数据模型与模板 template.process(data, out); //将合并后的数据和模板写入到流中,这里使用的字符流 out.flush(); return out.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return null; } 复制代码根据HTML生成PDF文件 public static void createPdf(OutputStream out, String content, String dest) throws IOException, DocumentException { // step 1 Document document = new Document(); // step 2 PdfWriter writer = PdfWriter.getInstance(document, out); // step 3 document.open(); // step 4 XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS); fontImp.register(FONT); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(content.getBytes("UTF-8")), null, Charset.forName("UTF-8"), fontImp); // step 5 document.close(); } 复制代码测试代码 private static final String HTML = "PaperTemplate.ftl"; private static final String FONT = "C:\\app\\simhei.ttf"; @RequestMapping("/download/{id}") @ResponseBody public Object download(@PathVariable Long id, HttpSession httpSession) throws IOException, DocumentException { Map data = new HashMap(); data.put("name", "张三"); data.put("model", paperServ.getAll()); String url = httpSession.getServletContext().getRealPath("/") + "download" + File.separator; String html = freeMarkerRender(data, url, HTML); ServletOutputStream out = getResponse().getOutputStream(); createPdf(out, html, DEST); out.flush(); IOUtils.closeQuietly(out); return html; } 复制代码效果图 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |