目录
- 需求说明
- 前期准备
- Spring Boot 集成
- 添加依赖
- 构建工具类
- 构建MultipartFile
- 编辑PDF模板
- Java代码设置对应form的key-value
需求说明
根据合同模板,将动态的合同标签,合同方以及合同签约时间等动态的生成PDF,供用户下载打印。
前期准备
安装 Adobe Acrobat DC
链接:https://pan.baidu.com/s/1xkIioIBDG4uLBGP20SZJEA
提取码:yn8g
Spring Boot 集成
添加依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
<scope>compile</scope>
</dependency>
<!--中文问题解决-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
构建工具类
public class PDFUtils {
private static final Logger log = LoggerFactory.getLogger(PDFUtils.class);
/**
* 根据pdf模板输出流
* @param templateFileName 模板文件名
* @param resultMap 包含文件字段名和值的map
* @return 生成的文件字节流
*/
public static ByteArrayOutputStream createPdfStream(String templateFileName,
Map<String, String> resultMap){
ByteArrayOutputStream ba = new ByteArrayOutputStream();
PdfStamper stamp =null;
PdfReader reader = null;
try {
reader = new PdfReader(templateFileName);
stamp = new PdfStamper(reader, ba);
//使用字体
BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
/* 获取模版中的字段 */
AcroFields form = stamp.getAcroFields();
//填充表单
if (resultMap != null) {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
form.setFieldProperty(entry.getKey(), "textfont", bf, null);
form.setField(entry.getKey(), entry.getValue()!=null?entry.getValue():"");
}
}
//不能编辑
stamp.setFormFlattening(true);
} catch (IOException e) {
log.error("文档构建I/O异常",e);
} catch (DocumentException e) {
log.error("文档构建异常",e);
}
finally {
if(stamp!=null){
try {
stamp.close();
} catch (DocumentException e) {
log.error("流关闭错误",e);
} catch (IOException e) {
log.error("流关闭错误",e);
}
}
if(reader!=null){
reader.close();
}
}
return ba;
}
}
构建MultipartFile
方便之后上传OSS返回url
public UploadFileModel createUrl(String filePath, ByteArrayOutputStream byteArrayOutputStream) throws URISyntaxException {
try{
byte[] pdfBytes = byteArrayOutputStream.toByteArray();
MultipartFile multipartFile = new MockMultipartFile(
"file",
filePath,
"application/pdf",
pdfBytes
);
return uploadFileUtil.upload(multipartFile);
} catch (Exception e) {
log.error("创建Url时出错:" + e.getMessage());
}
return null;
}
编辑PDF模板
Java代码设置对应form的key-value
pdf模板放在springboot 项目目录resources/static 目录下
public String createContract(CreateContractRequest request) {
HashMap<String, String> map = new HashMap<>();
map.put("companyName",request.getCompanyName());
map.put("phone",request.getPhone());
UploadFileModel url = null;
ByteArrayOutputStream pdfStream = PDFUtils.createPdfStream(UserApplication.class.getResource("/").getPath() + "static/contract.pdf", map);
try {
url = createUrl("合同.pdf", pdfStream);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return url.getUrl();
}