一丶使用场景
将两个或多个单独的PDF文件合并成一个PDF文件
二丶引入相关jar包
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
三丶编写相关工具类
/**
* 合并pdf
*
* @param files 需合并的pdf文件集合
* @param targetPath 保存路径
* @return
* @throws IOException 异常抛出
*/
public static File mulFile2One(List<File> files, String targetPath) throws IOException {
// pdf合并工具类
PDFMergerUtility mergePdf = new PDFMergerUtility();
for (File f : files) {
if(f.exists() && f.isFile()){
// 循环添加要合并的pdf
mergePdf.addSource(f);
}
}
// 设置合并生成pdf文件名称及路径
mergePdf.setDestinationFileName(targetPath);
// 合并pdf
mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
return new File(targetPath);
}
四丶相关测试
@Test
public void test3(){
List<File> files = new ArrayList<>();
files.add(new File("C:\\1.pdf"));
files.add(new File("C:\\2.pdf"));
try {
File f = FileUtils.mulFile2One(files, "D:\\heBing.pdf");
System.out.println(f.length()); // 长度>0则成功
}catch (Exception e) {
e.getMessage();
}
}
五丶总结
1丶此合并在于集合先后顺序进行排序
2丶若同一路径有相同的文件名,合并文件会替换掉相同的文件
3丶需使用绝对路径