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