前言:
因工作中需要用到pdf文件合并,遂编写了合并pdf代码的功能,以此记载,方便后续使用,本次采用的是PDFBox(Apache 官方开源库,稳定、无版权、代码简单)。

什么是PDFBox?
Apache PDFBox 库是一个开源的 Java 工具,用于使用 PDF文档。该项目允许创建新的 PDF 文档,操作现有文档 文档以及从文档中提取内容的能力。Apache PDFBox 还包含若干内容 命令行工具。
下来我们就来讲解详细步骤
第一步:添加Maven依赖
<dependencies>
<!-- PDFBox 合并PDF核心依赖 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.30</version> <!-- 稳定版 -->
</dependency>
</dependencies>
第二步:编写工具类
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.io.File;
/**
* PDF合并工具类
*
* @author 首席摸鱼师
* @date 2026-3-24 10:16:43
*/
@Slf4j
public class PdfMergeUtil {
/**
* 合并pdf
*
* @param pdfMergePath 合并后文件路径
* @param pdfPaths 多个pdf文件路径
*/
public static void pdfMerge(String pdfMergePath, String... pdfPaths) {
if (ObjectUtil.isEmpty(pdfPaths) || ObjectUtil.isEmpty(pdfMergePath)) {
throw new RuntimeException("文件路径不能为空");
}
try {
// 创建PDF合并工具
PDFMergerUtility merger = new PDFMergerUtility();
for (String pdfPath : pdfPaths) {
merger.addSource(new File(pdfPath));
}
// 设置输出文件路径
merger.setDestinationFileName(pdfMergePath);
// 执行合并
merger.mergeDocuments();
log.debug("✅ PDF合并完成!文件路径:" + pdfMergePath);
} catch (Exception e) {
log.error("❌ PDF合并失败:");
e.printStackTrace();
}
}
}
第三步:编写测试方法
public static void main(String[] args) {
pdfMerge("E:\\data\\test.pdf", "E:\\data\\1.pdf", "E:\\data\\2.pdf");
}
运行后结果如下,文件成功合并为一个

如果我们的pdf是来自网络文件呢,只需稍加改造工具类
/**
* 合并pdf
*
* @param pdfMergePath 合并后文件路径
* @param pdfUrls 多个pdf网络路径
*/
public static void pdfMergeByUrl(String pdfMergePath, String... pdfUrls) {
if (ObjectUtil.isEmpty(pdfUrls) || ObjectUtil.isEmpty(pdfMergePath)) {
throw new RuntimeException("文件路径不能为空");
}
try {
// 创建PDF合并工具
PDFMergerUtility merger = new PDFMergerUtility();
for (String pdfUrl : pdfUrls) {
// 打开网络流,直接添加到合并器
InputStream is = new URL(pdfUrl).openStream();
merger.addSource(is);
}
// 设置输出文件路径
merger.setDestinationFileName(pdfMergePath);
// 执行合并
merger.mergeDocuments();
log.debug("✅ PDF合并完成!文件路径:" + pdfMergePath);
} catch (Exception e) {
log.error("❌ PDF合并失败:");
e.printStackTrace();
}
}
是不是非常简单,PDFBox还提供了很多功能,感兴趣的可以去研究!
官方地址:https://pdfbox.apache.org/index.html

本次教程到这里就结束了,希望大家多多关注支持(首席摸鱼师 微信同号),持续跟踪最新文章吧~

6605

被折叠的 条评论
为什么被折叠?



