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