解析PDF中的表格
從現有的PDF文檔中提取文本
提取文本是PDFBox
的主要功能之一。 可以使用PDFTextStripper
類的getText()
方法提取文本。 這個類從給定的PDF文檔中提取所有文本。
以下是從現有PDF文檔中提取文本的步驟。
第1步:加載現有的PDF文檔
使用PDDocument
類的靜態方法load()
加載現有的PDF文檔。 此方法接受一個文件對象作為參數,將一個PDF文件初始化為一個pdfbox中的PDDocument類,因為這是一個靜態方法,可以使用類名稱調用它,如下所示。
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對象的形式返回。
PDFTextStripper: This class will take a pdf document and strip out all of the text and ignore the formatting and such. Please note; it is up to clients of this class to verify that a specific user has the correct permissions to extract text from the PDF document. The basic flow of this process is that we get a document and use a series of processXXX() functions that work on smaller and smaller chunks of the page. Eventually, we fully process each page and then print it.
String text = pdfStripper.getText(document);
第4步:關閉文檔
最后,使用PDDocument
類的close()
方法關閉文檔,如下所示。
document.close();