1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package com.yiboshi.science.utils;
import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;
import freemarker.cache.ClassTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;
public class HtmlBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(HtmlBuilder.class);
private ThreadLocal<Map<String, Object>> map = ThreadLocal.withInitial(HashMap::new);
private FreeMarkerConfigurer freeMarkerConfigurer;
public HtmlBuilder(FreeMarkerConfigurer freeMarkerConfigurer) {
this.freeMarkerConfigurer = freeMarkerConfigurer;
}
public static boolean loop(List<String> list, String value) {
for (String str : list) {
if (Objects.equals(str, value)) {
return true;
}
}
return false;
}
public void exportWord(Object dataModel, HttpServletRequest request, HttpServletResponse response) {
String url = request.getRequestURL().toString();
String s2 = url.substring(0,url.indexOf("v1"));
Map<String, Object> data1 = obj2Map(dataModel);
//这里是根据数据替换模板中的字段并返回一个字符串
String html = getHtmlText("tmp-pov.html",data1);
//对html中的中文进行Unicode编码,这里是最关键的一步,必须,不然导出的wordoffice打开乱码
html = EncodingUtil.setUrlForChn(html.replace("img src=\"","img src=\""+s2));
System.out.println(html);
String encodedFileName = "";
InputStream inputStream = new ByteArrayInputStream(html.getBytes());
FileDownloadUtil.download(inputStream, request, response, encodedFileName);
}
public static String getDomainName(String url) {
String host = "";
try {
URL Url = new URL(url);
host = Url.getHost();
} catch (Exception e) {
e.printStackTrace();
}
return host;
}
private static Map<String, Object> obj2Map(Object obj) {
Map<String, Object> map = new HashMap<String, Object>();
// 获取f对象对应类中的所有属性域
Field[] fields = obj.getClass().getDeclaredFields();
for (int i = 0, len = fields.length; i < len; i++) {
String varName = fields[i].getName();
// varName = varName.toLowerCase();//将key置为小写,默认为对象的属性
try {
// 获取原来的访问控制权限
boolean accessFlag = fields[i].isAccessible();
// 修改访问控制权限
fields[i].setAccessible(true);
// 获取在对象f中属性fields[i]对应的对象中的变量
Object o = fields[i].get(obj);
// if (o != null)
map.put(varName, o);
// 恢复访问控制权限
fields[i].setAccessible(accessFlag);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
return map;
}
/**
* 生成html文件
*
* @param htmlFile html文件
* @param templateName 模板名
*/
public File convertHtml(File htmlFile, String templateName) {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
BeansWrapper myWrapper = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
template.setObjectWrapper(myWrapper);
fos = new FileOutputStream(htmlFile);
osw = new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8");
bw = new BufferedWriter(osw);
// template.process(getRootMap(), bw);
// getRootMap().clear();
} catch (Exception e) {
LOGGER.error("FREEMARKER - create html by template error with templateName : " + templateName, e);
} finally {
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(osw);
IOUtils.closeQuietly(bw);
}
return htmlFile;
}
/**
* 生成html模板字符串
*
* @return 模板字符串
*/
public String getHtmlText(String templateName,Map<String, Object> map) {
String htmlText = "";
try {
// 通过指定模板名获取FreeMarker模板实例
Configuration configuration = freeMarkerConfigurer.getConfiguration();
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(this.getClass(), "/template");
configuration.setTemplateLoader(new ClassTemplateLoader(this.getClass(), "/template"));
Template tpl = configuration.getTemplate(templateName, "utf-8");
htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);
map.clear();
} catch (Exception e) {
LOGGER.error("FREEMARKER - create html by template error with templateName : " + templateName, e);
}
return htmlText;
}
public FreeMarkerConfigurer getFreeMarkerConfigurer() {
return freeMarkerConfigurer;
}
public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
this.freeMarkerConfigurer = freeMarkerConfigurer;
}
}