解决思路
在application.yml文件中配置三个文件地址:分别是文字模版地址、文件模版地址、目标生成地址
pom.xml
<!--生成PDF-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
application.yml
pdf:
fontPath: D:\***\***\src\main\resources\static\common\pdf\font\font1.ttf
templatePath: D:\***\***\src\main\resources\static\common\pdf\doc\1111.pdf
targetPath: D:\tools\
需要在项目部署服务器上创建文件夹并将这两个模版文件放进去,如果POM文件有过滤.ttf文件的,将其注释,最后将服务器返回的储存地址保存到相应字段。
模板文件需要用到专业的PDF编辑工具,所需的文件也可以直接去我的资源里下载
PDF生成工具类
package com.***.***.***.controller.pdf;
import cn.afterturn.easypoi.pdf.PdfExportUtil;
import cn.afterturn.easypoi.pdf.entity.PdfExportParams;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.***.***.***.dao.model.AgreementEntity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class PdfImageGenerate {
public static final String PDF_DATA_MAP = "PDF_DATA_MAP";
public static final String PDF_IMG_MAP = "PDF_IMG_MAP";
//生成Excel表格型PDF
public static File savePdfImg(String id) {
try {
List<AgreementEntity> studentList = new ArrayList<AgreementEntity>();
AgreementEntity agreementEntity = new AgreementEntity();
String fileName="common/pdf/doc/"+id+".pdf";
agreementEntity.setName("团队绑定协议");
agreementEntity.setImage("static/common/img/500.png");
studentList.add(agreementEntity);
PdfExportParams params = new PdfExportParams("协议");
File file = new File(fileName);
file.createNewFile();
PdfExportUtil.exportPdf(params, AgreementEntity.class, studentList, new FileOutputStream(file));
return file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 利用模板生成pdf
public static void pdfout(String fontPath, Map<String, Object> o, String templatePath, String destPath) {
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
// BaseFont bf = BaseFont.createFont("common/pdf/font/font1.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
out = new FileOutputStream(destPath);
reader = new PdfReader(templatePath);
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//文字类的内容处理
Map<String, String> datemap = (Map<String, String>) o.get(PDF_DATA_MAP);
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
}
//图片类的内容处理
Map<String, String> imgmap = (Map<String, String>) o.get(PDF_IMG_MAP);
for (String key : imgmap.keySet()) {
String value = imgmap.get(key);
String imgpath = value;
int pageNo = form.getFieldPositions(key).get(0).page;
Rectangle signRect = form.getFieldPositions(key).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
//根据路径读取图片
Image image = Image.getInstance(imgpath);
//获取图片页面
PdfContentByte under = stamper.getOverContent(pageNo);
//图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
stamper.close();
Document doc = new Document();
Font font = new Font(bf, 32);
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (IOException e) {
System.out.println(e);
} catch (DocumentException e) {
System.out.println(e);
}
}
}
调用时
第一步调用PDF生成方法
@Value("${pdf.fontPath}")
private String fontPath;//文字模版地址
@Value("${pdf.templatePath}")
private String templatePath;//文件模版地址
@Value("${pdf.targetPath}")//目标地址
private String targetPath;
...
String destPath = targetPath+id+".pdf";//目标地址
Map<String, String> map = new HashMap();
map.put("fill_1", "张三");
map.put("fill_2", "李四");
map.put("fill_3", "男");
map.put("fill_4", "这里是住址信息");
Map<String, String> map2 = new HashMap();
map2.put("image", "http://106.12.157.128:89/login/common/img/fw.png");
Map<String, Object> o = new HashMap();
o.put(PdfImageGenerate.PDF_DATA_MAP, map);
o.put(PdfImageGenerate.PDF_IMG_MAP, map2);
PdfImageGenerate.pdfout(fontPath,o, templatePath, destPath);
第二部 将生成的PDF文件从生成目标地址上传到目标服务器
FileSystemResource resource = new FileSystemResource(new File(destPath));
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
param.add("system", "lab");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(param, headers);
String recv = restTemplate.postForObject(uploadUrl, files, String.class);
第三部 将服务器返回的文件保存地址取出并保存到指定表
JSONObject jsonObject = JSONObject.parseObject(recv);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray fileList = data.getJSONArray("fileList");
String filePath = "";
if (fileList.size() > 0) {
JSONObject object = JSONObject.parseObject(fileList.get(0).toString());
filePath = object.getString("filePath");
}
info.put("treatyUrl", filePath);
int totls = teamLabShareService.saveTreatyUrl(info);