万事第一步引包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
第二步准备word模板,另存为.xml的形式
word模板图:
然后将word模板另存为.xml
使用 NotePad++ 打开 xml 文件
可以使用在线格式化工具进行格式化
xml内容部分截图:
最后保存为 FreeMarker 的模板文件,后缀为 ftl 格式,拷贝到项目中。不要用中文
替换数据
将要替换的数据放进map中
在模板中找到需要替换的位置,图片是base64的字符串
文本以此类推
然后调用下载工具类进行下载即可。
涉及工具类
图片转base64
public String getImageStr(String imgUrl) {
InputStream in = null;
byte[] data = null;
if (StringUtils.isNotEmpty(imgUrl) && !imgUrl.startsWith("http")) {
imgUrl = "http:" + imgUrl;
}
if (StringUtils.isEmpty(imgUrl)) {
//可以给默认图
return "";
} else {
try {
in = getInputStreamByUrl(imgUrl);
} catch (Exception e) {
logger.error("加载图片未找到", e);
e.printStackTrace();
}
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
logger.error("IO操作图片错误", e);
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public InputStream getInputStreamByUrl(String strUrl) {
HttpURLConnection conn = null;
try {
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(20 * 1000);
final ByteArrayOutputStream output = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), output);
return new ByteArrayInputStream(output.toByteArray());
} catch (Exception e) {
logger.error("getInputStreamByUrl 异常,exception is {}", e);
} finally {
try {
if (conn != null) {
conn.disconnect();
}
} catch (Exception e) {
}
}
return null;
}