如何在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.
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP