如何使用 Java 从 PDF 文件读取数据并显示在控制台上?
java 8object oriented programmingprogramming更新于 2025/6/27 0:37:17
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 { //加载现有文档 File file = new File("D://Sample.pdf"); PDDocument document = PDDocument.load(file); //实例化 PDFTextStripper 类 PDFTextStripper pdfStripper = new PDFTextStripper(); //从 PDF 文档中检索文本 String text = pdfStripper.getText(document); System.out.println(text); //关闭文档 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.