Java如何使用Java合併兩個PDF檔案?

2019-10-16 22:28:55

在Java程式設計中,如何使用Java合併兩個PDF檔案?

以下是使用Java合併兩個PDF檔案的範例程式。

package com.yiibai;

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檔案,如下所示 -