当前位置:网站首页>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);
}
}
边栏推荐
- 【网络方向实训】-企业园区网络设计-【Had Done】
- nacos 问题
- JVM(4) 字节码技术+运行期优化
- 技术保证质量,软件测试的这些测试方法你都掌握了吗?
- 通过MeterSphere和DataEase实现项目Bug处理进展实时跟进
- 一小时构建示例场景 声网发布灵隼物联网云平台
- npm ERR! fatal: early EOF npm ERR! fatal: index-pack failed
- npm ERR! fatal: early EOF npm ERR! fatal: index-pack failed
- 聊聊eureka的delta配置
- Common knowledge of ECS security settings
猜你喜欢

npm ERR! fatal: early EOF npm ERR! fatal: index-pack failed

Classic illustration of K-line diagram (Collection Edition)

JVM (2) garbage collection

Where is the win11 installation permission set? Win11 installation permission setting method

【观察】软通动力刘天文:拥抱变化“顺势而为”,做中国数字经济“使能者”...

mysql远程连接

Why is informatization ≠ digitalization? Finally someone made it clear

创作者基金会 6 月份亮点

MBA-day26 数的概念与性质

shell bash脚本注意:单行末尾转义符 \ 后千万不能有其他无关字符(多行命令)
随机推荐
剑指 Offer 66. 构建乘积数组
ASP.Net Core创建Razor页面上传多个文件(缓冲方式)(续)
Win11系统频繁断网怎么办?Win11网络不稳定的解决方法
From CIO to Consultant: the transformation of it leaders
有了这4个安全测试工具,对软件安全测试say so easy!
NLP - GIZA++ 实现词对齐
After CDN is added to the website, the Font Icon reports an error access control allow origin
KDD 2022 | 協同過濾中考慮錶征對齊和均勻性
KDD 2022 | 协同过滤中考虑表征对齐和均匀性
Installation and configuration of MariaDB
3-3主机发现-四层发现
罗清启:高端家电已成红海?卡萨帝率先破局
Shell bash script note: there must be no other irrelevant characters after the escape character \ at the end of a single line (multi line command)
Flutter 2.0 FocusScope. of(context). The requestfocus (focusnode()) does not take effect
Canonical engineers are trying to solve the performance problem of Firefox snap
startService() 过程
How important is it to make a silver K-line chart?
Win11安装权限在哪里设置?Win11安装权限设置的方法
云服务器的安全设置常识
正则表达式系列之手机号码正则