java代碼
package c; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; public class PdfOperate { static String savepath = "D:/temp/pdftest/all.pdf"; public static void main(String[] args) { System.out.println("start " + new Date()); List<String> fileList = getFiles(); morePdfTopdf(fileList, savepath); } public static List<String> getFiles() { List<String> fileList = new ArrayList<String>(); for (int i = 0; i < 3; i++) { fileList.add("D:/temp/pdftest/m (" + i + ").pdf"); } return fileList; } public static void morePdfTopdf(List<String> fileList, String savepath) { Document document = null; try { document = new Document(new PdfReader(fileList.get(0)).getPageSize(1)); PdfCopy copy = new PdfCopy(document, new FileOutputStream(savepath)); document.open(); 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);// 從當前Pdf,獲取第j頁 copy.addPage(page); } System.out.println(i); } } catch (IOException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } finally { if (document != null) { document.close(); } System.out.println("finish " + new Date()); } } }
jar包
本代碼用了比較新版的itextpdf-5.5.13.jar http://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.5.13
原參考鏈接好像用的是2.1.7舊版的.
效果
性能
在合並200個pdf , 每個600Kb, 耗時大約4秒左右,性能極佳.
部分參考自
IText實現多個pdf轉成一個pdf--http://wangming2012.iteye.com/blog/1529912