需求:使用到itextpdf添加图片功能生成一个新的pdf
相关Maven:
<itext.version>7.1.17</itext.version>
<html2pdf.version>3.0.5</html2pdf.version>
<!-- iText Core -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>${itext.version}</version>
<type>pom</type>
</dependency>
<!-- iText pdfHTML add-on -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>${html2pdf.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>${itext.version}</version>
</dependency>
生成新PDF的代码:
/**
* PDF合并签字图片
*
* @param sourcePath 源PDF路径
* @param destPath 合成图片后PDF路径
* @param imgPath 图片路径
* @param pageNum 页面
* @param x x
* @param y y
* @return
* @author shadow
* @date 2022-02-28 20:35:55
*/
public static String pressImage(String sourcePath, String destPath, String imgPath, Integer pageNum, Integer x, Integer y) {
try {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourcePath), new PdfWriter(destPath));
Document document = new Document(pdfDocument);
ImageData imageData = ImageDataFactory.create(imgPath);
Image image = new Image(imageData).scaleAbsolute(268, 100)
.setFixedPosition(pageNum, x, y);
document.add(image);
document.close();
return destPath;
} catch (Exception e) {
log.error("PDF合成图片失败", e);
}
return null;
}
问题:
使用main方法跑厕所时,不会报错,能够正常运行.但是启动springboot,前端调用的时候,
PdfDocument pdfDocument = new PdfDocument(new PdfReader(sourcePath), new PdfWriter(destPath));
上面这句代码会导致项目直接挂掉.部分报错信息如下:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGBUS (0xa) at pc=0x00007ff80797aad0, pid=19792, tid=0x0000000000008657
#
# JRE version: Java(TM) SE Runtime Environment (8.0_202-b08) (build 1.8.0_202-b08)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.202-b08 mixed mode bsd-amd64 compressed oops)
# Problematic frame:
# C [libsystem_platform.dylib+0xad0] _platform_memmove$VARIANT$Haswell+0xf0
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# If you would like to submit a bug report, please visit:
# <http://bugreport.java.com/bugreport/crash.jsp>
解决:
网上找了诸多文档,大多都是说是系统对打开文件数量限制导致的,修改limits文件;但是我修改了也无用.最后看到这篇文章,里面说到使用流的方式操作文件,改了后就调用项目就不会挂掉了.
最终的代码:
public static String pressImage(String sourcePath, String destPath, String imgPath, Integer pageNum, Integer x, Integer y) {
try {
PdfDocument pdfDocument = new PdfDocument(new PdfReader(Files.newInputStream(new File(sourcePath).toPath())), new PdfWriter(Files.newOutputStream(new File(destPath).toPath())));
Document document = new Document(pdfDocument);
ImageData imageData = ImageDataFactory.create(imgPath);
Image image = new Image(imageData).scaleAbsolute(268, 100)
.setFixedPosition(pageNum, x, y);
document.add(image);
document.close();
return destPath;
} catch (Exception e) {
log.error("PDF合成图片失败", e);
}
return null;
}