当前位置:网站首页>freemarker模板框架生成图片
freemarker模板框架生成图片
2022-06-29 19:44:00 【ywl470812087】
freemarker框架生成图片使用
// 模板代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Document</title>
<style>
body{
width: 420px;
margin:0;
padding:0;
text-align: center;
}
header {
background-color: #1c2327;
width: 420px;
padding: 20px 0;
}
content {
width: 420px;
}
content .tips {
background-color: #1c2327;
margin: 40px 30px 10px;
padding: 10px;
position: relative;
}
content .tips p{
color: #ffffff;
font-family: PingFang SC;
font-size: 16px;
font-weight: 400;
}
content .tips .icon {
width: 40px;
height: 40px;
position: absolute;
color: #1C2327;
background-color: #FFDA2D;
top: -20px;
left: 160px;
border-radius: 20px;
line-height: 40px;
}
.tips-highlight {
color: #FCD82D
}
content p {
font-size: 14px;
color: #6d6d70;
}
content p.title, p.number, div.input {
color:#1c2327;
font-size: 24px;
font-weight: bold;
}
content p span.label {
color: #89898B;
font-size: 16px;
font-weight: bold;
}
content div.input {
font-size: 16px;
font-weight: bold;
background-color: #F3F3F3;
margin: 0 30px;
height: 30px;
line-height: 30px;
}
content div.list {
font-size: 12px;
background-color: #F3F3F3;
margin: 0 30px;
line-height: 10px;
padding: 10px 0;
}
content div.list div.item {
width: 48%;
display: inline-block;
line-height:20px;
}
</style>
</head>
<body >
<header>
<img src="./img/logo.png"></img>
</header>
<content>
<div class="tips">
<div class="icon">!</div>
<p>Es importante que conserves el numero de folio del comp rob ante.</p>
<p>Puedes solicitar que el <span class="tips-highlight">Punto RABEE</span> te lo envie o <span class="tips-highlight">tomar fotos</span> de esta pantalla.</p>
</div>
<p class="title"> Comp rob ante de Dropoff </p>
<p class="time">${misSendOutScanRecord.serialNumberTime}</p>
<p class="number"> 34guias </p>
<p>
<span class="label">Punto RABEE:</span>${misSendOutScanRecord.deptName}.${misSendOutScanRecord.deptId}
</p>
<p>
<span class="label">Responsable:</span>${misSendOutScanRecord.operator}.${misSendOutScanRecord.createBy}
</p>
<p>Folio</p>
<div class="input">${misSendOutScanRecord.serialNumber}</div>
<p>Numeros de guia RABEE</p>
<div class="list">
<#if waybillNos??>
<#foreach waybillNo in waybillNos>
<div class="item">${waybillNo}</div>
</#foreach>
</#if>
</div>
</content>
</body>
</html>
package com.rabee.common.utils;
import com.lowagie.text.pdf.BaseFont;
import com.rabee.common.utils.http.HttpUtils;
import com.rabee.common.utils.image.B64ImgReplacedElementFactory;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
public class FreemarkerUtils {
private String getTemplate(String template, Map<String,Object> map) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
cfg.setClassForTemplateLoading(this.getClass(), "/template/image");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
Template temp = cfg.getTemplate(template);
StringWriter stringWriter = new StringWriter();
temp.process(map, stringWriter);
stringWriter.flush();
stringWriter.close();
String resutl = stringWriter.getBuffer().toString();
return resutl;
}
public byte[] generate(String template, Map<String,Object> map)throws Exception {
String html = getTemplate(template, map);
byte[] bytes=html.getBytes();
ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(bin);
Java2DRenderer renderer = new Java2DRenderer(document,480,-1);
BufferedImage img = renderer.getImage();
return imageToBytes(img);
}
private byte[] imageToBytes(BufferedImage bImage) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, "png", out);
} catch (IOException e) {
//log.error(e.getMessage());
}
return out.toByteArray();
}
public String turnImage(String template, Map<String,Object> map, HttpServletResponse response) throws Exception {
String html = getTemplate(template, map);
byte[] bytes=html.getBytes();
ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(bin);
Java2DRenderer renderer = new Java2DRenderer(document,480,850);
BufferedImage img = renderer.getImage();
// 生成图片名字
String uuid = UUID.randomUUID().toString();
renderer.getSharedContext().setReplacedElementFactory(new B64ImgReplacedElementFactory());
renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(1);
BufferedImage image = renderer.getImage();
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// 可以输出到流
ImageIO.write(image, "jpg", outputStream);
// 也可以直接保存到文件
ImageIO.write(image, "jpg", new File("E:\\java\\"+ uuid + ".jpg"));
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
} catch (Exception e) {
throw new Exception("桌牌图片转换失败");
}
}
public String turnImage(String template, Map<String,Object> map, int width, int height) throws Exception {
String html = getTemplate(template, map);
byte[] bytes=html.getBytes();
ByteArrayInputStream bin=new ByteArrayInputStream(bytes);
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(bin);
Java2DRenderer renderer = new Java2DRenderer(document,width,height);
BufferedImage img = renderer.getImage();
// response.setContentType("image/jpeg;charset=UTF-8");
// response.setDateHeader("expries", -1);
// response.setHeader("Cache-Control", "no-cache");
// response.setHeader("Pragma", "no-cache");
// ImageIO.write(img, "jpg", response.getOutputStream());
// final FSImageWriter imageWriter = new FSImageWriter();
// imageWriter.setWriteCompressionQuality(1.0f);
// 生成图片名字
String uuid = UUID.randomUUID().toString();
// 输出路径
// imageWriter.write(img, "E:\\java\\" + uuid + ".jpg");
// ImageIO.write(img, "jpg", response.getOutputStream());
renderer.getSharedContext().setReplacedElementFactory(new B64ImgReplacedElementFactory());
renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(1);
BufferedImage image = renderer.getImage();
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
// 可以输出到流
ImageIO.write(image, "jpg", outputStream);
// 也可以直接保存到文件
ImageIO.write(image, "jpg", new File("E:\\java\\"+ uuid + ".jpg"));
return Base64.getEncoder().encodeToString(outputStream.toByteArray());
} catch (Exception e) {
throw new Exception("桌牌图片转换失败");
}
}
/**
* 通过模板导出pdf文件
* @param data 数据
* @param templateFileName 模板文件名
* @throws Exception
*/
public ByteArrayOutputStream createPDF(Map<String, Object> data, String templateFileName) throws Exception {
// 创建一个FreeMarker实例, 负责管理FreeMarker模板的Configuration实例
Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
// 指定FreeMarker模板文件的位置
cfg.setClassForTemplateLoading(this.getClass(), "/template/ceetificate/");
ITextRenderer renderer = new ITextRenderer();
OutputStream out = new ByteArrayOutputStream();
try {
// 设置 css中 的字体样式(暂时仅支持宋体和黑体) 必须,不然中文不显示
renderer.getFontResolver().addFont("/template/ceetificate/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 设置模板的编码格式
cfg.setDefaultEncoding("UTF-8");
// 获取模板文件
Template template = cfg.getTemplate(templateFileName, "UTF-8");
StringWriter writer = new StringWriter();
// 将数据输出到html中
template.process(data, writer);
writer.flush();
String html = writer.toString();
// 把html代码传入渲染器中
renderer.getSharedContext().setReplacedElementFactory(new B64ImgReplacedElementFactory());
renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);
renderer.setDocumentFromString(html);
System.setProperty("java.net.useSystemProxies", "true");
renderer.layout();
renderer.createPDF(out, false);
renderer.finishPDF();
out.flush();
return (ByteArrayOutputStream)out;
} finally {
if(out != null){
out.close();
}
}
}
public static void main(String[] args) {
String res = HttpUtils.sendGet("https://maps.googleapis.com/maps/api/staticmap","center=20.7140616,-103.3612198&size=600x300&markers=color:red%7C20.7140616,-103.3612198&key=AIzaSyCauC0gY3UaaBEuzsic78QdzZWvcgTPJ6w");
System.out.println(res);
}
}
边栏推荐
- How is the combination of convolution and transformer optimal?
- 软件测试逻辑覆盖相关理解
- jfinal中如何使用过滤器监控Druid监听SQL执行?
- NLP 类问题建模方案探索实践
- 7.取消与关闭
- 并查集(Union-Find)
- Arm 全面计算解决方案重新定义视觉体验强力赋能移动游戏
- shell bash脚本注意:单行末尾转义符 \ 后千万不能有其他无关字符(多行命令)
- QC protocol + Huawei fcp+ Samsung AFC fast charging 5v9v chip fs2601 application
- Docker compose deploy the flask project and build the redis service
猜你喜欢

福昕软件受邀亮相2022先进制造业数智发展论坛

3-3主機發現-四層發現

Classic illustration of K-line diagram (Collection Edition)

洞见科技作为「唯一」隐私计算数商,「首批」入驻长三角数据要素流通服务平台

通过MeterSphere和DataEase实现项目Bug处理进展实时跟进

ASP.Net Core创建Razor页面上传多个文件(缓冲方式)(续)

细说GaussDB(DWS)复杂多样的资源负载管理手段

What about frequent network disconnection of win11 system? Solution to win11 network instability

There are more than 20 databases in a MySQL with 3306 ports. How can I backup more than 20 databases with one click and do system backup to prevent data from being deleted by mistake?

云服务器的安全设置常识
随机推荐
4-2端口Banner信息获取
4-2 port banner information acquisition
云服务器的安全设置常识
7.取消与关闭
Technical methodology of new AI engine under the data infrastructure upgrade window
JVM (4) Bytecode Technology + Runtime Optimization
Canonical engineers are trying to solve the performance problem of Firefox snap
Kdd 2022 | prise en compte de l'alignement et de l'uniformité des représentations dans le Filtrage collaboratif
Rejected by a large company? Tencent experts summarized 11 reasons for being rejected!
Connaissance générale des paramètres de sécurité du serveur Cloud
技术保证质量,软件测试的这些测试方法你都掌握了吗?
Win11 system component cannot be opened? Win11 system widget cannot be opened solution
测试方法学习
细说GaussDB(DWS)复杂多样的资源负载管理手段
【U盘检测】为了转移压箱底的资料,买了个2T U盘检测仅仅只有47G~
WPS和Excele
[boutique] detailed explanation of Pinia
How to use filters in jfinal to monitor Druid for SQL execution?
What if the win11 policy service is disabled? Solution to disabling win11 policy service
【Proteus仿真】矩阵键盘中断扫描