1. 程式人生 > >Java 合併多個 PDF 檔案

Java 合併多個 PDF 檔案

獲取所需合併的 PDF 檔案路徑即可。

/**
     * 合成 PDF
     * @param beforeRootPath: 專案路徑
     * @param filePath: 第一個 PDF 路徑
     * @param checkReport: 物件, 用於獲取使用者上傳的 PDF 路徑(欄位)
     * @return
     * @throws Exception
     */
    public String getPathSynthesisPdf(String beforeRootPath, String filePath, CheckReport checkReport) throws
Exception{ //合成後的檔案路徑("D:\\pdf\\aaaa.pdf") String synthesisPdfPath = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); synthesisPdfPath = beforeRootPath + "WEB-INF\\upload\\checkReport\\syntheticsPdf\\syntheticsPdf_" + formatter.format(new Date()) + "_鋁及鋁合金化學成分.pdf"
; PDFMergerUtility PDFmerger = new PDFMergerUtility(); PDFmerger.setDestinationFileName(synthesisPdfPath); File file1 = new File(filePath); File file2 = new File(checkReport.getSyPath() == null || checkReport.getSyPath().trim().length() == 0 ? "" : beforeRootPath + "WEB-INF\\upload\\checkReport\\uploadThreePDF\\"
+ checkReport.getSyPath()); File file3 = new File(checkReport.getBgPath() == null || checkReport.getBgPath().trim().length() == 0 ? "" : beforeRootPath + "WEB-INF\\upload\\checkReport\\uploadThreePDF\\" + checkReport.getBgPath()); File file4 = new File(checkReport.getYsPath() == null || checkReport.getYsPath().trim().length() == 0 ? "" : beforeRootPath + "WEB-INF\\upload\\checkReport\\uploadThreePDF\\" + checkReport.getYsPath()); PDDocument doc1 = null; PDDocument doc2 = null; PDDocument doc3 = null; PDDocument doc4 = null; if(equalsStr(file2.getPath()) && equalsStr(file3.getPath()) && equalsStr(file4.getPath())){ if(file1.getPath() != null && file1.getPath().trim().length() > 0){ doc1 = PDDocument.load(file1); PDFmerger.addSource(file1); } if(file2.getPath() != null && file2.getPath().trim().length() > 0){ doc2 = PDDocument.load(file2); PDFmerger.addSource(file2); } if(file3.getPath() != null && file3.getPath().trim().length() > 0){ doc3 = PDDocument.load(file3); PDFmerger.addSource(file3); } if(file4.getPath() != null && file4.getPath().trim().length() > 0){ doc4 = PDDocument.load(file4); PDFmerger.addSource(file4); } PDFmerger.mergeDocuments(); if(doc1 != null){ doc1.close(); } if(doc2 != null){ doc2.close(); } if(doc3 != null){ doc3.close(); } if(doc4 != null){ doc4.close(); } System.out.println("使用者上傳的三個PDF和模板合成完成!"); }else { throw new Exception("請先上傳附件!"); } return synthesisPdfPath; }