目录

PDFBox - 快速指南

PDFBox - Overview

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

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

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

  • Adobe PDF Library - 该库提供C ++,.NET和Java等语言的API,使用它可以编辑,查看打印和从PDF文档中提取文本。

  • Formatting Objects Processor - 由XSL格式化对象和输出独立格式化程序驱动的开源打印格式化程序。 主要输出目标是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的显着特征 -

  • Extract Text - 使用PDFBox,您可以从PDF文件中提取Unicode文本。

  • Split & Merge - 使用PDFBox,您可以将单个PDF文件分成多个文件,并将它们合并为一个文件。

  • Fill Forms - 使用PDFBox,您可以在文档中填写表单数据。

  • Print - 使用PDFBox,您可以使用标准Java打印API打印PDF文件。

  • Save as Image - 使用PDFBox,您可以将PDF保存为图像文件,如PNG或JPEG。

  • Create PDFs - 使用PDFBox,您可以通过创建Java程序创建新的PDF文件,还可以包含图像和字体。

  • Signing - 使用PDFBox,您可以将数字签名添加到PDF文件。

PDFBox的应用

以下是PDFBox的应用 -

  • Apache Nutch - Apache Nutch是一个开源的网络搜索软件。 它建立在Apache Lucene的基础上,添加了特定于Web的内容,例如爬虫,链接图数据库,HTML和其他文档格式的解析器等。

  • Apache Tika - Apache Tika是一个工具包,用于使用现有的解析器库从各种文档中检测和提取元数据和结构化文本内容。

PDFBox的组件

以下是PDFBox的四个主要组成部分 -

  • PDFBox - 这是PDFBox的主要部分。 它包含与内容提取和操作相关的类和接口。

  • FontBox - 它包含与font相关的类和接口,使用这些类我们可以修改PDF文档的文本字体。

  • XmpBox - 包含处理XMP元数据的类和接口。

  • Preflight - 此组件用于根据PDF/A-1b标准验证PDF文件。

PDFBox - Environment

安装PDFBox

以下是下载Apache PDFBox的步骤 -

Step 1 - 点击以下链接打开Apache PDFBox的主页 - https://pdfbox.apache.org/

Step 2 - 以上链接将引导您进入主页,如以下屏幕截图所示 -

PDFBox主页

Step 3 - 现在,点击上面屏幕截图中突出显示的Downloads链接。 点击后,您将进入PDFBox的下载页面,如下面的屏幕截图所示。

PDFBox Downloads.jpg

Step 4 - 在“下载”页面中,您将拥有PDFBox的链接。 单击最新版本的相应链接。 例如,我们选择PDFBox 2.0.1 ,点击此按钮,您将被定向到所需的jar文件,如下面的屏幕截图所示。

PDFBox Jarfiles.jpg

Step 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的步骤 -

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

Step 2 - 打开Eclipse,单击File,New,然后打开一个新项目,如以下屏幕截图所示。

Eclipse文件菜单

Step 3 - 选择项目后,您将看到“ New Project向导。 在此向导中,选择Java项目,然后单击“ Next按钮继续,如以下屏幕截图所示。

Eclipse Newproject向导

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

创建项目向导

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

Eclipse构建路径

Step 6 - 单击Build Path选项,您将进入Java Build Path wizard 。 选择Add External JARs ,如以下屏幕截图所示。

Eclipse外部罐子

Step 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 ,如图所示在下面的截图中。

Jar文件位置

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

Jar文件已添加

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

Eclipse Jar文件

Using pom.xml

将项目转换为maven项目,并将以下内容添加到其pom.xml.

<project xmlns="https://maven.apache.org/POM/4.0.0"
   xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
   https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>my_project</groupId>
   <artifactId>my_project</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <build>
      <sourceDirectory>src</sourceDirectory>
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
               <source>1.8</source>
               <target>1.8</target>
            </configuration> 
         </plugin>
      </plugins> 
   </build> 
   <dependencies>  
      <dependency> 
         <groupId>org.apache.pdfbox</groupId> 
         <artifactId>pdfbox</artifactId> 
         <version>2.0.1</version> 
      </dependency>   
      <dependency> 
         <groupId>org.apache.pdfbox</groupId> 
         <artifactId>fontbox</artifactId> 
         <version>2.0.0</version> 
      </dependency>
      <dependency>  
         <groupId>org.apache.pdfbox</groupId> 
         <artifactId>jempbox</artifactId> 
         <version>1.8.11</version> 
      </dependency> 
      <dependency>
         <groupId>org.apache.pdfbox</groupId> 
         <artifactId>xmpbox</artifactId> 
         <version>2.0.0</version> 
      </dependency> 
      <dependency> 
         <groupId>org.apache.pdfbox</groupId> 
         <artifactId>preflight</artifactId> 
         <version>2.0.0</version> 
      </dependency> 
      <dependency> 
         <groupId>org.apache.pdfbox</groupId> 
         <artifactId>pdfbox-tools</artifactId> 
         <version>2.0.0</version> 
      </dependency>
   </dependencies>
</project>

PDFBox - Creating a PDF Document

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

创建空PDF文档

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

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

第1步:创建一个空文档

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

PDDocument document = new PDDocument();

第2步:保存文档

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

document.save("Path");

第3步:关闭文档

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

document.close();

例子 (Example)

此示例演示了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文档,如下所示。

我的文件已保存

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

空PDF

PDFBox - Adding Pages

在上一章中,我们已经了解了如何创建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();

例子 (Example)

此示例演示如何创建PDF文档并向其添加页面。 在这里,我们将创建一个名为my_doc.pdf的PDF文档,并进一步向其添加10个空白页,并将其保存在路径C:/PdfBox_Examples/ 。 将此代码保存在名为Adding_pages.java.的文件中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文档,如以下屏幕截图所示。

创建文档

PDFBox - Loading a Document

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

加载现有PDF文档

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

第1步:加载现有PDF文档

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

File file = new File("path of the document") 
<b class="notranslate">PDDocument</b>.load(file);

第2步:执行所需的操作

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

第3步:保存文档

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

document.save("Path");

第4步:关闭文档

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

document.close();

例子 (Example)

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

加载文件

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

Step 1 - 将此代码保存在名为LoadingExistingDocument.java.的文件中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文档的其他页面,如下所示。

文档中的附加页面

PDFBox - Removing Pages

现在让我们学习如何从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();

例子 (Example)

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

之前删除页面

此示例演示如何从现有PDF文档中删除页面。 在这里,我们将加载上面指定的PDF文档sample.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.<i>load</i>(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

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

之后删除页面

PDFBox - Document Properties

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

以下是PDF文档的属性 -

S.No. 财产和描述
1

File

此属性保存文件的名称。

2

Title

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

3

Author

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

4

Subject

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

5

Keywords

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

6

Created

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

7

Modified

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

8

Application

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

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

PDF属性

设置文档属性

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

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

以下是PDDocumentInformation类的setter方法。

S.No. 方法和描述
1

setAuthor(String author)

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

2

setTitle(String title)

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

3

setCreator(String creator)

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

4

setSubject(String subject)

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

5

setCreationDate(Calendar date)

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

6

setModificationDate(Calendar date)

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

7

setKeywords(String keywords list)

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

例子 (Example)

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

此示例演示如何向PDF文档添加“ Author, Title, Date, and Subject等属性。 在这里,我们将创建一个名为doc_attributes.pdf的PDF文档, doc_attributes.pdf添加各种属性,并将其保存在路径C:/PdfBox_Examples/ 。 将此代码保存在名为AddingAttributes.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("IoWiki");
      // 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。 右键单击文档并选择文档属性选项,如下所示。

文档属性

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

属性菜单

检索文档属性

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

以下是PDDocumentInformation类的getter方法。

S.No. 方法和描述
1

getAuthor()

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

2

getTitle()

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

3

getCreator()

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

4

getSubject()

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

5

getCreationDate()

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

6

getModificationDate()

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

7

getKeywords()

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

例子 (Example)

此示例演示如何检索现有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 :IoWiki 
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 - Adding Text

在上一章中,我们讨论了如何将页面添加到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();

例子 (Example)

此示例演示如何将内容添加到文档中的页面。 在这里,我们将创建一个Java程序来加载名为my_doc.pdf的PDF文档,该文档保存在路径C:/PdfBox_Examples/ ,并向其中添加一些文本。 将此代码保存在名为AddingContent.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 ,则可以观察到给定内容已添加到文档中,如下所示。

添加文字

PDFBox - Adding Multiple Lines

在上一章提供的示例中,我们讨论了如何在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 <b class="notranslate">showText()</b> method of the 
   ContentStream class";

用上面提到的字符串替换上一章中示例的string text并执行它。 执行后,您将收到以下输出。

单线扩展

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

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

Steps

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

第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步:使用换行符插入多个字符串()

您可以使用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();

例子 (Example)

此示例演示如何使用PDFBox在PDF中添加多行。 将此程序保存在名为AddMultipleLines.java.的文件中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.<i>TIMES_ROMAN</i>, 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. <b class="notranslate">ShowText</b>(text1);
      contentStream.newLine();
      contentStream. <b class="notranslate">ShowText</b>(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 ,则可以观察到给定内容以多行添加到文档中,如下所示。

添加多行

PDFBox - Reading Text

在上一章中,我们已经了解了如何将文本添加到现有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();

例子 (Example)

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

示例PDF

此示例演示如何从上述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 - Inserting Image

在上一章中,我们已经了解了如何从现有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.<i>createFromFile</i>("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();

例子 (Example)

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

样本文件

此示例演示如何将图像添加到上述PDF文档的空白页。 在这里,我们将加载名为sample.pdf的PDF文档并向其添加图像。 将此代码保存在名为InsertingImage.java.的文件中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 ,您可以观察到图像插入其中,如下所示。

插入图片

PDFBox - Encrypting a PDF Document

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

加密PDF文档

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

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

  • 打印文档
  • 修改文档的内容
  • 复制或提取文档的内容
  • 添加或修改注释
  • 填写交互式表单字段
  • 提取文本和图形,以便为视障人士提供便利
  • 组装文档
  • Print in degraded quality

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();

例子 (Example)

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

样本文件

此示例演示如何加密上述PDF文档。 在这里,我们将加载名为sample.pdf的PDF文档并对其进行加密。 将此代码保存在名为EncriptingPDF.java.的文件中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 ,则不能,因为它已加密。 相反,它会提示输入密码以打开文档,如下所示。

文档加密

PDFBox - JavaScript in PDF Document

在上一章中,我们学习了如何将图像插入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对象,如下所示。 对于此类的构造函数,以String的形式传递所需的JavaScript,如下所示。

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();

例子 (Example)

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

样本文件

此示例演示如何在上述PDF文档中嵌入JavaScript。 在这里,我们将加载名为sample.pdf的PDF文档并在其中嵌入JavaScript。 将此代码保存在名为AddJavaScript.java.的文件中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 ,它将显示一条警告消息,如下所示。

添加javascript

PDFBox - Splitting a PDF Document

在上一章中,我们已经了解了如何将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();

例子 (Example)

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

拆分页面

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

拆分第一一瞬间

PDFBox - Merging Multiple PDF Documents

在上一章中,我们已经了解了如何将给定的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("C:/PdfBox_Examples/data1/merged.pdf");

第4步:设置源文件

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

PDFmerger.addSource(file1);

第5步:合并文档

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

PDFmerger.mergeDocuments();

第6步:关闭文档

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

document.close();

例子 (Example)

假设我们在路径C:\PdfBox_Examples\有两个PDF文档sample2.pdfsample2.pdf ,如下所示。

Image File.jpg内容File.jpg

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

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("C:/PdfBox_Examples/sample1.pdf");
      PDDocument doc1 = PDDocument.<i>load</i>(file1);
      File file2 = new File("C:/PdfBox_Examples/sample2.pdf");
      PDDocument doc2 = PDDocument.<i>load</i>(file2);
      //Instantiating PDFMergerUtility class
      PDFMergerUtility PDFmerger = new PDFMergerUtility();
      //Setting the destination file
      PDFmerger.setDestinationFileName("C:/PdfBox_Examples/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();
   }
}

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

javac MergePDFs.java 
java MergePDFs 

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

Documents merged

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

合并的

PDFBox - Extracting Image

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

从PDF文档生成图像

PDFBox库为您提供了一个名为PDFRenderer的类, 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();

例子 (Example)

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

示例图像

此示例演示如何将上述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.<i>write</i>(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 ,如下所示。

Generateimage

PDFBox - Adding Rectangles

本章将教您如何在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步:设置非抚摸颜色

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

contentStream.setNonStrokingColor(Color.<i>DARK_GRAY</i>);

第5步:绘制矩形

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

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

第6步:填充矩形

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

contentStream.fill();

第7步:关闭文档

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

document.close();

例子 (Example)

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

空白页

此示例演示如何在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.<i>load</i>(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 ,则可以观察到其中插入了一个框,如下所示。

Coloredbox
↑回到顶部↑
WIKI教程 @2018