PDFBox删除页面

现在让我们学习如何从PDF文档中移除页面。

从现有文档中删除页面

使用PDDocument类的removePage()方法从现有的PDF文档中移除页面。

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

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

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

第2步:列出页数

使用getNumberOfPages()方法列出PDF文档中存在的页面数量,如下所示。

int noOfPages= document.getNumberOfPages();
System.out.print(noOfPages);

第3步:删除页面

使用PDDocument类的removePage()方法从PDF文档中移除页面。 对于此方法,需要传递要删除的页面的索引。

在为PDF文档中的页面指定索引时,请记住,这些页面的索引从零开始,即如果要删除第1页,则索引值为0

document.removePage(2); // 删除第三页

第4步:保存文档

删除页面后,使用PDDocument类的save()方法保存PDF文档,如以下代码块中所示。

document.save("Path");

第5步:关闭文档

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

document.close();

示例

假设有一个名称为sample.pdf的PDF文档,它包含三个空页面,如下所示。

这个例子演示了如何从现有的PDF文档中删除页面。 在这里,将加载上面名称为sample.pdf的PDF文档,从中删除一个页面,并将其保存在:F:\worksp\pdfbox\sample-remove-pages.pdf文件中。 将此代码保存在名称为RemovingPages.java的文件中。

package com.zyiz;

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;

public class RemovingPages {

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

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

      //Listing the number of existing pages
      int noOfPages= document.getNumberOfPages();
      System.out.println(noOfPages);

      //Removing the pages
      document.removePage(2);

      System.out.println("page removed");

      //Saving the document
      document.save("F:/worksp/pdfbox/sample-remove-pages.pdf");

      //Closing the document
      document.close();

   }
}

执行上面示例代码后,将会创建一个PDF文档,其中包含显示以下消息的空白页面。

3
page removed

如果验证指定的路径,则可以发现所需页面已被删除,并且文档中只剩下两页,如下所示。


上一篇:PDFBox加载文件

下一篇:PDFBox文档属性

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

扫描二维码
程序员编程王

扫一扫关注最新编程教程