public void exportTest(HttpServletResponse response, String templatePath, Map<String, String> pdfMap, Collection<String> imgFiledNames) {
// 字节流 pdf相关
PdfReader reader = null;
OutputStream outputStream = null;
int[] pageNumToCopy = {1,2};
try {
// 获取模板的数据
//URL resourceUrl = classLoader.getResource(templatePath);
String filePath = "/home/software/accInfo.pdf";//resourceUrl.getPath();
//String filePath = "E:\\desop\\user\\src\\main\\resources\\pdf\\accInfo.pdf";
//resourceUrl.getPath();
System.out.println("filePath"+filePath);
FileInputStream inputStream = new FileInputStream(filePath);
// 读取PDF模板表单
reader = new PdfReader(inputStream);
// 字节数组流,用来缓存文件流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 根据模板表单生成一个新的PDF
PdfStamper pdfStamper = new PdfStamper(reader,byteArrayOutputStream);
// 获取新生成的PDF表单
AcroFields acroFields = pdfStamper.getAcroFields();
// 给表单生成中文字体,这里采用系统字体,不设置的话,中文显示会有问题
// 我也不知道为啥加个 ",1" ,用的本地字体不加不行;(评论里有个哥们说是这个是字体文件中指定的具体的文字类型的索引)
BaseFont baseFont = BaseFont.createFont("/usr/share/fonts/wqy-microhei/wqy-microhei.ttc" + ",1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//com.itextpdf.text.DocumentException: Font 'STSong-Light' with 'UniGb-UCS2-H' is not recognized.
//BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGb-UCS2-H", BaseFont.EMBEDDED);
acroFields.addSubstitutionFont(baseFont);
// 图片字段不为空
boolean imgFiledNamesNotEmpty = CollectionUtil.isNotEmpty(imgFiledNames);
pdfMap.forEach((fieldName, value) -> {
// 图片要单独处理
if (imgFiledNamesNotEmpty && imgFiledNames.contains(fieldName)) {
// 图片处理
try {
int pageNo = acroFields.getFieldPositions(fieldName).get(0).page;
Rectangle signRect = acroFields.getFieldPositions(fieldName).get(0).position;
//根据Url读取图片
Image image = Image.getInstance(new URL(value));
//图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
image.setAbsolutePosition(signRect.getLeft(), signRect.getBottom());
//获取图片页面
PdfContentByte pdfContentByte = pdfStamper.getOverContent(pageNo);
//添加图片
pdfContentByte.addImage(image);
} catch (Exception e) {
// 异常处理
throw new RuntimeException(e);
}
} else {
// 设置普通文本数据
try {
acroFields.setField(fieldName, value);
System.out.println(acroFields.getField(fieldName));
} catch (Exception e) {
// 异常处理
throw new RuntimeException(e);
}
}
});
// 表明该PDF不可修改
pdfStamper.setFormFlattening(true);
// 关闭资源
pdfStamper.close();
// 响应头的输出流
outputStream = response.getOutputStream();
// 将ByteArray字节数组中的流输出到out中(即输出到浏览器)
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, outputStream);
doc.open();
for (int pageNum : pageNumToCopy){
copy.addPage(copy.getImportedPage(new PdfReader(byteArrayOutputStream.toByteArray()),pageNum));
}
doc.close();
} catch (Exception e) {
// 异常处理
throw new RuntimeException(e);
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (reader != null) {
reader.close();
}
} catch (Exception e) {
// 异常处理
throw new RuntimeException(e);
}
}
}