如何在Java中讀取PDF檔案中的資料並在控制檯顯示?
有幾個庫可以使用Java讀取pdf中的資料。讓我們看看如何使用名為PDFBox的庫讀取PDF文件中的資料並在控制檯顯示它。
您可以使用**PDFTextStripper**類的**getText()**方法提取文字。此類提取給定PDF文件中的所有文字以使用它。
使用PDDocument類的靜態方法load()載入現有的PDF文件。
例項化PDFTextStripper類。
使用PDFTextStripper類的getText()方法檢索/讀取PDF頁面內容到字串。
最後,使用PDDocument類的close()方法關閉文件,如下所示。
示例
假設我們在D://目錄中有一個名為sample.PDF的pdf,如下所示:
下面的Java程式讀取上述PDF文件的內容並在控制檯顯示它們。
import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; public class PdfToConsole { public static void main(String args[]) throws IOException { //Loading an existing document File file = new File("D://Sample.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(); } }
輸出
Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more.
廣告