<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.14</version>
</dependency>
public static File mergeDocuments(File files, String filePath) throws IOException {
PDFMergerUtility pdf = new PDFMergerUtility();
for (File f : files.listFiles()) {
if (f.getName().contains("汇总")) {
continue;
}
if (f.exists() && f.isFile()) {
pdf.addSource(f);
}
}
// 设置合并生成pdf文件名称
pdf.setDestinationFileName(filePath);
// 开始合并pdf
pdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
File file = new File(filePath);
//加载PDF
PDDocument document = PDDocument.load(file);
AccessPermission accessPermission = new AccessPermission();
accessPermission.setCanPrint(true);
accessPermission.setCanModify(false);
accessPermission.setCanExtractContent(false);
StandardProtectionPolicy spp = new StandardProtectionPolicy("编辑pdf需要密码",null, accessPermission);
spp.setEncryptionKeyLength(256);
spp.setPermissions(accessPermission);
document.protect(spp);
document.save(filePath);
document.close();
return file;
}
files是已经生成好PDF的文件夹,filePath是合并后生成PDF路径