前言

之前写了两篇关于动态模板转pdf和word的文章:《模板文件转pdf打印》、《模板文件转word打印》,最近又接到一个需求需要转图片,所以本文做下记录。

如何开始

thymeleaf 依赖包

<!-- thymeleaf -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--html2image-->
<dependency><groupId>gui.ava</groupId><artifactId>html2image</artifactId><version>2.0.1</version>
</dependency>

thymeleaf配置

spring:# thymeleafthymeleaf:prefix: classpath:/templates/check-template-location: truesuffix: .htmlencoding: UTF-8mode: HTMLcache: falseservlet:content-type: text/html

模板准备,此处模板和导出pdf、word的模板一样。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.w3.org/1999/xhtml" layout:decorator="layout">
<head lang="en"><title>Spring Boot Demo - PDF</title><style>@page {size: 210mm 297mm; /*设置纸张大小:A4(210mm 297mm)、A3(297mm 420mm) 横向则反过来*/margin: 0.25in;padding: 1em;@bottom-center{content:"葫芦科技 © 版权所有";font-family: SimSun;font-size: 12px;color:red;};@top-center { content: element(header) };@bottom-right{content:"第" counter(page) "页  共 " counter(pages) "页";font-family: SimSun;font-size: 12px;color:#000;};}body{font-family: 'SimSun'}h2{color: crimson}#myheader{width: 500px;height: 22px;border: 1px solid #000000;}table, th , td  {border: 1px solid grey;border-collapse: collapse;padding: 5px;}table tr:nth-child(odd) {background-color: #f1f1f1;}table tr:nth-child(even) {background-color: #ffffff;}#input1{border-bottom: 1px solid #000000;}</style>
</head>
<!--这样配置不中文不会显示-->
<!--<body style="font-family: 宋体">-->
<body style="font-family: 'SimSun'">
<div>1.标题-中文</div>
<h2 th:text="${title}"></h2><div>2.按钮:按钮的边框需要写css渲染</div>
<button class="a" style="border: 1px solid #000000"> click me t-p</button>
<div id="divsub"></div><div>3.普通div</div>
<div id="myheader">Alice's Adventures in Wonderland</div><div>4.图片 绝对定位到左上角(注意:图片必须用全路径或者http://开头的路径,否则无法显示)</div>
<img th:src="${imageUrl}"/><div>5.普通table表格</div>
<div><table style="width: 700px"><tr><th>姓名</th><th>昵称</th><th>年龄</th></tr><tr th:each="info : ${demoList}"><td th:text="${info.name}"></td><td th:text="${info.nick}"></td><td th:text="${info.age}"></td></tr></table></div><div>6.input控件,边框需要写css渲染 (在模板中一般不用input,因为不存在输入操作)</div>
<div><label>姓名:</label><input id="input1" aria-label="葫芦胡" type="text" value="葫芦胡"/>
</div>
</body>
</html>

文件位置

模板位置放在templates目录下,宋体包放在static目录下,如下:

核心处理类

工具类

/*** @Description html模板转jpg* @Author gourd.hu* @Date 2020/6/28 10:43* @Version 1.0*/
@Slf4j
public class ImageUtil {public static void saveAsImage(TemplateEngine templateEngine, String templateName, Map<String,Object> variables, String filePath){// 声明一个上下文对象,里面放入要存到模板里面的数据final Context context = new Context();context.setVariables(variables);//imageHtml为获取的html源码字符串String imageHtml = templateEngine.process(templateName, context);Html2Image html2Image = Html2Image.fromHtml(imageHtml);ImageRenderer imageRenderer = html2Image.getImageRenderer();imageRenderer.saveImage(filePath);}public static void download(TemplateEngine templateEngine, String templateName, Map<String,Object> variables, HttpServletResponse response, String fileName ){// 断言参数不为空ResponseEnum.TEMPLATE_DATA_NULL.assertNotEmpty(variables);// 声明一个上下文对象,里面放入要存到模板里面的数据final Context context = new Context();context.setVariables(variables);// 设置编码、文件ContentType类型、文件头、下载文件名response.setCharacterEncoding("utf-8");response.setContentType("image/jpeg");ServletOutputStream outputStream = null;try {response.setHeader("Content-Disposition", "attachment;fileName=" +new String(fileName.getBytes("gb2312"), "ISO8859-1"));outputStream = response.getOutputStream();} catch (UnsupportedEncodingException e) {log.error(e.getMessage(), e);} catch (IOException e) {log.error(e.getMessage(), e);}//imageHtml为获取的html源码字符串String imageHtml = templateEngine.process(templateName, context);Html2Image html2Image = Html2Image.fromHtml(imageHtml);ImageRenderer imageRenderer = html2Image.getImageRenderer();imageRenderer.saveImage(outputStream,Boolean.TRUE);}
}

controller测试入口

 /*** image下载到特定位置**/@GetMapping(value = "/image/save")@ApiOperation(value="image下载到特定位置")public BaseResponse<String> imageSave() {Map<String,Object> variables = new HashMap<>(4);variables.put("title","image下载到特定位置!");variables.put("imageUrl",sslEnabled?"https://localhost:10001/imgs/sg.jpg":"http://localhost:10001/imgs/sg.jpg");List<Map<String,String>> demoList = new ArrayList<>();Map<String,String> demoMap = new HashMap<>(8);demoMap.put("name","哈哈");demoMap.put("nick","娃娃");demoMap.put("age","19");Map<String,String> demoMap2 = new HashMap<>(8);demoMap2.put("name","天天");demoMap2.put("nick","饭饭");demoMap2.put("age","14");demoList.add(demoMap);demoList.add(demoMap2);variables.put("demoList",demoList);// pdf文件下载位置String pdfPath = CommonUtil.isLinux() ? pdfLinuxPath : pdfWindowsPath +  "test0.png";ImageUtil.saveAsImage(templateEngine,"pdfPage",variables,pdfPath);return BaseResponse.ok("image保存成功");}/*** image浏览器下载**/@GetMapping(value = "/image/download")@ApiOperation(value="image浏览器下载")public BaseResponse<String> imageDownload(HttpServletResponse response) {Map<String,Object> variables = new HashMap<>(4);variables.put("title","image浏览器下载!");variables.put("imageUrl",sslEnabled?"https://localhost:10001/imgs/sg.jpg":"http://localhost:10001/imgs/sg.jpg");List<Map<String,String>> demoList = new ArrayList<>();Map<String,String> demoMap = new HashMap<>(8);demoMap.put("name","哈哈");demoMap.put("nick","娃娃");demoMap.put("age","19");Map<String,String> demoMap2 = new HashMap<>(8);demoMap2.put("name","天天");demoMap2.put("nick","饭饭");demoMap2.put("age","14");demoList.add(demoMap);demoList.add(demoMap2);variables.put("demoList",demoList);ImageUtil.download(templateEngine,"pdfPage",variables,response,"test.jpg");return BaseResponse.ok("image保存成功");}

避坑

在Linux服务器上,图片会出现乱码情况,原因是lunix上没有宋体的字体包,我们需要将宋体包simsun.ttf 上传到Linux服务器的 /usr/share/fonts 目录下,如图:

测试效果

结语

至此,导出图片功能就完成了,如果本文有错误的地方,欢迎评论指正。

===============================================

代码均已上传至本人的开源项目
cloud-plus:https://blog.csdn.net/HXNLYW/article/details/104635673

《SpringBoot2.0 实战》系列-整合thymeleaf 实现模板文件转图片相关推荐

  1. 《SpringBoot2.0 实战》系列-整合thymeleaf 实现模板文件转word打印

    前言 最近,有小伙伴看了我的<模板文件转pdf打印>文章后,私信问我,有没有转word的demo.当时只能遗憾的说没有.所以就有了这篇文章. 如何开始 thymeleaf 依赖包 < ...

  2. WF4.0实战系列索引

    从WF4.0 betal1出来的时候就开始使用WF4.0,由于资料不多,学习过程也非常艰苦.今年四月份的时候打算写WF4.0实战系列,由于今年是本命年故坚持写了24篇文章.这个系列的文章都有一个特点, ...

  3. 《SpringBoot2.0 实战》系列-整合FlyingSaucer + thymeleaf 实现模板文件转pdf打印

    前言 最近,接到一个模板打印pdf的任务,后来网上找了很多案例,本文做下记录. 如何开始 添加依赖包 <!-- thymeleaf --> <dependency><gr ...

  4. SpringBoot2.0之四 简单整合MyBatis

    从最开始的SSH(Struts+Spring+Hibernate),到后来的SMM(SpringMVC+Spring+MyBatis),到目前的S(SpringBoot),随着框架的不断更新换代,也为 ...

  5. springboot2.0 多数据源整合问题 At least one JPA metamodel must be present!   at

    2019独角兽企业重金招聘Python工程师标准>>> 数据源代码: 第一个读取配置文件代码: package com.datasource;import org.apache.ib ...

  6. 《SpringBoot2.0 实战》系列-整合kafka实现消息发送、消费

    之前写过一篇关于ActiveMq的博文,有兴趣的小伙伴可以点击查看.但是ActiveMq总体性能表现一般,如果对消息队列性能要求较高,业务量较大,那我们需要重新考量.本文就介绍一款性能高的消息队列- ...

  7. elasticsearch 分页_[Springboot实战系列]整合ElasticSearch实现数据模糊搜索

    前言 本文介绍了如何整合搜索引擎elasticsearch与springboot,对外提供数据查询接口. 业务介绍 我的个人网站需要对mysql数据库内存储的京东商品进行模糊查询(模仿淘宝商品搜索), ...

  8. SpringBoot2.0之三 优雅整合Spring Data JPA

      在我们的实际开发的过程中,无论多复杂的业务逻辑到达持久层都回归到了"增删改查"的基本操作,可能会存在关联多张表的复杂sql,但是对于单表的"增删改查"也是不 ...

  9. SparkSQL(Spark-1.4.0)实战系列(一)——DataFrames基础

    主要内容 本教程中所有例子跑在Spark-1.4.0集群上 DataFrames简介 DataFrame基本操作实战 DataFrames简介 本文部分内容译自https://databricks.c ...

最新文章

  1. 代理 Delegeta
  2. java保留两位小数_java使double保留两位小数的多方法 java保留两位小数
  3. mysql buffer size_优化mysql之key_buffer_size设置
  4. mysql代码生成器_MYSQL语句生成器
  5. java百度云推送demo_百度云推送java服务端maven安装完整demo
  6. 结构主题模型(一)stm包工作流
  7. linux dd命令制作软盘,制作Linux启动软盘的四种方法
  8. CentOS7 下调教mysql记实 之一
  9. Reddit前CEO黄易山:马斯克不懂言论自由的挑战
  10. frp源码剖析-frp中的log模块
  11. 计算机科学 —— 冯诺依曼结构
  12. 购物车的简单添加与计算
  13. 基于python及图像识别的围棋棋盘棋子识别3——耗时优化(一行代码速度提高600倍)
  14. C#网络编程之基础语法 网络流(NetworkStream) 文本流(Stream) 文件流(Filestream )
  15. (批处理)批量文件夹重命名,要求是在原文件夹名前加上英文字母前缀aa
  16. 自动化接口实战(一)
  17. 浅谈后缀自动机SAM
  18. c语言函数定义时涉及的基本要素是什么,C语言基础:函数的定义与调用
  19. Android项目实战--手机卫士
  20. 战双帕弥什登入显示服务器错误,战双帕弥什渠道账号登录失败/安装失败/提示新版本/卡顿闪退FAQ大全[多图]...

热门文章

  1. mysql 存储过程 循环拼接字符串
  2. Fireworks MX 2004 制作简单动画 飞鸟翅膀煽动的动画
  3. jsp获取java处理结果_JSP Cookie 处理
  4. EndNote X5的附件(File Attachments)问题
  5. linux dns劫持转发,linux的dns被劫持(解决方案)
  6. mysql建库建表全过程20201215
  7. 利用文本编辑器判断dll/exe是否为64位
  8. 前后端分离微服务管理系统项目实战SaaS-HRM项目(二)——数据库设计与前端框架
  9. R语言学堂推文索引-v5.8.1
  10. 绝了!关系抽取新SOTA