添加依赖:
<!-- freemarker生成word文件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.aspose.cells</groupId>
<artifactId>aspose-cells</artifactId>
<version>20.4 - c</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-20.4 - c.jar</systemPath>
</dependency>
<dependency>
<groupId>com.aspose.words</groupId>
<artifactId>aspose-words</artifactId>
<version>words-18.10-jdk16</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jar</systemPath>
</dependency>
freemarker生成WORD的工具类
package com.vxdata.pdf.aspose.utils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
@Component
public class WordUtil {
/**
* 存放模板的目录
*/
@Value("${word2pdf.templatePath}")
private String templatePath;
/**
* 生成 word 文档方法
*
* @param dataMap 要填充的数据
* @param templateName 模版名称.ftl (只有名称)
* @param fileName 要输出的文件路径 xxx/xxx/xxx.doc
* @throws Exception 抛出的异常
*/
public void createWord(Map<String, Object> dataMap, String templateName, String fileName) throws Exception {
// 设置FreeMarker的版本和编码格式
Configuration configuration = new Configuration(new Version("2.3.28"));
configuration.setDefaultEncoding("UTF-8");
// 设置FreeMarker生成Word文档所需要的模板的路径
configuration.setDirectoryForTemplateLoading(new File(templatePath));
// 此处把模版文件都放在 resources 下的 templates 中
// configuration.setClassForTemplateLoading(WordUtils.class, "/templates");
// 设置FreeMarker生成Word文档所需要的模板
Template tem = configuration.getTemplate(templateName, "UTF-8");
// 创建一个Word文档的输出流
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));
// FreeMarker使用Word模板和数据生成Word文档
tem.process(dataMap, out);
out.flush();
out.close();
}
}
注意点
生成图片: 需要base64格式, 先用图片占位, 调整好格式, 然后把图片的base64换成占位符
生成复选框: 整体替换, 不要一个个替换
aspose 生成PDF的工具类
Jar包:
链接:https://pan.baidu.com/s/1YKXbt13w-Bu6-h1TjFTX9A
提取码:ci5q
破解文件: license.xml
aspose需要破解, 破解文件要放在resources下
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
package com.vxdata.pdf.aspose.utils;
import com.aspose.words.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import java.io.FileOutputStream;
import java.io.InputStream;
/**
* 使用Aspose将word转成pdf
*
* @author sunhongyun
*/
@Slf4j
@Component
public class Word2PdfUtil {
/**
* 破解方法
* 需要jar包: aspose-words-15.12.0-jdk16.jar
* 同时配置 license.xml
*
* @return
*/
private static boolean getLicense() {
boolean result = false;
try {
InputStream is = new ClassPathResource("/license.xml").getInputStream();
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* word 转 pdf
*
* @param inputPath word文件path(全路径)
* @param outPath pdf文件path(全路径)
* @return
*/
public Boolean word2pdf(String inputPath, String outPath) {
try (FileOutputStream os = new FileOutputStream(outPath)) {
if (getLicense()) {
Document doc = new Document(inputPath);
doc.save(os, SaveFormat.PDF);
return true;
}
log.error("转换失败!", "破解失败");
return false;
} catch (Exception e) {
log.error("转换失败!", e);
return false;
}
}
}
调用工具类
package com.vxdata.pdf.aspose.service.impl;
import com.vxdata.pdf.aspose.service.IPdfService;
import com.vxdata.pdf.aspose.utils.Word2PdfUtil;
import com.vxdata.pdf.aspose.utils.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.UUID;
@Component
public class PdfServiceImpl implements IPdfService {
@Autowired
private WordUtil wordUtil;
@Autowired
private Word2PdfUtil word2PdfUtil;
@Value("${word2pdf.tmpPath}")
private String tmpPath;
/**
* 生成pdf
*
* @param map 数据
* @param response 返回流
* @param templateFileName 模板名称
*/
@Override
public void word2pdf(Map<String, Object> map, HttpServletResponse response, String templateFileName) {
long start = System.currentTimeMillis();
try {
// word与pdf的随机文件名
String tmpFile = tmpPath + File.separator + UUID.randomUUID().toString();
String wordFileName = tmpFile + ".docx";
String pdfFileName = tmpFile + ".pdf";
// 生成word
wordUtil.createWord(map, templateFileName, wordFileName);
// 生成pdf
Boolean flag = word2PdfUtil.word2pdf(wordFileName, pdfFileName);
if (flag) {
byte[] buf = new byte[8 * 1024];
int len = 0;
try (InputStream is = new FileInputStream(pdfFileName); OutputStream os = response.getOutputStream();) {
while ((len = is.read(buf, 0, buf.length)) != -1) {
os.write(buf, 0, len);
}
os.flush();
} finally {
try {
deleteFile(wordFileName);
deleteFile(pdfFileName);
} catch (Exception e) {
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("pdf转换成功,共耗时:" + +(end - start) / 1000.0);
}
/**
* 删除文件
*
* @param filePath 文件
* @return
*/
public static boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
}