java合并PDF文件

时间:2022-09-10 06:37:07

使用java代码合并PDF文件需要导入iText-2.1.7.jar

 1 import java.io.FileOutputStream;  
 2 import java.io.IOException;  
 3 import com.lowagie.text.Document;  
 4 import com.lowagie.text.DocumentException;  
 5 import com.lowagie.text.pdf.PdfCopy;  
 6 import com.lowagie.text.pdf.PdfImportedPage;  
 7 import com.lowagie.text.pdf.PdfReader;  
 8   
 9 public class MergeFile {  
10     public static void main(String[] args) {  
11         String[] files = { "e:\\1.pdf", "e:\\2.pdf", "e:\\3.pdf" };  
12         String savepath = "e:\\temp.pdf";  
13         mergePdfFiles(files, savepath);  
14     } /* 
15          * * 合並pdf文件 * * @param files 要合並文件數組(絕對路徑如{ "e:\\1.pdf", "e:\\2.pdf" , 
16          * "e:\\3.pdf"}) * @param newfile 
17          * 合並後新產生的文件絕對路徑如e:\\temp.pdf,請自己刪除用過後不再用的文件請 * @return boolean 
18          * 產生成功返回true, 否則返回false 
19          */  
20   
21     public static boolean mergePdfFiles(String[] files, String newfile) {  
22         boolean retValue = false;  
23         Document document = null;  
24         try {  
25             document = new Document(new PdfReader(files[0]).getPageSize(1));  
26             PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));  
27             document.open();  
28             for (int i = 0; i < files.length; i++) {  
29                 PdfReader reader = new PdfReader(files[i]);  
30                 int n = reader.getNumberOfPages();  
31                 for (int j = 1; j <= n; j++) {  
32                     document.newPage();  
33                     PdfImportedPage page = copy.getImportedPage(reader, j);  
34                     copy.addPage(page);  
35                 }  
36             }  
37             retValue = true;  
38         } catch (Exception e) {  
39             e.printStackTrace();  
40         } finally {  
41             document.close();  
42         }  
43         return retValue;  
44     }  
45 }