public static boolean mergePdfFiles(String[] files, String newfile) {
boolean retValue = false;
Document document = null;
PdfReader reader = null;
PdfImportedPage page = null;
PdfCopy copy = null;
List<PdfReader> readerList = new ArrayList<PdfReader>();// 记录合并PDF集合
List<PdfImportedPage> pageList = new ArrayList<PdfImportedPage>();// 记录合并PDF集合
List<PdfCopy> copyList = new ArrayList<PdfCopy>();// 记录合并PDF集合
OutputStream newFileStream = null;
try {
newFileStream = new FileOutputStream(newfile);
reader = new PdfReader(files[0]);
document = new Document(reader.getPageSize(1));
reader.close();
reader = null;
copy = new PdfCopy(document, newFileStream);
document.open();
for (int i = 0; i < files.length; i++) {
reader = new PdfReader(files[i]);
int n = reader.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
page = copy.getImportedPage(reader, j);
pageList.add(page);
copy.addPage(page);
copyList.add(copy);
}
readerList.add(reader);
}
retValue = true;
} catch (Exception e) {
e.printStackTrace();
RecordException.recordPrintException(e, null);
} finally {
for (int i = 0; i < copyList.size(); i++) {
copy = copyList.get(i);
copy.close();
}
for (int i = 0; i < pageList.size(); i++) {
page = pageList.get(i);
page.closePath();
}
for (int i = 0; i < readerList.size(); i++) {
reader = readerList.get(i);
reader.close();
}
document.close();
copy = null;
page = null;
reader = null;
document = null;
copyList.clear();
pageList.clear();
readerList.clear();
copyList = null;
pageList = null;
readerList = null;
try {
if (null!=newFileStream) {
newFileStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
newFileStream = null;
File file = null;
for (int i = 0; i < files.length; i++) {
file = new File(files[i]);
file.delete();
file = null;
}
}
return retValue;
}
版权声明:本文为ftm_csdn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。