【代码】JAVA合并PDF文件
第一步, 添加依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-app</artifactId>
<version>2.0.21</version>
</dependency>
第二步, 写代码, 将需要合并的PDF文件按照顺序命名, 执行main方法
package com.guanwei.study.PDF;
import cn.hutool.core.util.StrUtil;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
/**
* 添加依赖
* <dependency>
* <groupId>org.apache.pdfbox</groupId>
* <artifactId>pdfbox-app</artifactId>
* <version>2.0.27</version>
* </dependency>
*
*
* 官方文档
* https://pdfbox.apache.org/2.0/getting-started.html
*
* 相关文档
* http://www.yiidian.com/pdfbox/pdfbox-merging-pdf-document.html
*
*/
public class 合并PDF {
public static void main(String[] args) throws IOException {
/**
* ================ 配置项 Start ======================
*/
String 文件目录 = "C:\\GW\\个人\\新建文件夹 (2)\\";
/**
* 文件名称 提前按照需要合并的顺序命名
* XXX1.pdf
* XXX2.pdf
* XXX3.pdf
*
* fileName = XXX{}.pdf
*
*/
String 文件名称 = "有效排痰的护理ppt{}.pdf";
int 文件数量 = 9;
/**
* ================ 配置项 End ======================
*/
//PDF集合
List<PDDocument> pdDocumentList = new LinkedList<>();
//PDF文件流集合
List<File> files = new LinkedList<>();
//将所有需要合并的PDF读取出来
for (int i = 1; i <= 文件数量; i++) {
//Loading an existing PDF document
File file = new File(文件目录 + StrUtil.format(文件名称, i));
files.add(file);
PDDocument pdDocument = new PDDocument();
PDDocument document1 = PDDocument.load(file);
pdDocumentList.add(document1);
}
//创建合并工具
//Create PDFMergerUtility class object
PDFMergerUtility PDFmerger = new PDFMergerUtility();
//设置合并后的PDF输出路径
//Setting the destination file path
PDFmerger.setDestinationFileName(文件目录 + StrUtil.format(文件名称, "_最终合并版"));
//添加需要合并的文件
//adding the source files
for (File file : files) {
PDFmerger.addSource(file);
}
//开始合并文档
//Merging the documents
PDFmerger.mergeDocuments(null);
System.out.println("PDF Documents merged to a single file successfully");
//关闭文档
//Close documents
for (PDDocument pdDocument : pdDocumentList) {
pdDocument.close();
}
}
}
相关文档:
springboot使用pdfbox-app-1.8.10实现pdf分页流下载_Shiyxu的博客-CSDN博客_pdfbox-app
java操作PDF文件,可支持分页、合并、图片转PDF等_不会理财的程序员不是好UP主的博客-CSDN博客