PDFBox合併多個PDF文檔

在前一章中,我們已經看到如何將給定的PDF文檔分成多個文檔。 現在讓我們學習如何將多個PDF文檔合併為一個文檔。

合併多個PDF文檔

使用PDFMergerUtility類的類將多個PDF文檔合併到單個PDF文檔中,該類提供了將兩個或多個PDF文檔合併到單個PDF文檔中的方法。

以下是合併多個PDF文檔的步驟。

第1步:加載現有的PDF文檔

使用PDDocument類的靜態方法load()加載現有的PDF文檔。 此方法接受一個檔對象作為參數,因為這是一個靜態方法,可以使用類名稱調用它,如下所示。

File file = new File("path of the document")
PDDocument document = PDDocument.load(file);

第2步:實例化PDFMergerUtility類

如下所示實例化合並實用程式類。

PDFMergerUtility PDFmerger = new PDFMergerUtility();

第3步:設置目標檔

使用setDestinationFileName()方法設置目標檔,如下所示。

PDFmerger.setDestinationFileName("D:/PdfBoxExamples/docs/merged.pdf");

第4步:設置原始檔案

使用addSource()方法設置原始檔案,如下所示。

PDFmerger.addSource(file1);

第5步:合併文檔

使用PDFmerger類的mergeDocuments()方法合併文檔,如下所示。

PDFmerger.mergeDocuments();

第6步:關閉文檔

最後使用PDDocument類的close()方法關閉文檔,如下所示。

document.close();

示例

假設,在目錄:F:\worksp\pdfbox中有兩個PDF文檔 - sample1.pdfsample2.pdf,如下所示。

第一個PDF檔(sample1.pdf):

第二個PDF檔(sample2.pdf):

本示例演示如何合併上述PDF文檔。 在這裏,我們將把sample1.pdfsample2.pdf這兩個PDF文檔合併到一個PDF文檔 - merged.pdf中。 將此代碼保存在名稱為MergePDFs.java的檔中。

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 MergePDFs {
   public static void main(String[] args) throws IOException {

      //Loading an existing PDF document
      File file1 = new File("F:/worksp/pdfbox/sample1.pdf");
      PDDocument doc1 = PDDocument.load(file1);

      File file2 = new File("F:/worksp/pdfbox/sample2.pdf");
      PDDocument doc2 = PDDocument.load(file2);

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

      //Setting the destination file
      PDFmerger.setDestinationFileName("F:/worksp/pdfbox/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

打開新合成的文檔(merged.pdf),如下所示 -


上一篇: PDFBox分割PDF文檔 下一篇: PDFBox提取圖像