1、首先建一个word,插入一个表格,需要填充的值用${parame}代替
(注意:这里的参数要和java实体类里面的参数对应起来,代码放在下面)
2、制作完成后另存为xml格式
3、然后用文本编辑工具打开这个xml文件,复制源码
4、 打开:https://mp.csdn.net/mp_blog/creation/editor/131155433,在线格式化xml文件
5、复制到xml文件,然后将名称改为:exam.ftl 。这里后缀名也需要变更,如图
6、项目目录结构:
7、OK,模板制作完成开始搞代码,pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>greate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>greate</name>
<description>greate</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--freemarker模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 构建pdf-->
<dependency>
<groupId>wiki.xsx</groupId>
<artifactId>x-easypdf</artifactId>
<version>2.9.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<!-- doc转pdf-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
<scope>system</scope>
<systemPath>${basedir}/lib/aspose-words-15.8.0.jar</systemPath>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
8、填充表格的实体类:Exam.java、GradeVo.java
package com.example.greate.model;
import lombok.Data;
@Data
public class GradeVo {
private String name;
private String code;
private int chinese;
private int mathematics;
private int english;
private int synthesize;
private int information;
private int total;
}
package com.example.greate.model;
import lombok.Data;
import java.util.List;
@Data
public class Exam {
private String date;
private String desc;
private List<GradeVo> gradeList;
}
9、生成pdf工具类:GeneratePdfUtil.java
package com.example.greate.util;
import com.aspose.words.License;
import com.example.greate.model.Exam;
import com.example.greate.model.GradeVo;
import freemarker.template.Version;
import io.micrometer.common.util.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import freemarker.core.XMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import wiki.xsx.core.pdf.convertor.XEasyPdfConvertor;
public class GeneratePdfUtil {
private static final Logger log = LogManager.getLogger(GeneratePdfUtil.class);
public static void main(String[] args) throws IOException {
GeneratePdfUtil.acceptList();
}
/**
* 高考成绩单
* @throws IOException
*/
public static void acceptList() throws IOException {
String fileName = "高考成绩单";
Exam exam = new Exam();
List<GradeVo> list = new ArrayList<>();
GradeVo vo1 = new GradeVo();
vo1.setName("张三");
vo1.setCode("GK000001");
vo1.setChinese(100);
vo1.setMathematics(120);
vo1.setEnglish(120);
vo1.setSynthesize(180);
vo1.setInformation(60);
vo1.setTotal(580);
GradeVo vo2 = new GradeVo();
vo2.setName("李四");
vo2.setCode("GK000002");
vo2.setChinese(120);
vo2.setMathematics(130);
vo2.setEnglish(125);
vo2.setSynthesize(180);
vo2.setInformation(65);
vo2.setTotal(620);
list.add(vo1);
list.add(vo2);
exam.setDate("2023年06月11日");
exam.setDesc("省高校招生办");
exam.setGradeList(list);
createDocByObj(exam,fileName,"exam.ftl");
}
/**
* 根据模板生成word文档
*
* @param obj map中一定要有filePath键值对
* @param fileName 文件名称
* @param templates 模板文件
* @throws IOException
*/
public static String createDocByObj(Object obj,String fileName,String templates) throws IOException {
String saveFilePath = "F:\\";
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("classpath:templates");
if (StringUtils.isEmpty(saveFilePath)) {
throw new IOException("保存文件路径不存在!");
}
if (templates == null) {
throw new IOException("未获取到模板文件,请确认路径是否正确!");
}
String ftlName = templates;
Version v = new Version("2.3.0",true,new Date());
Configuration configuration = new Configuration(v);
configuration.setDefaultEncoding("utf-8");
configuration.setOutputFormat(XMLOutputFormat.INSTANCE);
configuration.setDirectoryForTemplateLoading(resource.getFile());
String outFileName = "";
if(fileName.contains(".doc")){
outFileName = fileName;
}else{
outFileName = fileName+".doc";
}
Template t = configuration.getTemplate(ftlName);
String of = saveFilePath + "/" + outFileName;
File df = new File(saveFilePath);
if (!df.exists()) {
df.mkdir();
}
File outFile = new File(of);
log.info("文件名称:" + outFileName + ",文件路径:" + outFile);
Writer out = null;
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try {
fos = new FileOutputStream(outFile);
osw = new OutputStreamWriter(fos, "utf-8");
out = new BufferedWriter(osw);
t.process(obj, out);
String filePath = saveFilePath+outFileName;
docTransitionPdf(filePath,filePath.replace(".doc",".pdf"));
} catch (Exception e) {
log.error("根据模板生成word文档:", e);
} finally {
try {
out.close();
osw.close();
fos.close();
//删除doc文件
if(outFile.exists()){
log.info("删除:{}",outFileName);
outFile.delete();
}
} catch (Exception e) {
log.error("关闭文件流异常:",e);
}
}
return saveFilePath+outFileName.replace(".doc",".pdf");
}
/**
* word文档转pdf文件
* @param Address 要不转化的文档地址
* @param pdfName pdf名称
*/
public static void docTransitionPdf(String Address, String pdfName) throws IOException {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return;
}
log.info("==XEasyPdfConvertor start");
XEasyPdfConvertor.toPdf(Address, pdfName);
log.info("==XEasyPdfConvertor end");
}
/**
* 验证证书
* @return
*/
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = GeneratePdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
log.error("获取license失败:", e);
}
return result;
}
}
10、运行代码,生成pdf文件如图: