<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>${openpdf.version}</version>
</dependency>
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfReader;
/**
* 合并多个 PDF 文件
*
* @param mergedPdf 合并后的文件
* @param pdfs 待合并的文件
* @throws DocumentException 读取 PDF 文件异常
* @throws IOException 合并异常
*/
public static void mergePDF(File mergedPdf, File... pdfs) throws DocumentException, IOException {
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, new FileOutputStream(mergedPdf));
doc.open();
for (File pdf : pdfs) {
PdfReader pdfreader = new PdfReader(new FileInputStream(pdf));
int n = pdfreader.getNumberOfPages();
for (int i = 1; i <= n; i++) {
copy.addPage(copy.getImportedPage(pdfreader, i));
}
copy.freeReader(pdfreader);
}
doc.close();
copy.close();
}