<!-- 添加2個依賴 html2image 把html轉換成圖片格式 freemarker模板引擎-->
<dependency>
<groupId>gui.ava</groupId>
<artifactId>html2image</artifactId>
</dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
// 在yml 文件中設置Freemarker模板參數
spring: profiles: active: dev ## 設定ftl文件路徑 freemarker: template-loader-path: classpath:/templates ##是否開啟緩存 cache: false ##設置編碼格式 charset: utf-8 ##檢查模板路徑是否存在 check-template-location: true ##請求頭格式 content-type: text/html expose-request-attributes: false expose-session-attributes: false request-context-attribute: request suffix: .html path: /data/image/skc/images/FreemarkerTemplates.html
//模板文件 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div style=" width: 333px; height: 585px; padding: 36px 0 0; box-sizing: border-box; background: #f8f3ea url(http://xxxx/miniapp/logo.png); no-repeat: center / cover; text-align: center; border-radius: 10px; text-align: center; line-height: 1; " > <img style="height: 20px" src="http://xxxx/miniapp/logo.png" alt /> <p style=" margin-block-start: 0; margin-block-end: 0; margin-inline-start: 0px; margin-inline-end: 0px; padding-top: 30px; font-size: 18px; font-weight: 400; color: #333333; line-height: 1; letter-spacing: 2px; " > 您的專屬qq顧問 </p> <div style=" margin: 20px auto 35px; width: 34px; height: 2px; background: #cb8831; " ></div> <img style="margin: 0 auto; width: 111px; height: 111px; border-radius: 50%" src=${FreemarkerFormVO.avatar} alt="" /> <div style=" padding-top: 10px; font-size: 21px; font-weight: 500; color: #333333; line-height: 30px; letter-spacing: 2px; " > ${FreemarkerFormVO.userName} </div> <div style=" padding: 5px 0; font-size: 15px; font-weight: 400; color: #333333; " > ${FreemarkerFormVO.department} </div> <img style="margin: 40px auto 10px; width: 110px; height: 110px" src=${FreemarkerFormVO.qrCode} alt="" /> <div style=" font-size: 13px; font-weight: 400; color: #333333; line-height: 24px; letter-spacing: 2px; " > 請加我的QQ </div> </div> </body> </html>
/**
* 接口調用層
* FreemarkerFormVO 入參實體類,對應index.html 中需要替換的參數
*/
@ApiOperation(value="模板") @PostMapping("/freemarker") public ResponseEntity<ResultBean<String>> freemarkerIndex(@Valid @RequestBody FreemarkerFormVO bean, Model model) { model.addAttribute("FreemarkerFormVO",bean); Map<String, FreemarkerFormVO> root = new HashMap(1); root.put("FreemarkerFormVO", bean); String filePath = freeMarkerContent(root); try { File file = ResourceUtils.getFile(filePath); String html = FileReader.create(file).readString(); String s = switchToPic(html); s= s.replaceAll("\\r\\n", ""); base64StringToImage(s); return ResultBeanUtil.success(s); } catch (Exception e) { log.error("", e); } return ResultBeanUtil.success(filePath); } //測試的時候 生成到D盤的AMD文件夾下 private String freeMarkerContent(Map<String, FreemarkerFormVO> root) { try { Template temp = cfg.getTemplate("index.html"); //以classpath下面的static目錄作為靜態頁面的存儲目錄,同時命名生成的靜態html文件名稱 // File pathFile = new File(path.substring(path.indexOf('/'))); File pathFile = new File("D:\\AMD\\FreemarkerTemplates.html"); if (!pathFile.getParentFile().exists()) { pathFile.getParentFile().mkdirs(); } Writer file = new FileWriter(pathFile); temp.process(root, file); file.flush(); file.close(); return "D:\\AMD\\FreemarkerTemplates.html"; } catch (IOException | TemplateException e) { log.error(e.getMessage(), e); } return null; } //變成base64格式 private String switchToPic(String html) { HtmlImageGenerator imageGenerator = new HtmlImageGenerator(); imageGenerator.getBufferedImage(); // File path=new File(html); // String urlPath=path.toURL().toString(); // imageGenerator.loadUrl(urlPath); imageGenerator.loadHtml(html); //這里如果指定了盤符,可以直接存在本地,自己本地寫demo的話可以用 String imageName = imagePath + "html1.png"; imageGenerator.saveAsImage(imageName); BufferedImage buffimg = imageGenerator.getBufferedImage(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ImageIO.write(buffimg, "png", os); } catch (Exception e) { e.printStackTrace(); } byte[] bytes1 = os.toByteArray(); return encoder.encodeBuffer(bytes1).trim(); } //base64轉圖片,生成到指定目錄 private void base64StringToImage(String base64) { try { byte[] bytes1 = decoder.decodeBuffer(base64); ByteArrayInputStream bais = new ByteArrayInputStream(bytes1); BufferedImage bi1 = ImageIO.read(bais); File f = new File("D:\\AMD\\html.png"); ImageIO.write(bi1, "png", f); } catch (IOException e) { e.printStackTrace(); } }