1,引入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2,controller方法
@PostMapping("/exportUserPdf")
@Permission
public ApiResult<Object> exportUserPdf(HttpServletResponse response,@RequestBody StarOrderRelation starOrderRelation){
StarOrderRelation starOrderRelation1=consumerService.getStarRelationByOrderNo(starOrderRelation);
if(starOrderRelation1==null){
return ApiResult.newSuccess(ApiResultCode.COMMON_PARAM_NULL);
}
Order order1=orderService.selectByOrderNo(starOrderRelation.getOrderNo());
String randomPath = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomStringUtils.randomNumeric(4);
String savePath="";
if(StringUtils.isNullString(order1.getUsrSignature()) ){
return ApiResult.newSuccess(ApiResultCode.COMMON_PARAM_NULL);
}
try {
Map<String,String> map = new HashMap<>();
map.put("fill_1",starOrderRelation1.getPatientName());
map.put("fill_2",starOrderRelation1.getPatientSex()==1?"男":"女");
//...
map.put("fill_12",starOrderRelation1.getContacterNumber());
map.put("image",order1.getUsrSignature());
savePath="/opt";
String fileName=randomPath+".pdf";
String templateType="exportUserPdf";
PDFUtil.exportMapMZydPdf( map,"/用户需求协议.pdf",savePath,fileName,templateType);
} catch (DocumentException e) {
e.printStackTrace();
}
String fullPath = savePath +"/"+ randomPath + ".pdf";
//todo上传阿里云返回url操作
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("file", FileUtil.file(fullPath));
String result= HttpUtil.post("https://.........//隐藏//...../upload/file", paramMap);
String url ="";
if ("200".equals(JSONObject.parseObject(result).get("code").toString())){
// FileUtil.del(destPath);
url = JSONObject.parseObject(result).get("dataMap").toString();
}
//使用文件流下载pdf文件
// File file = new File(fullPath);
// if (file.exists()) {
// String fileName = file.getName();
// response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
// response.setCharacterEncoding("utf-8");
// response.setContentType("application/pdf");
// download(response, file);
// }
return ApiResult.newSuccess(url);
}
//下载文件流方法
public void download(HttpServletResponse response, File file) {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
bis.close();
fis.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3,PDFUtil类
package com.xiangban.utils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
//java项目 www.fhadmin.org
public class PDFUtil {
public static void exportMapMZydPdf(Map<String,String> map, String templatePath, String savePath, String fileName,String templateType) throws DocumentException {
ByteArrayOutputStream byteArrayOutputStream = null;
PdfReader pdfReader = null;
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(savePath+"//"+fileName);
byteArrayOutputStream = new ByteArrayOutputStream();
pdfReader = new PdfReader(templatePath);
PdfStamper pdfStamper = new PdfStamper(pdfReader, byteArrayOutputStream);
//获取模板所有域参数
AcroFields acroFields = pdfStamper.getAcroFields();
//解决中文字体不显示的问题
BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontArrayList = new ArrayList<BaseFont>();
fontArrayList.add(baseFont);
acroFields.setSubstitutionFonts(fontArrayList);
if(templateType.equals("exportUserPdf")) {
acroFields.setField("fill_1", map.get("fill_1"));
acroFields.setField("fill_2", map.get("fill_2"));
acroFields.setField("fill_3", map.get("fill_3"));
acroFields.setField("fill_4", map.get("fill_4"));
acroFields.setField("fill_5", map.get("fill_5"));
acroFields.setField("fill_6", map.get("fill_6"));
acroFields.setField("fill_7", map.get("fill_7"));
acroFields.setField("fill_8", map.get("fill_8"));
acroFields.setField("fill_9", map.get("fill_9"));
acroFields.setField("fill_10", map.get("fill_10"));
acroFields.setField("fill_11", map.get("fill_11"));
acroFields.setField("fill_12", map.get("fill_12"));
}
if(templateType.equals("exportNursePdf")) {
acroFields.setField("fill_1", map.get("fill_1"));
acroFields.setField("fill_2", map.get("fill_2"));
acroFields.setField("fill_3", map.get("fill_3"));
acroFields.setField("fill_4", map.get("fill_4"));
acroFields.setField("fill_5", map.get("fill_5"));
acroFields.setField("fill_6", map.get("fill_6"));
acroFields.setField("fill_7", map.get("fill_7"));
acroFields.setField("fill_8", map.get("fill_8"));
acroFields.setField("fill_9", map.get("fill_9"));
acroFields.setField("fill_10", map.get("fill_10"));
acroFields.setField("fill_11", map.get("fill_11"));
acroFields.setField("fill_12", map.get("fill_12"));
acroFields.setField("fill_13", map.get("fill_13"));
acroFields.setField("fill_14", map.get("fill_14"));
acroFields.setField("fill_15", map.get("fill_15"));
}
// 插入图片
if(!StringUtils.isNullString(map.get("image"))) {
AcroFields.FieldPosition position = acroFields.getFieldPositions("fill_image").get(0);
int pageNo = position.page;
Rectangle signRect = position.position;
float x = signRect.getLeft();
float y = signRect.getBottom();
// 读图片
Image image = Image.getInstance(map.get("image"));
// 获取操作的页面
PdfContentByte under = pdfStamper.getOverContent(pageNo);
// 根据域的大小缩放图片
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
pdfStamper.setFormFlattening(true);//如果为false那么生成的PDF文件还能编辑,一定要设为true
pdfStamper.flush();
pdfStamper.close();
//设置纸张,可以在Excel制作是设定好纸张大小
Document doc = new Document(PageSize.A5);
PdfCopy copy = new PdfCopy(doc,fileOutputStream);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(byteArrayOutputStream.toByteArray()), 1);
try {
copy.addPage(importPage);
} catch (BadPdfFormatException e) {
e.printStackTrace();
}
doc.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (pdfReader != null) {
pdfReader.close();
}
}
}
}
4,使用Adobe Acrobat Pro DC打开pdf文档,在工具中搜索“域”,找到准备表单,选择识别表单域,编辑域,有部分表单域会识别不到,需要我们手动去添加,选择 添加文本域 ,标记出一块区域出来,并命名,这块区域就是我们新添加的域;本文这里图片的域名称命名为了image;记好所有域之后,保存模板
5,将pdf模板放入项目resources文件夹下以供使用。
6,运行接口调试,使用文件流下载pdf文件,或上传至云存储空间得到文件链接。