本文共 2292 字,大约阅读时间需要 7 分钟。
在将多个PDF文件合并为一个PDF文件时,通常会创建一个新的 Document
对象,并读取每一个PDF文件的 PdfImportedPage
页,而后使用 PdfCopy
类中的方法将其添加到新创建的PDF文件中,部分代码如下:
for (int i = 0; i < fileList.size(); i++) { PdfReader reader = new PdfReader(fileList.get(i)); int n = reader.getNumberOfPages(); for (int j = 1; j <= n; j++) { document.newPage(); PdfImportedPage page = copy.getImportedPage(reader, j); copy.addPage(page); } }
但是,这种方式可能会破坏多个PDF文件的大小和旋转角度,如合并的PDF文件中有A4大小的和A3大小的,或者存在横向和纵向的。
为了保留原始文件的各种状态,可以参考下面的方法:
public static boolean concatPdfs(String[] originPaths, String targetPath) { PdfCopyFields copyFields = null; FileOutputStream outputStream = null; PdfReader reader = null; boolean result = true; try { File targetFile = new File(targetPath); if (targetFile.exists() && targetFile.isFile()){ result = targetFile.delete(); } if (result) { outputStream = new FileOutputStream(targetFile); copyFields = new PdfCopyFields(outputStream); for (String pdfPath : originPaths) { File pdfFile = new File(pdfPath); if (!pdfFile.exists() || !pdfFile.isFile()) { System.out.println("file is not exist or is not a file."); return false; } reader = new PdfReader(pdfPath); copyFields.addDocument(reader); reader.close(); } } return result; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (copyFields != null) { copyFields.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (outputStream != null) { outputStream.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } }
转载地址:http://wtdws.baihongyu.com/