多个pdf文件合并成一个pdf文件。生成过后怎么也删除不了,估计有使用到的流没关闭,手动在文件夹中也无法删除,提示文件正在被占用,但是怎么查找代码也不知道哪里的流没关闭。
最后在循环中发现了new PdfReader(),每次循环都会生成一个新PdfReader对象,代码从循环中出来,但是对象并没有被销毁,即使从方法中走出来,也没有被销毁,导致文件无法删除,也不好使。
最终采用不以PdfReader去维护,以当前文件流来管理。
maven 依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
/**
* 合并PDF文件
* @param files 文件列表
* @param output 输出的PDF文件
* @throws AppException 合并的异常
*/
public static void mergeFileToPDF(List<File> files, File output) throws AppException {
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) {
logger.warn("error to close file : {}" + file.getCanonicalPath(), e);
}
} else {
logger.warn("file may not be merged to pdf. name:" + file.getCanonicalPath());
}
}
} catch (Exception e) {
throw new AppException(e, ErrorCodes.class, ErrorCodes.IO_ACCESS_ERROR);
} finally {
if (document != null) {
document.close();
}
if (copy != null) {
copy.close();
}
if (os != null) {
IOUtils.closeQuietly(os);
}
}
}