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.zyiz;

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提取图像

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程