org.xhtmlrenderer flying-saucer-pdf9.1.16 com.itextpdf itextpdf5.5.13 org.freemarker freemarker2.3.31
templates.ftl 放入resource文件中
simsun.ttc 为字体文件
1. HttpHeaders 写法
@GetMapping("/pdf") public ResponseEntity> export(HttpServletResponse response) { try { HttpHeaders headers = new HttpHeaders(); MapdataMap = new HashMap<>(16); dataMap.put("userName", "张三"); String htmlStr = PDFUtil.freemarkerRender(dataMap, "templates.ftl"); byte[] pdfBytes = PDFUtil.createPDF(htmlStr, "simsun.ttc"); if (pdfBytes != null && pdfBytes.length > 0) { String fileName = System.currentTimeMillis() + (int) (Math.random() * 90000 + 10000) + ".pdf"; headers.setContentDispositionFormData("attachment", fileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity (pdfBytes, headers, HttpStatus.OK); } } catch (Exception e) { e.printStackTrace(); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); return new ResponseEntity<>("{ "code" : "404", "message" : "not found" }", headers, HttpStatus.NOT_FOUND); }
2. Response 写法
@GetMapping("/pdf") public void export(HttpServletResponse response) { ServletOutputStream outputStream = null; InputStream inputStream = null; try { // 设置参数 MapdataMap = new HashMap<>(16); dataMap.put("text", " 姓名:张三
日期:2022/08/10
"); String htmlStr = PDFUtil.freemarkerRender(dataMap, "templates.ftl"); byte[] pdfBytes = PDFUtil.createPDF(htmlStr, "simsun.ttc"); // 获取输出流 outputStream = response.getOutputStream(); if (pdfBytes != null && pdfBytes.length > 0) { // 设置文件名 String fileName = System.currentTimeMillis() + (int) (Math.random() * 90000 + 10000) + ".pdf"; response.setHeader("content-Type", "application/octet-stream"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); // 写入输出流 outputStream.write(pdfBytes); // 获取输入流 inputStream = new ByteArrayInputStream(pdfBytes); // 输入流保存阿里云 final String upload = OssBootUtil.upload(inputStream, "upload/agree/" + fileName); } } catch (Exception e) { e.printStackTrace(); try { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException ex) { ex.printStackTrace(); } } }
import com.dpxdata.backend.report.util.ResourceFileUtil; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.BaseFont; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.*; import java.util.Map; public class PDFUtil { private PDFUtil(){} private volatile static Configuration configuration; static { if (configuration == null) { synchronized (PDFUtil.class) { if (configuration == null) { configuration = new Configuration(Configuration.VERSION_2_3_28); } } } } public static String freemarkerRender(MapdataMap, String ftlFilePath) { Writer out = new StringWriter(); configuration.setDefaultEncoding("UTF-8"); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); try { configuration.setDirectoryForTemplateLoading(new File(ResourceFileUtil.getParent(ftlFilePath))); configuration.setLogTemplateExceptions(false); configuration.setWrapUncheckedExceptions(true); Template template = configuration.getTemplate(ResourceFileUtil.getFileName(ftlFilePath)); template.process(dataMap, out); out.flush(); return out.toString(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } public static byte[] createPDF(String htmlTmpStr, String fontFile) { ByteArrayOutputStream outputStream = null; byte[] result = null; try { outputStream = new ByteArrayOutputStream(); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(htmlTmpStr); ITextFontResolver fontResolver = renderer.getFontResolver(); // 解决中文支持问题,需要所需字体(ttc)文件 fontResolver.addFont(ResourceFileUtil.getAbsolutePath(fontFile),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); renderer.layout(); renderer.createPDF(outputStream); result=outputStream.toByteArray(); if(outputStream != null) { outputStream.flush(); outputStream.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
Title
收 据 |
||||
付款人 |
${userName!''} ${text!''} |