PDFBox讀取文件


在前一章中,我們已經學習了如何將文字新增到現有的PDF文件。 在本章中,我們將學習如何從現有PDF文件中讀取文字。

從現有的PDF文件中提取文字

提取文字是PDFBox的主要功能之一。 可以使用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文件(new-mul-doc.pdf),其中包含一些文字,如下所示。

此範例演示如何從上述PDF文件中讀取文字。 在這裡,將建立一個Java程式並載入一個PDF文件:new-mul-doc.pdf,該文件儲存在目錄:F:\worksp\pdfbox 中。 將此程式碼儲存在名稱為ReadingText.java的檔案中。

package com.yiibai;

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("F:\\worksp\\pdfbox\\new-mul-doc.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();

   }
}

執行上面範例程式碼,得到以下結果 -

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