PDFBox分割PDF文档

在前一章中,我们已经看到了如何将JavaScript添加到PDF文档。 现在来学习如何将给定的PDF文档分成多个文档。

分割PDF文档中的页面

可以使用Splitter类将给定的PDF文档分割为多个PDF文档。 该类用于将给定的PDF文档分成几个其他文档。

以下是拆分现有PDF文档的步骤

第1步:加载现有的PDF文档

使用PDDocument类的静态方法load()加载现有的PDF文档。 此方法接受一个文件对象作为参数,因为这是一个静态方法,可以使用类名称调用它,如下所示。

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

第2步:实例化Splitter类

这个Splitter类包含了分割给定的PDF文档的方法,因此实例化这个类,如下所示。

Splitter splitter = new Splitter();

第3步:分割PDF文档

使用Splitter类的Split()方法来分割给定的文档。 该方法接受PDDocument类的一个对象作为参数。

List<PDDocument> Pages = splitter.split(document);

split()方法将给定文档的每个页面分割为单独的文档,并以列表的形式返回所有这些文档。

第4步:创建一个迭代器对象

要遍历文档列表,需要获取上述步骤中获取的列表的迭代器对象,使用listIterator()方法获取列表的迭代器对象,如下所示。

Iterator<PDDocument> iterator = Pages.listIterator();

第5步:关闭文档

最后,使用PDDocument类的close()方法关闭文档,如下所示。

document.close();

示例

假设在目录:F:\worksp\pdfbox 中有一个名称为mypdf.pdf的PDF文档,并且该文档包含两个页面 - 一个页面包含图像,另一个页面包含文本,如下所示。

这个例子演示了如何分割上面提到的PDF文档。 在这里,将把名称为mypdf.pdf的PDF文档分成两个不同的文档:sample1.pdfsample2.pdf。 将此代码保存在名为SplitPages.java的文件中。

package com.zyiz;

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

import java.io.File; 
import java.io.IOException; 
import java.util.List; 
import java.util.Iterator;

public class SplitPages {
   public static void main(String[] args) throws IOException {

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

      //Instantiating Splitter class
      Splitter splitter = new Splitter();

      //splitting the pages of a PDF document
      List<PDDocument> Pages = splitter.split(document);

      //Creating an iterator 
      Iterator<PDDocument> iterator = Pages.listIterator();

      //Saving each page as an individual document
      int i = 1;
      while(iterator.hasNext()) {
         PDDocument pd = iterator.next();
         pd.save("F:/worksp/pdfbox/sample"+ i +".pdf");
         i = i + 1;
      }
      System.out.println("Multiple PDF’s created");
      document.close();
   }
}

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

Multiple PDF’s created

生成的两个文件,打开效果如下 -

第二个PDF文件:


上一篇:PDFBox PDF文档中的JavaScript

下一篇:PDFBox合并多个PDF文档

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

扫描二维码
程序员编程王

扫一扫关注最新编程教程