使用 itextpdf 合并图片生成 pdf 文件的步骤如下:
- 导入 itextpdf 的 jar 包
- 创建一个 Document 对象
- 创建一个 PdfWriter 对象, 并将其与 Document 对象关联
- 打开 Document 对象
- 循环添加图片到 Document 对象中
- 关闭 Document 对象
以下是一个示例代码:
<!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.2</version>
</dependency>
public static boolean mergeImages(List<String> images, File newFile) {
boolean retValue = false;
// 创建一个 Document 对象
Document document = new Document();
try {
// 创建一个 PdfWriter 对象, 并将其与 Document 对象关联
PdfWriter.getInstance(document, new FileOutputStream(newFile));
// 打开 Document 对象
document.open();
// 循环添加图片到 Document 对象中
for (int i = 0; i < images.size(); i++) {
// 创建图片对象
Image image = Image.getInstance(images.get(i));
//设置图片位置的x轴和y轴
//image.setAbsolutePosition(0, 0); // 相对于上面获取到的坐标,位于左下角
//设置图片的宽度和高度
image.scalePercent(60, 60);
// 将图片添加到 Document 对象中
document.add(image);
}
retValue = true;
} catch (DocumentException | IOException e) {
log.error("", e);
} finally {
// 关闭 Document 对象
document.close();
}
return retValue;
}





