package com.ltkj.common.utils.pdfutils; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.*; import org.apache.commons.io.IOUtils; import java.io.*; import java.util.List; /** * @Author: 西安路泰科技有限公司/lige * @Date: 2022/12/12 17:45 */ public class MergePdf { /** * 合并PDF文件 * * @param files 文件列表 * @param output 输出的PDF文件 * @throws */ public static void mergeFileToPDF(List files, File output) { Document document = null; PdfCopy copy = null; OutputStream os = null; try { os = new FileOutputStream(output); document = new Document(); copy = new PdfCopy(document, os); document.open(); for (File file : files) { if (!file.exists()) { continue; } String fileName = file.getName(); if (fileName.endsWith(".pdf")) { PdfContentByte cb = copy.getDirectContent(); PdfOutline root = cb.getRootOutline(); new PdfOutline(root, new PdfDestination(PdfDestination.XYZ), fileName .substring(0, fileName.lastIndexOf("."))); // 不使用reader来维护文件,否则删除不掉文件,一直被占用 try (InputStream is = new FileInputStream(file)) { PdfReader reader = new PdfReader(is); int n = reader.getNumberOfPages(); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } } catch (Exception e) { System.out.println("error to close file : {}" + file.getCanonicalPath()); } } else { System.out.println("file may not be merged to pdf. name:" + file.getCanonicalPath()); } } } catch (Exception e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } if (copy != null) { copy.close(); } if (os != null) { IOUtils.closeQuietly(os); } } } }