1.导包:
<!--FreeMarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aspose.words/aspose-words-jdk16 -->
<dependency>
<groupId>com.aspose.words</groupId>
<artifactId>aspose-words-jdk16</artifactId>
<version>14.6.0.0</version>
</dependency>
<repositories>
<repository>
<id>aspose-words-jdk16</id>
<url>https://maven.atlassian.com/3rdparty</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
引入:aspose-words-15.8.0-jdk16.jar
2>数据、包都在云盘上(免费提取哦)
链接:https://pan.baidu.com/s/1KzuXyUBHQK-zGTECu7g7gQ
提取码:eqgv
代码走起
1.工具类
package com.nwpusct.csal.common.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;
import java.io.*;
/**
* freemarker + word模板 导出word
*
* @author bobo
* @date 2019/4/14 17:41
*/
public class FreemarkeExportrWordUtil {
/** 默FreeMarker配置实例 */
private static final Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
/** 默认采用UTF-8编码 */
private static final String ENCODING = "UTF-8";
/** buffer */
private static final int BUFFER_SIZE = 1024;
/**
* 从指定freemarker模板所在文件夹
*
* “/” 对应 classpath
* “/templates/” 对应 classpath下的templates/
*/
private static final String DEFAULT_POSITION = "/";
static {
configuration.setDefaultEncoding(ENCODING);
}
/**
* 导出excel
*
* @param templateFileName
* 模板文件名(含后缀,如:abc.ftl)
* @param resultFileAllPathName
* 结果文件全路径文件名 (如: C:/Users/result.doc 再如: C:/Users/result.docx)
* @param dataObject
* 与模板中的占位符 对应的 数据信息(一般为:一个专门创建的对象, 或者是Map)
* @return 生成的word文件
* @throws IOException
* @throws TemplateException
* @date 2019/4/16 10:52
*/
public static File doExport(String templateFileName, String resultFileAllPathName, Object dataObject)
throws IOException, TemplateException {
return doExport(templateFileName, DEFAULT_POSITION, resultFileAllPathName, dataObject);
}
/**
* 导出excel
*
* @param templateFileName
* 模板文件名(含后缀,如:abc.ftl)
* @param templateFileDir
* 模板文件所在位置名(如: "/" 代表 classpath)
* @param resultFileAllPathName
* 结果文件全路径文件名 (如: C:/Users/result.doc 再如: C:/Users/result.docx)
* @param dataObject
* 与模板中的占位符 对应的 数据信息(一般为:一个专门创建的对象, 或者是Map)
* @return 生成的word文件
* @throws IOException
* @throws TemplateException
* @date 2019/4/16 10:52
*/
public static File doExport(String templateFileName, String templateFileDir,
String resultFileAllPathName, Object dataObject)
throws IOException, TemplateException {
// 指定模板文件所在 位置
configuration.setClassForTemplateLoading(FreemarkeExportrWordUtil.class, templateFileDir);
// 根据模板文件、编码;获取Template实例
Template template = configuration.getTemplate(templateFileName, ENCODING);
File resultFile = new File(resultFileAllPathName);
// 判断要生成的word文件所在目录是否存在,不存在则创建
if (!resultFile.getParentFile().exists()) {
boolean result = resultFile.getParentFile().mkdirs();
}
// 写出文件
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(resultFile));
Writer writer = new BufferedWriter(osw, BUFFER_SIZE)) {
template.process(dataObject, writer);
}
return resultFile;
}
/**
* 获取图片对应的base64码
*
* @param imgFile
* 图片
* @return 图片对应的base64码
* @throws IOException
* @date 2019/4/16 17:05
*/
public static String getImageBase64String(File imgFile) throws IOException {
InputStream inputStream = new FileInputStream(imgFile);
byte[] data = new byte[inputStream.available()];
int totalNumberBytes = inputStream.read(data);
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}
2.接口
@ApiOperation(value = "pdf文档导出")
@RequestMapping(value = "getExportPdf", method = RequestMethod.GET)
public RestResult<String> getExportPdf(@RequestParam(value = "infoId") String infoId) {
try {
NdeReportInfo ndeReportInfo = ndeReportInfoMapper.selectById(infoId);
String reportParmeter = ndeReportInfo.getReportParmeter();
// 模板文件名
String templateFileName = "\\templates\\4-18.ftl";
// 要生成的文件 全路径文件名E:\learn\SecurityTest\src\main\resources\importWord
String fileName =
"\\learn\\SecurityTest\\src\\main\\resources\\importWord\\" + new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".doc";
JSONArray jsonArray = new JSONArray(reportParmeter);
Map<String, Object> datas = new HashMap<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray tables = jsonObject.getJSONArray("tables");
List<Map<String, Object>> list = new ArrayList<>();
datas.put("table" + i, list);
for (int j = 0; j < tables.length(); j++) {
JSONObject jsonObject1 = tables.getJSONObject(j);
JSONObject tbs = jsonObject1.getJSONObject("tbody");
JSONArray trsTbs = tbs.getJSONArray("trs");
for (int k = 0; k < trsTbs.length(); k++) {
JSONObject jsonTrs = trsTbs.getJSONObject(k);
JSONArray tds = jsonTrs.getJSONArray("tds");
Map<String, Object> tempMap = new HashMap<>();
Integer string = jsonTrs.getInt("loop");
if (string == 1) {
int line = 0;
for (int l = 0; l < tds.length(); l++) {
JSONObject jsonTds = tds.getJSONObject(l);
String type = jsonTds.getString("type");
if (type.equals("input")) {
String value = jsonTds.getString("value");
tempMap.put("Td" + line, value);
line++;
} else if (type.equals("label")) {
String value1 = jsonTds.getString("label_chn");
String value2 = jsonTds.getString("label_en");
tempMap.put("Td" + line, value1);
line++;
tempMap.put("Td" + line, value2);
line++;
}
}
list.add(tempMap);
}
if (string == 0) {
for (int l = 0; l < tds.length(); l++) {
JSONObject jsonTds = tds.getJSONObject(l);
String type = jsonTds.getString("type");
if (type.equals("input")) {
if (jsonTds.getString("filed").equals("examinationTo")) {
String value = jsonTds.getString("value");
datas.put("examinationTo", value);
}
if (jsonTds.getString("filed").equals("commissionNo")) {
String value = jsonTds.getString("value");
datas.put("commissionNo", value);
}
if (jsonTds.getString("filed").equals("reportNo")) {
String value = jsonTds.getString("value");
datas.put("reportNo", value);
}
}
}
}
}
}
}
try {
File imageFile = new File(ndeReportInfo.getSketch());
datas.put("myImage",
FreemarkeExportrWordUtil.getImageBase64String(imageFile));
} catch (
IOException e) {
e.printStackTrace();
}
//保存word
FreemarkeExportrWordUtil.doExport(templateFileName, fileName, datas);
File wordFile = new File(fileName);
if (!wordFile.exists()) {
return RestResultUtil.failed("文件不存在");
}
try {
//获取文件
File file = new File("\\learn\\SecurityTest\\src\\main\\resources\\importPdf\\"
+ new SimpleDateFormat("yyyyMMddHHmm").format(new Date()) + ".pdf");
//获取文件流
FileOutputStream os = new FileOutputStream(file);
// Address是将要被转化的word文档
Document doc = new Document(fileName);
// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
doc.save(os, SaveFormat.PDF);
//删除word原始文件
//File fileDelete = new File(fileName);
//fileDelete.delete();
return RestResultUtil.genSuccessResult(httpPath + file.getPath().replaceAll("\\\\", "/"));
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return RestResultUtil.failed("导出失败");
}
初次使用,大神莫怪,多提宝贵意见,共同学习!!!谢谢