PDFBox - 概述

可移植文档格式 (PDF) 是一种文件格式,有助于以独立于应用程序软件、硬件和操作系统的方式呈现数据。

每个 PDF 文件都包含对固定布局平面文档的描述,包括文本、字体、图形和显示它所需的其他信息。

有几个库可用于通过程序创建和操作 PDF 文档,例如 -

  • Adobe PDF Library - 该库以 C++、.NET 和 Java 等语言提供 API,使用它我们可以编辑、查看打印和从 PDF 文档中提取文本。
  • Formatting Objects Processor - 由 XSL Formatting Objects 驱动的开源打印格式化程序和一个独立于输出的格式化程序。主要输出目标是 PDF。
  • iText - 该库以 Java、C# 和其他 .NET 语言等语言提供 API,使用该库我们可以创建和操作 PDF、RTF 和 HTML 文档。
  • JasperReports - 这是一个 Java 报告工具,可在 PDF 文档中生成报告,包括 Microsoft Excel、RTF、ODT、逗号分隔值和 XML 文件。

什么是 PDFBox

Apache PDFBox 是一个开源 Java 库,支持 PDF 文档的开发和转换。使用这个库,您可以开发创建、转换和操作 PDF 文档的 Java 程序。

除此之外,PDFBox 还包括一个命令行实用程序,用于使用可用的 Jar 文件对 PDF 执行各种操作。

PDFBox 的特点

以下是 PDFBox 的显着特点 -

  • 提取文本- 使用 PDFBox,您可以从 PDF 文件中提取 Unicode 文本。
  • Split & Merge - 使用 PDFBox,您可以将单个 PDF 文件分成多个文件,并将它们合并为单个文件。
  • Fill Forms - 使用 PDFBox,您可以在文档中填写表单数据。
  • Print - 使用 PDFBox,您可以使用标准 Java 打印 API 打印 PDF 文件。
  • Save as Image - 使用 PDFBox,您可以将 PDF 保存为图像文件,例如 PNG 或 JPEG。
  • 创建 PDF - 使用 PDFBox,您可以通过创建 Java 程序来创建新的 PDF 文件,还可以包含图像和字体。
  • 签名- 使用 PDFBox,您可以向 PDF 文件添加数字签名。

PDFBox 的应用

以下是 PDFBox 的应用 -

  • Apache Nutch - Apache Nutch 是一个开源网络搜索软件。它建立在 Apache Lucene 之上,添加了 Web 特性,例如爬虫、链接图数据库、HTML 解析器和其他文档格式等。
  • Apache Tika - Apache Tika 是一个工具包,用于使用现有的解析器库从各种文档中检测和提取元数据和结构化文本内容。

PDFBox 组件

以下是 PDFBox 的四个主要组件 -

  • PDFBox - 这是 PDFBox 的主要部分。这包含与内容提取和操作相关的类和接口。
  • FontBox - 这包含与字体相关的类和接口,使用这些类我们可以修改 PDF 文档文本的字体。
  • XmpBox - 这包含处理 XMP 元数据的类和接口。
  • Preflight - 此组件用于根据 PDF/A-1b 标准验证 PDF 文件。

PDFBox - 环境

安装 PDFBox

以下是下载 Apache PDFBox 的步骤 -

第 1 步-通过单击以下链接打开Apache PDFBox的主页- Apache PDFBox | A Java PDF Library

第 2 步- 上面的链接将引导您到主页,如以下屏幕截图所示 -

java中使用openpdf java操作pdf的开源工具_Java

第 3 步- 现在,单击上面屏幕截图中突出显示的下载链接。单击后,您将被定向到 PDFBox 的下载页面,如下图所示。

java中使用openpdf java操作pdf的开源工具_Java_02

第 4 步- 在“下载”页面中,您将获得 PDFBox 的链接。单击相应链接以获取最新版本。例如,我们选择PDFBox 2.0.1,点击它,您将被定向到所需的 jar 文件,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_Java_03

第 5 步- 下载 jar 文件 pdfbox-2.0.1.jar、fontbox-2.0.1.jar、preflight-2.0.1.jar、xmpbox-2.0.1.jar 和 pdfbox-tools-2.0.1.jar。

Eclipse 安装

下载所需的 jar 文件后,您必须将这些 JAR 文件嵌入到您的 Eclipse 环境中。您可以通过设置这些 JAR 文件的构建路径并使用pom.xml来做到这一点。

设置构建路径

以下是在 Eclipse 中安装 PDFBox 的步骤 -

第 1 步- 确保您已在系统中安装 Eclipse。如果没有,请在您的系统中下载并安装 Eclipse。

第 2 步- 打开 Eclipse,单击文件、新建,然后打开一个新项目,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_Java_04

第 3 步- 选择项目后,您将获得新建项目向导。在此向导中,选择 Java 项目并单击Next按钮继续,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_java_05

Step 4 - 继续前进,您将被引导至New Java Project 向导。创建一个新项目并单击下一步,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_06

Step 5 - 创建一个新项目后,右键单击它;选择Build Path并单击Configure Build Path...,如下面的屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_07

Step 6 - 单击Build Path选项,您将被定向到Java Build Path 向导。选择Add External JARs,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_08

步骤 7 - 选择 jar 文件fontbox-2.0.1.jar、pdfbox-2.0.1.jar、pdfbox-tools-2.0.1.jar、preflight-2.0.1.jar、xmpbox-2.0.1.jar,如图所示在下面的屏幕截图中。

java中使用openpdf java操作pdf的开源工具_Java_09

第 8 步- 单击上面屏幕截图中的“打开”按钮,这些文件将被添加到您的库中,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_Java_10

Step 9 - 单击OK,您将成功地将所需的 JAR 文件添加到当前项目中,您可以通过展开 Referenced Libraries 来验证这些添加的库,如下面的屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_java_11

使用 pom.xml

将项目转换为maven项目,在其pom.xml中添加如下内容。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example.pdfboxcropbox</groupId>
    <artifactId>PDFBoxCropBox</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <exec.mainClass>com.example.pdfboxcropbox.PDFBoxCropBox</exec.mainClass>
    </properties>



    <dependencies>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.25</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.25</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>jempbox</artifactId>
            <version>1.8.16</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>xmpbox</artifactId>
            <version>2.0.25</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>preflight</artifactId>
            <version>2.0.25</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox-tools</artifactId>
            <version>2.0.25</version>
        </dependency>

    </dependencies>


</project>

PDFBox - 创建 PDF 文档

现在让我们了解如何使用 PDFBox 库创建 PDF 文档。

创建一个空的 PDF 文档

您可以通过实例化PDDocument类来创建一个空的 PDF 文档。您可以使用Save()方法将文档保存在所需的位置。

以下是创建空 PDF 文档的步骤。

第 1 步:创建一个空文档

属于包org.apache.pdfbox.pdmodelPDDocument类是 PDFDocument 的内存表示。因此,通过实例化此类,您可以创建一个空的 PDFDocument,如以下代码块所示。

PDDocument document = new PDDocument();

第 2 步:保存文档

创建文档后,您需要将此文档保存在所需的路径中,您可以使用PDDocument类的Save()方法来完成。此方法接受一个字符串值,表示您要存储文档的路径,作为参数。以下是PDDocument类的 save() 方法的原型。

document.save("Path");

第 3 步:关闭文档

当您的任务完成后,最后,您需要使用close()方法关闭PDDocument对象。以下是PDDocument类的 close() 方法的原型。

document.close();

例子

此示例演示 PDF 文档的创建。在这里,我们将创建一个 Java 程序来生成一个名为my_doc.pdf的 PDF 文档并将其保存在路径C:/PdfBox_Examples/中。将此代码保存在名为Document_Creation.java 的文件中。

import java.io.IOException; 
import org.apache.pdfbox.pdmodel.PDDocument;
  
public class Document_Creation {
    
   public static void main (String args[]) throws IOException {
       
      //Creating PDF document object 
      PDDocument document = new PDDocument();    
       
      //Saving the document
      document.save("C:/PdfBox_Examples/my_doc.pdf");
         
      System.out.println("PDF created");  
    
      //Closing the document  
      document.close();

   }  
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac Document_Creation.java 
java Document_Creation

执行后,上述程序会创建一个显示以下消息的 PDF 文档。

PDF created

如果您验证指定的路径,您可以找到创建的 PDF 文档,如下所示。

java中使用openpdf java操作pdf的开源工具_java_12

由于这是一个空文档,如果您尝试打开此文档,则会提示您显示错误消息,如以下屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_13

PDFBox - 添加页面

在上一章中,我们已经了解了如何创建 PDF 文档。创建 PDF 文档后,您需要为其添加页面。现在让我们了解如何在 PDF 文档中添加页面。

将页面添加到 PDF 文档

您可以通过实例化PDPage类来创建一个空页面,并使用PDDocument类的addPage()方法将其添加到 PDF 文档中。

以下是创建空文档并向其添加页面的步骤。

第 1 步:创建一个空文档

通过实例化PDDocument类来创建一个空的 PDF 文档,如下所示。

PDDocument document = new PDDocument();

第 2 步:创建空白页

PDPage类表示PDF文档中的一个页面,因此,您可以通过实例化该类来创建一个空页面,如以下代码块所示。

PDPage my_page = new PDPage();

第 3 步:将页面添加到文档

您可以使用PDDocument类的addPage()方法将页面添加到 PDF 文档。对于此方法,您需要将 PDPage 对象作为参数传递。

因此,将上一步中创建的空白页添加到 PDDocument 对象中,如以下代码块所示。

document.addPage(my_page);

通过这种方式,您可以在 PDF 文档中添加任意数量的页面。

第 4 步:保存文档

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

document.save("Path");

第 5 步:关闭文档

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

document.close();

例子

此示例演示如何创建 PDF 文档并向其添加页面。在这里,我们将创建一个名为my_doc.pdf的 PDF 文档,并进一步添加 10 个空白页,并将其保存在路径C:/PdfBox_Examples/中。将此代码保存在名为Adding_pages.java 的文件中。

package document;
 
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class Adding_Pages {

   public static void main(String args[]) throws IOException {
       
      //Creating PDF document object 
      PDDocument document = new PDDocument();

      for (int i=0; i<10; i++) {
         //Creating a blank page 
         PDPage blankPage = new PDPage();

         //Adding the blank page to the document
         document.addPage( blankPage );
      } 
     
      //Saving the document
      document.save("C:/PdfBox_Examples/my_doc.pdf");
      System.out.println("PDF created");
      
      //Closing the document
      document.close();

   }  
}

使用以下命令从命令提示符编译并执行保存的 Java 文件 -

javac Adding_pages.java 
java Adding_pages

执行后,上述程序会创建一个 PDF 文档,其中包含显示以下消息的空白页面 -

PDF created

如果您验证指定的路径,您可以找到创建的 PDF 文档,如下图所示。

java中使用openpdf java操作pdf的开源工具_java_14

PDFBox - 加载文档

在前面的示例中,您已经了解了如何创建新文档并向其添加页面。本章教您如何加载系统中已经存在的 PDF 文档,并对其进行一些操作。

加载现有的 PDF 文档

PDDocument类的load()方法用于加载现有的 PDF 文档。按照下面给出的步骤加载现有的 PDF 文档。

第 1 步:加载现有 PDF 文档

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

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

步骤 2:执行所需的操作

执行所需的操作,例如添加页面、添加文本、向加载的文档添加图像。

第 3 步:保存文档

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

document.save("Path");

第 4 步:关闭文档

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

document.close();

例子

假设我们有一个包含单个页面的 PDF 文档,路径为C:/PdfBox_Examples/,如下面的屏幕截图所示。

java中使用openpdf java操作pdf的开源工具_apache_15

此示例演示如何加载现有 PDF 文档。在这里,我们将加载如上所示的PDF文档sample.pdf,为其添加一个页面,并以相同的名称保存在相同的路径中。

第 1 步- 将此代码保存在名为LoadingExistingDocument.java 的文件中。

import java.io.File;
import java.io.IOException;
 
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage;
public class LoadingExistingDocument {

   public static void main(String args[]) throws IOException {
   
      //Loading an existing document 
      File file = new File("C:/PdfBox_Examples/sample.pdf"); 
      PDDocument document = PDDocument.load(file); 
        
      System.out.println("PDF loaded"); 
        
      //Adding a blank page to the document 
      document.addPage(new PDPage());  

      //Saving the document 
      document.save("C:/PdfBox_Examples/sample.pdf");

      //Closing the document  
      document.close(); 
        
   }  
}

使用以下命令从命令提示符编译并执行保存的 Java 文件

javac LoadingExistingDocument.java  
java LoadingExistingDocument

执行后,上述程序加载指定的 PDF 文档并添加一个空白页,显示以下消息。

PDF loaded

如果您验证指定的路径,您可以找到添加到指定 PDF 文档的附加页面,如下所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_16

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 文档,它包含三个空白页面,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_17

此示例演示如何从现有 PDF 文档中删除页面。在这里,我们将加载上面指定的名为sample.pdf的 PDF 文档,从中删除一个页面,并将其保存在路径C:/PdfBox_Examples/中。将此代码保存在名为Removing_pages.java的文件中。

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("C:/PdfBox_Examples/sample.pdf");
      PDDocument document = PDDocument.load(file);
       
      //Listing the number of existing pages
      int noOfPages= document.getNumberOfPages();
      System.out.print(noOfPages);
       
      //Removing the pages
      document.removePage(2);
      
      System.out.println("page removed");

      //Saving the document
      document.save("C:/PdfBox_Examples/sample.pdf");

      //Closing the document
      document.close();

   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac RemovingPages.java 
java RemovingPages

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

3
page removed

如果你验证指定的路径,你可以发现需要的页面被删除了,文档中只剩下两页,如下图所示。

java中使用openpdf java操作pdf的开源工具_java_18

PDFBox - 文档属性

与其他文件一样,PDF 文档也具有文档属性。这些属性是键值对。每个属性都提供有关文档的特定信息。

以下是 PDF 文档的属性 -

S.No.

属性和描述

1

文件

此属性保存文件的名称。

2

标题

使用此属性,您可以设置文档的标题。

3

作者

使用此属性,您可以设置文档的作者姓名。

4

学科

使用此属性,您可以指定 PDF 文档的主题。

5

关键词

使用此属性,您可以列出我们可以用来搜索文档的关键字。

6

已创建

使用此属性,您可以设置为文档创建的日期。

7

修改的

使用此属性,您可以设置文档的修改日期。

8

应用

使用此属性,您可以设置文档的应用程序。

以下是 PDF 文档的文档属性表的屏幕截图。

java中使用openpdf java操作pdf的开源工具_apache_19

设置文档属性

PDFBox 为您提供了一个名为PDDocumentInformation的类。此类具有一组 setter 和 getter 方法。

此类的 setter 方法用于为文档的各种属性设置值,而 getter 方法用于检索这些值。

以下是PDDocumentInformation类的 setter 方法。

S.No.

方法和说明

1

setAuthor(字符串作者)

此方法用于设置名为Author的 PDF 文档的属性值。

2

setTitle(字符串标题)

此方法用于设置名为Title的 PDF 文档的属性值。

3

setCreator(字符串创建者)

此方法用于设置名为Creator的 PDF 文档的属性值。

4

setSubject(字符串主题)

此方法用于设置名为Subject的 PDF 文档的属性值。

5

setCreationDate(日历日期)

此方法用于设置名为CreationDate的 PDF 文档的属性值。

6

setModificationDate(日历日期)

此方法用于设置名为ModificationDate的 PDF 文档的属性值。

7

setKeywords(字符串关键字列表)

此方法用于设置 PDF 文档名为Keywords的属性的值。

例子

PDFBox 提供了一个名为PDDocumentInformation的类,该类提供了各种方法。这些方法可以为文档设置各种属性并检索它们。

此示例演示如何将作者、标题、日期和主题等属性添加到 PDF 文档。在这里,我们将创建一个名为doc_attributes.pdf的 PDF 文档,为其添加各种属性,并将其保存在路径C:/PdfBox_Examples/中。将此代码保存在名为AdditionalAttributes.java的文件中。

import java.io.IOException; 
import java.util.Calendar; 
import java.util.GregorianCalendar;
  
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;

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

      //Creating PDF document object
      PDDocument document = new PDDocument();

      //Creating a blank page
      PDPage blankPage = new PDPage();
       
      //Adding the blank page to the document
      document.addPage( blankPage );

      //Creating the PDDocumentInformation object 
      PDDocumentInformation pdd = document.getDocumentInformation();

      //Setting the author of the document
      pdd.setAuthor("Tutorialspoint");
       
      // Setting the title of the document
      pdd.setTitle("Sample document"); 
       
      //Setting the creator of the document 
      pdd.setCreator("PDF Examples"); 
       
      //Setting the subject of the document 
      pdd.setSubject("Example document"); 
       
      //Setting the created date of the document 
      Calendar date = new GregorianCalendar();
      date.set(2015, 11, 5); 
      pdd.setCreationDate(date);
      //Setting the modified date of the document 
      date.set(2016, 6, 5); 
      pdd.setModificationDate(date); 
       
      //Setting keywords for the document 
      pdd.setKeywords("sample, first example, my pdf"); 
 
      //Saving the document 
      document.save("C:/PdfBox_Examples/doc_attributes.pdf");

      System.out.println("Properties added successfully ");
       
      //Closing the document
      document.close();

   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac AddingAttributes.java 
java AddingAttributes

执行后,上述程序将所有指定的属性添加到显示以下消息的文档中。

Properties added successfully

现在,如果您访问给定的路径,您可以找到其中创建的 PDF。右键单击文档并选择文档属性选项,如下所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_20

这将为您提供文档属性窗口,您可以在此处观察文档的所有属性都设置为指定值。

java中使用openpdf java操作pdf的开源工具_apache_21

检索文档属性

您可以使用PDDocumentInformation类提供的getter方法检索文档的属性。

以下是PDDocumentInformation类的 getter 方法。

S.No.

方法和说明

1

获取作者()

此方法用于检索名为Author的 PDF 文档的属性值。

2

获取标题()

此方法用于检索名为Title的 PDF 文档的属性值。

3

获取创建者()

此方法用于检索名为Creator的 PDF 文档的属性值。

4

获取主题()

此方法用于检索名为Subject的 PDF 文档的属性值。

5

获取创建日期()

此方法用于检索名为CreationDate的 PDF 文档的属性值。

6

获取修改日期()

此方法用于检索名为ModificationDate的 PDF 文档的属性值。

7

获取关键字()

此方法用于检索名为“关键字”的 PDF 文档的属性值。

例子

此示例演示如何检索现有 PDF 文档的属性。在这里,我们将创建一个 Java 程序并加载名为doc_attributes.pdf的 PDF 文档,该文档保存在路径C:/PdfBox_Examples/中,并检索其属性。将此代码保存在名为RetrivingDocumentAttributes.java的文件中。

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

import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDDocumentInformation;

public class RetrivingDocumentAttributes {
   public static void main(String args[]) throws IOException {
      
      //Loading an existing document 
      File file = new File("C:/PdfBox_Examples/doc_attributes.pdf")
      PDDocument document = PDDocument.load(file);
      //Getting the PDDocumentInformation object
      PDDocumentInformation pdd = document.getDocumentInformation();

      //Retrieving the info of a PDF document
      System.out.println("Author of the document is :"+ pdd.getAuthor());
      System.out.println("Title of the document is :"+ pdd.getTitle());
      System.out.println("Subject of the document is :"+ pdd.getSubject());

      System.out.println("Creator of the document is :"+ pdd.getCreator());
      System.out.println("Creation date of the document is :"+ pdd.getCreationDate());
      System.out.println("Modification date of the document is :"+ 
         pdd.getModificationDate()); 
      System.out.println("Keywords of the document are :"+ pdd.getKeywords()); 
       
      //Closing the document 
      document.close();        
   }  
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac RetrivingDocumentAttributes.java 
java RetrivingDocumentAttributes

执行时,上述程序检索文档的所有属性并显示它们,如下所示。

Author of the document is :Tutorialspoint 
Title of the document is :Sample document 
Subject of the document is :Example document 
Creator of the document is :PDF Examples 
Creation date of the document is :11/5/2015
Modification date of the document is :6/5/2016
Keywords of the document are :sample, first example, my pdf

PDFBox - 添加文本

在上一章中,我们讨论了如何向 PDF 文档添加页面。在本章中,我们将讨论如何向现有 PDF 文档添加文本。

向现有 PDF 文档添加文本

您可以使用 PDFBox 库将内容添加到文档中,它为您提供了一个名为 PDPageContentStream 的类,其中包含在 PDFDocument 的页面中插入文本、图像和其他类型的内容所需的方法。

以下是创建一个空文档并将内容添加到其中的页面的步骤。

第 1 步:加载现有文档

您可以使用PDDocument 类的load()方法加载现有文档。因此,实例化该类并加载所需的文档,如下所示。

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

第 2 步:获取所需页面

您可以使用getPage()方法在文档中获取所需的页面。通过将其索引传递给此方法来检索所需页面的对象,如下所示。

PDPage page = doc.getPage(1);

第 3 步:准备内容流

您可以使用PDPageContentStream类的对象插入各种数据元素。您需要将文档对象和页面对象传递给此类的构造函数,因此,通过传递前面步骤中创建的这两个对象来实例化此类,如下所示。

PDPageContentStream contentStream = new PDPageContentStream(doc, page);

第 4 步:开始文本

在 PDF 文档中插入文本时,您可以使用 PDPageContentStream 类的 beginText() 和 endText() 方法指定文本的起点和终点,如下所示。

contentStream.beginText(); 
……………………….. 
code to add text content 
……………………….. 
contentStream.endText();

因此,使用beginText()方法开始文本,如下所示。

contentStream.beginText();

第 5 步:设置文本的位置

使用newLineAtOffset()方法,您可以在页面中的内容流上设置位置。

//Setting the position for the line 
contentStream.newLineAtOffset(25, 700);

第 6 步:设置字体

您可以使用PDPageContentStream类的setFont()方法将文本的字体设置为所需的样式,如下所示。对于此方法,您需要传递字体的类型和大小。

contentStream.setFont( font_type, font_size );

第 7 步:插入文本

您可以使用PDPageContentStream类的ShowText()方法将文本插入页面,如下所示。此方法接受字符串形式的所需文本。

contentStream.showText(text);

第 8 步:结束文本

插入文本后,您需要使用PDPageContentStream类的endText()方法结束文本,如下所示。

contentStream.endText();

第 9 步:关闭 PDPageContentStream

使用close()方法关闭PDPageContentStream对象,如下所示。

contentstream.close();

第 10 步:保存文档

添加所需内容后,使用PDDocument类的save()方法保存 PDF 文档,如以下代码块所示。

doc.save("Path");

第 11 步:关闭文档

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

doc.close();

例子

此示例演示如何将内容添加到文档中的页面。在这里,我们将创建一个 Java 程序来加载名为my_doc.pdf的 PDF 文档,该文档保存在路径C:/PdfBox_Examples/中,并在其中添加一些文本。将此代码保存在名为AdditionalContent.java的文件中。

import java.io.File; 
import java.io.IOException;
  
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage; 
import org.apache.pdfbox.pdmodel.PDPageContentStream; 
import org.apache.pdfbox.pdmodel.font.PDType1Font;
  
public class AddingContent {
   public static void main (String args[]) throws IOException {

      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/my_doc.pdf");
      PDDocument document = PDDocument.load(file);
       
      //Retrieving the pages of the document 
      PDPage page = document.getPage(1);
      PDPageContentStream contentStream = new PDPageContentStream(document, page);
      
      //Begin the Content stream 
      contentStream.beginText(); 
       
      //Setting the font to the Content stream  
      contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);

      //Setting the position for the line 
      contentStream.newLineAtOffset(25, 500);

      String text = "This is the sample document and we are adding content to it.";

      //Adding text in the form of string 
      contentStream.showText(text);      

      //Ending the content stream
      contentStream.endText();

      System.out.println("Content added");

      //Closing the content stream
      contentStream.close();

      //Saving the document
      document.save(new File("C:/PdfBox_Examples/new.pdf"));

      //Closing the document
      document.close();
   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac AddingContent.java 
java AddingContent

执行后,上述程序将给定文本添加到文档并显示以下消息。

Content added

如果您验证指定路径中的 PDF 文档new.pdf,您可以观察到给定的内容已添加到文档中,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_22

PDFBox - 添加多行

在上一章提供的示例中,我们讨论了如何在 PDF 的页面中添加文本,但通过该程序,您只能添加适合单行的文本。如果您尝试添加更多内容,则不会显示所有超出行距的文本。

例如,如果您通过传递以下字符串来执行上一章中的上述程序,则只会显示其中的一部分。

String text = "This is an example of adding text to a page in the pdf document. we can
   add as many lines as we want like this using the showText() method of the 
   ContentStream class";

将上一章示例的字符串文本替换为上述字符串并执行。执行后,您将收到以下输出。

java中使用openpdf java操作pdf的开源工具_java_23

如果你仔细观察输出,你会注意到只显示了字符串的一部分。

为了向 PDF 添加多行,您需要使用setLeading()方法设置前导,并在完成每一行后使用newline()方法切换到新行。

脚步

以下是创建一个空文档并将内容添加到其中的页面的步骤。

第 1 步:加载现有文档

您可以使用PDDocument 类的load()方法加载现有文档。因此,实例化该类并加载所需的文档,如下所示。

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

第 2 步:获取所需页面

您可以使用getPage()方法在文档中获取所需的页面。通过将其索引传递给此方法来检索所需页面的对象,如下所示。

PDPage page = doc.getPage(1);

第 3 步:准备内容流

您可以使用名为PDPageContentStream的类的对象插入各种数据元素。您需要将文档对象和页面对象传递给此类的构造函数,因此,通过传递前面步骤中创建的这两个对象来实例化此类,如下所示。

PDPageContentStream contentStream = new PDPageContentStream(doc, page);

第 4 步:开始文本

在 PDF 文档中插入文本时,您可以使用PDPageContentStream类的beginText()endText()方法指定文本的起点和终点,如下所示。

contentStream.beginText(); 
……………………….. 
code to add text content 
……………………….. 
contentStream.endText();

因此,使用beginText()方法开始文本,如下所示。

contentStream.beginText();

第 5 步:设置文本的位置

使用newLineAtOffset()方法,您可以在页面中的内容流上设置位置。

//Setting the position for the line 
contentStream.newLineAtOffset(25, 700);

第 6 步:设置字体

您可以使用PDPageContentStream类的setFont()方法将文本的字体设置为所需的样式,如下所示,该方法需要传递字体的类型和大小。

contentStream.setFont( font_type, font_size );

第 7 步:设置文本前导

您可以使用setLeading()方法设置文本前导,如下所示。

contentStream.setLeading(14.5f);

第 8 步:使用 newline() 插入多个字符串

您可以使用PDPageContentStream类的ShowText()方法插入多个字符串,方法是使用newline()方法将每个字符串分开,如下所示。

contentStream. ShowText(text1); 
contentStream.newLine(); 
contentStream. ShowText(text2);

第 9 步:结束文本

插入文本后,您需要使用PDPageContentStream类的endText()方法结束文本,如下所示。

contentStream.endText();

第 10 步:关闭 PDPageContentStream

使用close()方法关闭PDPageContentStream对象,如下所示。

contentstream.close();

第 11 步:保存文档

添加所需内容后,使用PDDocument类的save()方法保存 PDF 文档,如以下代码块所示。

doc.save("Path");

第 12 步:关闭文档

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

doc.close();

例子

此示例演示如何使用 PDFBox 在 PDF 中添加多行。将此程序保存在名为AddMultipleLines.java 的文件中。

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

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

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

      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/my_pdf.pdf");
      PDDocument doc = document.load(file);
       
      //Creating a PDF Document
      PDPage page = doc.getPage(1);  
       
      PDPageContentStream contentStream = new PDPageContentStream(doc, page); 
       
      //Begin the Content stream 
      contentStream.beginText(); 
       
      //Setting the font to the Content stream
      contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
       
      //Setting the leading
      contentStream.setLeading(14.5f);

      //Setting the position for the line
      contentStream.newLineAtOffset(25, 725);

      String text1 = "This is an example of adding text to a page in the pdf document.
         we can add as many lines";
      String text2 = "as we want like this using the ShowText()  method of the
         ContentStream class";

      //Adding text in the form of string
      contentStream. ShowText(text1);
      contentStream.newLine();
      contentStream. ShowText(text2);
      //Ending the content stream
      contentStream.endText();

      System.out.println("Content added");

      //Closing the content stream
      contentStream.close();

      //Saving the document
      doc.save(new File("C:/PdfBox_Examples/new.pdf"));
            
      //Closing the document
      doc.close();
   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac AddMultipleLines.java 
java AddMultipleLines

执行后,上述程序将给定文本添加到文档并显示以下消息。

Content added

如果您验证指定路径中的 PDF 文档new.pdf,您可以观察到给定的内容以多行添加到文档中,如下所示。

java中使用openpdf java操作pdf的开源工具_apache_24

PDFBox - 阅读文本

在上一章中,我们已经了解了如何将文本添加到现有的 PDF 文档中。在本章中,我们将讨论如何从现有的 PDF 文档中读取文本。

从现有 PDF 文档中提取文本

提取文本是 PDF 框库的主要功能之一。您可以使用PDFTextStripper类的getText()方法提取文本。此类从给定的 PDF 文档中提取所有文本。

以下是从现有 PDF 文档中提取文本的步骤。

第 1 步:加载现有 PDF 文档

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

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

第 2 步:实例化 PDFTextStripper 类

PDFTextStripper类提供了从 PDF 文档中检索文本的方法,因此,如下所示实例化此类。

PDFTextStripper pdfStripper = new PDFTextStripper();

第 3 步:检索文本

您可以使用PDFTextStripper类的getText()方法从 PDF 文档中读取/检索页面的内容。对于此方法,您需要将文档对象作为参数传递。此方法检索给定文档中的文本并以 String 对象的形式返回。

String text = pdfStripper.getText(document);

第 4 步:关闭文档

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

document.close();

例子

假设我们有一个 PDF 文档,其中包含一些文本,如下所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_25

此示例演示如何从上述 PDF 文档中读取文本。在这里,我们将创建一个 Java 程序并加载一个名为new.pdf的 PDF 文档,该文档保存在路径C:/PdfBox_Examples/中。将此代码保存在名为ReadingText.java的文件中。

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

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class ReadingText {

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

      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/new.pdf");
      PDDocument document = PDDocument.load(file);

      //Instantiate PDFTextStripper class
      PDFTextStripper pdfStripper = new PDFTextStripper();

      //Retrieving text from PDF document
      String text = pdfStripper.getText(document);
      System.out.println(text);

      //Closing the document
      document.close();

   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac ReadingText.java 
java ReadingText

执行后,上述程序从给定的 PDF 文档中检索文本并将其显示如下所示。

This is an example of adding text to a page in the pdf document. we can add as many lines
as we want like this using the ShowText() method of the ContentStream class.

PDFBox - 插入图片

在上一章中,我们已经了解了如何从现有 PDF 文档中提取文本。在本章中,我们将讨论如何将图像插入 PDF 文档。

将图像插入 PDF 文档

您可以分别使用PDImageXObjectPDPageContentStream类的createFromFile()drawImage()方法将图像插入 PDF 文档。

以下是从现有 PDF 文档中提取文本的步骤。

第 1 步:加载现有 PDF 文档

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

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

第 2 步:检索页面

在 PDF 文档中选择一个页面并使用getPage()方法检索其页面对象,如下所示。

PDPage page = doc.getPage(0);

第 3 步:创建 PDImageXObject 对象

PDFBox 库中的PDImageXObject类代表一个图像。它提供了执行与图像相关的操作所需的所有方法,例如插入图像、设置其高度、设置其宽度等。

我们可以使用createFromFile()方法创建此类的对象。对于此方法,我们需要以字符串的形式传递要添加的图像的路径以及需要添加图像的文档对象。

PDImageXObject pdImage = PDImageXObject.createFromFile("C:/logo.png", doc);

第 4 步:准备内容流

您可以使用名为PDPageContentStream的类的对象插入各种数据元素。您需要将文档对象和页面对象传递给此类的构造函数,因此,通过传递前面步骤中创建的这两个对象来实例化此类,如下所示。

PDPageContentStream contentStream = new PDPageContentStream(doc, page);

第 5 步:在 PDF 文档中绘制图像

您可以使用drawImage()方法在 PDF 文档中插入图像。对于此方法,您需要添加在上述步骤中创建的图像对象以及图像所需的尺寸(宽度和高度),如下所示。

contentstream.drawImage(pdImage, 70, 250);

第 6 步:关闭 PDPageContentStream

使用close()方法关闭PDPageContentStream对象,如下所示。

contentstream.close();

第 7 步:保存文档

添加所需内容后,使用PDDocument类的save()方法保存 PDF 文档,如以下代码块所示。

doc.save("Path");

第 8 步:关闭文档

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

doc.close();

例子

假设我们有一个名为sample.pdf的 PDF 文档,位于路径C:/PdfBox_Examples/中,其中包含如下所示的空白页面。

java中使用openpdf java操作pdf的开源工具_java_26

此示例演示如何将图像添加到上述 PDF 文档的空白页。在这里,我们将加载名为sample.pdf的 PDF 文档并为其添加图像。将此代码保存在名为InsertingImage.java 的文件中。

import java.io.File;
  
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

public class InsertingImage {

   public static void main(String args[]) throws Exception {
      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/sample.pdf");
      PDDocument doc = PDDocument.load(file);
        
      //Retrieving the page
      PDPage page = doc.getPage(0);
       
      //Creating PDImageXObject object
      PDImageXObject pdImage = PDImageXObject.createFromFile("C:/PdfBox_Examples/logo.png",doc);
       
      //creating the PDPageContentStream object
      PDPageContentStream contents = new PDPageContentStream(doc, page);

      //Drawing the image in the PDF document
      contents.drawImage(pdImage, 70, 250);

      System.out.println("Image inserted");

      //Closing the PDPageContentStream object
      contents.close();
		
      //Saving the document
      doc.save("C:/PdfBox_Examples/sample.pdf");
            
      //Closing the document
      doc.close();
     
   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac InsertingImage.java 
java InsertingImage

执行后,上述程序将图像插入给定 PDF 文档的指定页面,显示以下消息。

Image inserted

如果您验证文档sample.pdf,您可以观察到其中插入了一张图像,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_27

PDFBox - 加密 PDF 文档

在上一章中,我们已经了解了如何在 PDF 文档中插入图像。在本章中,我们将讨论如何加密 PDF 文档。

加密 PDF 文档

您可以使用StandardProtectionPolicyAccessPermission 类提供的方法加密 PDF 文档。

AccessPermission类用于通过为其分配访问权限来保护 PDF 文档。使用此类,您可以限制用户执行以下操作。

  • 打印文档
  • 修改文档内容
  • 复制或提取文档内容
  • 添加或修改注释
  • 填写交互式表单域
  • 提取文本和图形以供视障人士使用
  • 组装文件
  • 打印质量下降

StandardProtectionPolicy类用于向文档添加基于密码的保护。

以下是加密现有 PDF 文档的步骤。

第 1 步:加载现有 PDF 文档

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

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

步骤 2:创建访问权限对象

实例化AccessPermission类,如下所示。

AccessPermission accessPermission = new AccessPermission();

第 3 步:创建 StandardProtectionPolicy 对象

通过传递所有者密码、用户密码和AccessPermission对象来实例化StandardProtectionPolicy类,如下所示。

StandardProtectionPolicy spp = new StandardProtectionPolicy("1234","1234",accessPermission);

第 4 步:设置加密密钥的长度

使用setEncryptionKeyLength()方法设置加密密钥长度,如下所示。

spp.setEncryptionKeyLength(128);

第 5 步:设置权限

使用StandardProtectionPolicy 类的setPermissions()方法设置权限。此方法接受AccessPermission对象作为参数。

spp.setPermissions(accessPermission);

第 6 步:保护文档

您可以使用PDDocument类的protect()方法保护您的文档,如下所示。将StandardProtectionPolicy对象作为参数传递给此方法。

document.protect(spp);

第 7 步:保存文档

添加所需内容后,使用PDDocument类的save()方法保存 PDF 文档,如以下代码块所示。

document.save("Path");

第 8 步:关闭文档

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

document.close();

例子

假设我们有一个名为sample.pdf的 PDF 文档,位于路径C:/PdfBox_Examples/中,页面为空,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_28

此示例演示如何加密上述 PDF 文档。在这里,我们将加载名为sample.pdf的 PDF 文档并对其进行加密。将此代码保存在名为EncriptingPDF.java 的文件中。

import java.io.File;
 
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
public class EncriptingPDF {
  
   public static void main(String args[]) throws Exception {
      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/sample.pdf");
      PDDocument document = PDDocument.load(file);
   
      //Creating access permission object
      AccessPermission ap = new AccessPermission();         

      //Creating StandardProtectionPolicy object
      StandardProtectionPolicy spp = new StandardProtectionPolicy("1234", "1234", ap);

      //Setting the length of the encryption key
      spp.setEncryptionKeyLength(128);

      //Setting the access permissions
      spp.setPermissions(ap);

      //Protecting the document
      document.protect(spp);

      System.out.println("Document encrypted");

      //Saving the document
      document.save("C:/PdfBox_Examples/sample.pdf");
      //Closing the document
      document.close();

   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac EncriptingPDF.java
java EncriptingPDF

执行后,上述程序会加密显示以下消息的给定 PDF 文档。

Document encrypted

如果您尝试打开文档sample.pdf,则无法打开,因为它已加密。相反,它会提示输入密码以打开文档,如下所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_29

PDFBox - PDF 文档中的 JavaScript

在上一章中,我们学习了如何将图像插入 PDF 文档。在本章中,我们将讨论如何将 JavaScript 添加到 PDF 文档中。

将 JavaScript 添加到 PDF 文档

您可以使用PDActionJavaScript类将 JavaScript 操作添加到 PDF 文档。这代表一个 JavaScript 动作。

以下是将 JavaScript 操作添加到现有 PDF 文档的步骤。

第 1 步:加载现有 PDF 文档

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

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

第 2 步:创建 PDActionJavaScript 对象

实例化PDActionJavaScript对象,如下所示。将所需的 JavaScript 以 String 的形式传递给该类的构造函数,如下所示。

String javaScript = "app.alert( {cMsg: 'this is an example', nIcon: 3,"
   + " nType: 0,cTitle: 'PDFBox Javascript example' } );";       
PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);

第 3 步:在文档中嵌入 Java 脚本

将所需的字符串嵌入到 PDF 文档中,如下所示。

document.getDocumentCatalog().setOpenAction(PDAjavascript);

第 4 步:保存文档

添加所需内容后,使用PDDocument类的save()方法保存 PDF 文档,如以下代码块所示。

document.save("Path");

第 5 步:关闭文档

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

document.close();

例子

假设我们有一个名为sample.pdf的 PDF 文档,位于路径C:/PdfBox_Examples/中,页面为空,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_30

此示例演示如何在上述 PDF 文档中嵌入 JavaScript。在这里,我们将加载名为sample.pdf的 PDF 文档并在其中嵌入 JavaScript。将此代码保存在名为AddJavaScript.java 的文件中。

import java.io.File;
  
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;

public class AddJavaScript {

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

      //Loading an existing file
      File file = new File("C:/PdfBox_Examples/new.pdf");
      PDDocument document = PDDocument.load(file);

      String javaScript = "app.alert( {cMsg: 'this is an example', nIcon: 3,"
         + " nType: 0, cTitle: 'PDFBox Javascript example’} );";

      //Creating PDActionJavaScript object 
      PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);

      //Embedding java script
      document.getDocumentCatalog().setOpenAction(PDAjavascript);

      //Saving the document
      document.save( new File("C:/PdfBox_Examples/new.pdf") );
      System.out.println("Data added to the given PDF"); 

      //Closing the document
      document.close();

   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac AddJavaScript.java 
java AddJavaScript

执行后,上述程序将 JavaScript 嵌入给定的 PDF 文档中,显示以下消息。

Data added to the given PDF

如果您尝试打开文档new.pdf,它将显示如下所示的警告消息。

java中使用openpdf java操作pdf的开源工具_Java_31

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的类包含拆分给定 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();

例子

假设在路径C:\PdfBox_Examples\中有一个名为sample.pdf的 PDF 文档,该文档包含两页——一页包含图像,另一页包含文本,如下所示。

java中使用openpdf java操作pdf的开源工具_apache_32

此示例演示如何拆分上述 PDF 文档。在这里,我们将名为sample.pdf的 PDF 文档拆分为两个不同的文档sample1.pdfsample2.pdf。将此代码保存在名为SplitPages.java 的文件中。

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("C:/PdfBox_Examples/sample.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("C:/PdfBox_Examples/sample"+ i++ +".pdf");
      }
      System.out.println("Multiple PDF’s created");
      document.close();
   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件

javac SplitPages.java 
java SplitPages

执行后,上述程序会加密显示以下消息的给定 PDF 文档。

Multiple PDF’s created

如果您验证给定的路径,您可以观察到创建了多个名为sample1sample2的 PDF ,如下所示。

java中使用openpdf java操作pdf的开源工具_apache_33

java中使用openpdf java操作pdf的开源工具_apache_34

PDFBox - 合并多个 PDF 文档

在上一章中,我们已经了解了如何将给定的 PDF 文档拆分为多个文档。现在让我们学习如何将多个 PDF 文档合并为一个文档。

合并多个 PDF 文档

您可以使用名为PDFMergerUtility的类将多个 PDF 文档合并为单个 PDF 文档,该类提供将两个或多个 PDF 文档合并为单个 PDF 文档的方法。

以下是合并多个 PDF 文档的步骤。

步骤 1:实例化 PDFMergerUtility 类

实例化合并实用程序类,如下所示。

PDFMergerUtility PDFmerger = new PDFMergerUtility();

第二步:设置目标文件

使用 setDestinationFileName() 方法设置目标文件,如下所示。

PDFmerger.setDestinationFileName("C:/PdfBox_Examples/data1/merged.pdf");

第三步:设置源文件

使用 addSource() 方法设置源文件,如下所示。

File file = new File("path of the document")
PDFmerger.addSource(file);

第 4 步:合并文档

使用 PDFmerger 类的 mergeDocuments() 方法合并文档,如下所示。

PDFmerger.mergeDocuments();

例子

假设我们有两个 PDF 文档 — sample1.pdfsample2.pdf,位于路径C:\PdfBox_Examples\中,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_35

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_36

本示例演示如何合并上述 PDF 文档。在这里,我们将名为sample1.pdfsample2.pdf的 PDF 文档合并到一个 PDF 文档merge.pdf中。将此代码保存在名为MergePDFs.java 的文件中。

import org.apache.pdfbox.multipdf.PDFMergerUtility; 
import java.io.File; 
import java.io.IOException;
public class MergePDFs {
   public static void main(String[] args) throws IOException {
      File file1 = new File("C:\\EXAMPLES\\Demo1.pdf");       
      File file2 = new File("C:\\EXAMPLES\\Demo2.pdf");    
		
      //Instantiating PDFMergerUtility class
      PDFMergerUtility PDFmerger = new PDFMergerUtility();
		
      //Setting the destination file
      PDFmerger.setDestinationFileName("C:\\Examples\\merged.pdf");
		
      //adding the source files
      PDFmerger.addSource(file1);
      PDFmerger.addSource(file2);
		
      //Merging the two documents
      PDFmerger.mergeDocuments();
      System.out.println("Documents merged");
   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac MergePDFs.java 
java MergePDFs

执行后,上述程序会加密显示以下消息的给定 PDF 文档。

Documents merged

如果您验证给定的路径,您可以观察到创建了一个名为merge.pdf的 PDF 文档,其中包含两个源文档的页面,如下所示。

java中使用openpdf java操作pdf的开源工具_java_37

PDFBox - 将 PDF 转换为图像

在上一章中,我们已经了解了如何合并多个 PDF 文档。在本章中,我们将了解如何从 PDF 文档的页面中提取图像。

从 PDF 文档生成图像

PDFBox 库为您提供了一个名为PDFRenderer的类,它将 PDF 文档呈现为 AWT BufferedImage。

以下是从 PDF 文档生成图像的步骤。

第 1 步:加载现有 PDF 文档

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

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

第 2 步:实例化 PDFRenderer 类

名为PDFRenderer的类将 PDF 文档呈现为AWT BufferedImage。因此,您需要实例化此类,如下所示。此类的构造函数接受一个文档对象;传递上一步中创建的文档对象,如下所示。

PDFRenderer renderer = new PDFRenderer(document);

第 3 步:从 PDF 文档渲染图像

您可以使用 Renderer 类的方法renderImage()在特定页面中渲染图像,您需要将要渲染图像的页面的索引传递给此方法。

BufferedImage image = renderer.renderImage(0);

第 4 步:将图像写入文件

您可以使用write()方法将上一步中渲染的图像写入文件。对于此方法,您需要传递三个参数 -

  • 渲染的图像对象。
  • 表示图像类型(jpg 或 png)的字符串。
  • 您需要将提取的图像保存到的文件对象。
ImageIO.write(image, "JPEG", new File("C:/PdfBox_Examples/myimage.jpg"));

第 5 步:关闭文档

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

document.close();

例子

假设我们有一个 PDF 文档——路径C:\PdfBox_Examples\中的sample.pdf,它的第一页包含一个图像,如下所示。

java中使用openpdf java操作pdf的开源工具_java中使用openpdf_38

本示例演示如何将上述 PDF 文档转换为图像文件。在这里,我们将检索 PDF 文档第一页中的图像并将其保存为myimage.jpg。将此代码另存为PdfToImage.java

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class PdfToImage {

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

      //Loading an existing PDF document
      File file = new File("C:/PdfBox_Examples/sample.pdf");
      PDDocument document = PDDocument.load(file);
       
      //Instantiating the PDFRenderer class
      PDFRenderer renderer = new PDFRenderer(document);

      //Rendering an image from the PDF document
      BufferedImage image = renderer.renderImage(0);

      //Writing the image to a file
      ImageIO.write(image, "JPEG", new File("C:/PdfBox_Examples/myimage.jpg"));
       
      System.out.println("Image created");
       
      //Closing the document
      document.close();

   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac PdfToImage.java 
java PdfToImage

执行后,上述程序检索给定 PDF 文档中显示以下消息的图像。

Image created

如果您验证给定的路径,您可以观察到图像已生成并保存为myimage.jpg,如下所示。

java中使用openpdf java操作pdf的开源工具_java_39

PDFBox - 添加矩形

本章教您如何在 PDF 文档的页面中创建颜色框。

在 PDF 文档中创建框

您可以使用PDPageContentStream类的addRect()方法 在 PDF 页面中添加矩形框。

以下是在 PDF 文档页面中创建矩形形状的步骤。

第 1 步:加载现有 PDF 文档

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

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

第 2 步:获取页面对象

您需要使用PDDocument类的getPage()方法检索要在其中添加矩形的所需页面的PDPage对象。对于此方法,您需要传递要添加矩形的页面的索引。

PDPage page = document.getPage(0);

第 3 步:准备内容流

您可以使用名为PDPageContentStream的类的对象插入各种数据元素。您需要将文档对象和页面对象传递给此类的构造函数,因此,通过传递前面步骤中创建的这两个对象来实例化此类,如下所示。

PDPageContentStream contentStream = new PDPageContentStream(document, page);

第 4 步:设置非描边颜色

您可以使用 PDPageContentStream 类的 setNonStrokingColor() 方法将非描边颜色设置矩形。对于此方法,您需要将所需的颜色作为参数传递,如下所示。

contentStream.setNonStrokingColor(Color.DARK_GRAY);

第五步:画矩形

使用addRect()方法绘制具有所需尺寸的矩形。对于此方法,您需要传递要添加的矩形的尺寸,如下所示。

contentStream.addRect(200, 650, 100, 100);

第6步:填充矩形

PDPageContentStream类的fill()方法用所需的颜色填充指定维度之间的路径,如下所示。

contentStream.fill();

第 7 步:关闭文档

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

document.close();

例子

假设我们在路径C:\PdfBox_Examples\中有一个名为blankpage.pdf的 PDF 文档,其中包含一个空白页,如下所示。

java中使用openpdf java操作pdf的开源工具_apache_40

此示例演示如何在 PDF 文档中创建/插入矩形。在这里,我们将在空白 PDF 中创建一个框。将此代码另存为AddRectangles.java

import java.awt.Color;
import java.io.File;
  
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
public class ShowColorBoxes {

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

      //Loading an existing document
      File file = new File("C:/PdfBox_Examples/BlankPage.pdf");
      PDDocument document = PDDocument.load(file);
        
      //Retrieving a page of the PDF Document
      PDPage page = document.getPage(0);

      //Instantiating the PDPageContentStream class
      PDPageContentStream contentStream = new PDPageContentStream(document, page);
       
      //Setting the non stroking color
      contentStream.setNonStrokingColor(Color.DARK_GRAY);

      //Drawing a rectangle 
      contentStream.addRect(200, 650, 100, 100);

      //Drawing a rectangle
      contentStream.fill();

      System.out.println("rectangle added");

      //Closing the ContentStream object
      contentStream.close();

      //Saving the document
      File file1 = new File("C:/PdfBox_Examples/colorbox.pdf");
      document.save(file1);

      //Closing the document
      document.close();
   }
}

使用以下命令从命令提示符编译并执行保存的 Java 文件。

javac AddRectangles.java 
java AddRectangles

执行后,上述程序会在 PDF 文档中创建一个矩形,显示以下图像。

Rectangle created

如果您验证给定路径并打开保存的文档 - colorbox.pdf,您可以观察到其中插入了一个框,如下所示。

java中使用openpdf java操作pdf的开源工具_Java_41