Java如何使用Java合并两个PDF文件?

在Java编程中,如何使用Java合并两个PDF文件?

以下是使用Java合并两个PDF文件的示例程序。

package com.zaixian;

import org.apache.pdfbox.multipdf.PDFMergerUtility; 
import org.apache.pdfbox.pdmodel.PDDocument;  

import java.io.File; 
import java.io.IOException;  

public class MergingPdfsIntoOne { 
   public static void main(String[] args) throws IOException { 
      String workpath = "F:/worksp/javaexamples/java_apache_pdf_box/";
      //Loading an existing PDF document 
      File file1 = new File(workpath+"many1.pdf"); 
      PDDocument doc1 = PDDocument.load(file1); 

      File file2 = new File(workpath+"many2.pdf"); 
      PDDocument doc2 = PDDocument.load(file2); 

      //Instantiating PDFMergerUtility class 
      PDFMergerUtility PDFmerger = new PDFMergerUtility();       

      //Setting the destination file 
      PDFmerger.setDestinationFileName(workpath+"merged.pdf"); 

      //adding the source files 
      PDFmerger.addSource(file1); 
      PDFmerger.addSource(file2); 

      //Merging the two documents 
      PDFmerger.mergeDocuments(); 
      System.out.println("Documents merged"); 

      //Closing the documents 
      doc1.close(); 
      doc2.close();           
   } 
}

执行上面示例代码,得到以下结果 -

Documents merged

此时,程序已经合并成一个PDF文件,如下所示 -


上一篇: Java PDF Box程序示例 下一篇: Java POI PPT