目录

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.
↑回到顶部↑
WIKI教程 @2018