需要将数据写入模板,并转成pdf格式上传服务器保存,查询一些资料,以及参考前辈留下的部分代码,总结了一下自己的这次学习的过程,以及功能代码,记录一下:
声明:本次仅为学习和探讨,Aspose.Words 为商用软件,为避免纠纷,如需商用,还是建议请购买正版.
Aspose.Words这个组件的功能很强大,可以直接保存docx、doc、pdf等,基本能够满足日常的学习使用,具体使用方法如下:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.9</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.9.jar</systemPath>
</dependency>
然后是工具类,工具类的作用就是注册一下证书(不然处理后的word会有水印),不想用工具类的可以在调用组件写入数据之前,用工具类里面的代码简单注册一下就行,只是工具类会更加简洁,工具类代码:
@Component
public class AsposeWordUtil implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(AsposeWordUtil.class);
public static boolean loadLicense() {
boolean result = false;
try {
InputStream license = AsposeWordUtil.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(license);
result = true;
} catch (Exception e) {
logger.error("Aspose license load error:", e);
}
return result;
}
@Override
public void run(String... args) throws Exception {
loadLicense();
}
}
还需要一个证书(license.xml)用来去掉水印,文章底部的链接会提供jar包、证书、工具类等
比如说模板长这样:
然后就是功能代码:
//为了方便理解,我手动创建一个实体对象,比如
User user = new User();
user.setName("YANG");
user.setAge(18);
user.setAddress("贝克街221B");
//这里我是需要pdf格式的文件,就保存pdf了
public String toPDFUrl(User user) throws Exception {
String url = "";
Map<String, String> textMap = new HashMap<>();
//为了简单,模板里的字段我就用A,B,C,D这种了,具体写的时候可以严谨一点
textMap.put("A",user.getName());//姓名
textMap.put("B",user.getAge());//年龄
textMap.put("C",user.getAddress());//地址
textMap.put("D","2022-12-13");//时间 转化为xx年xx月xx日
//这里是模板地址templateFilePath是自己配置的全局变量,File.separator是File类提供的/,确保在不同操作系统不会报错,XXX模板.docx就是要写入的模板名称
String mb = templateFilePath + File.separator +"XXX模板.docx";
Document doc = new Document(mb);
//调用下面的替换方法
replaceAll(doc, textMap);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//这里是保存为PDF格式,这里可以进入SaveFormat里面看一下可以直接save很多格式
doc.save(bos, SaveFormat.PDF);
//也可以直接像下面这种保存,下面第一句就是保存为pdf格式,第二句就是保存docx格式
//doc.save("D:\\Template1.pdf");
//doc.save("D:\\Template1.docx");
//这里是一个封装的上传方法,需提供byte数组和保存的格式
url = storageUtil.upload(bos.toByteArray(), "pdf");
return url;
}
public static void replaceAll(Document document, Map<String, String> textMap) {
FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
textMap.forEach((k, v) -> {
try {
document.getRange().replace(k, v, options);
} catch (Exception e) {
log.error("替换失败!", e);
}
});
}
调用方法之后就会变成下面这样: