这个简短的教程将指导您如何用 Java 阅读 PDF 文件。它包含用于读取 PDF 文件的 Java 代码,首先,您将 Java 中 PDF 中的文本读取为字符串,然后从 PDF 文件中获取所有图像以将它们作为 JPG。无需安装任何第三方工具即可用 Java 阅读 PDF。
用 Java 读取 PDF 文件的步骤
- 使用 Maven 存储库将 Aspose.PDF 配置到您的项目中以读取 PDF 文件
- 将示例 PDF 文件加载到 Document 类对象中
- 实例化可以从 PDF 文件中读取整个文本的 TextAbsorber 类对象
- 使用 TextAbsorber 类对象从加载的文件中读取 PDF 文本
- 在控制台上显示从 PDF 文件读取的整个文本
- 遍历 PDF 文件中的所有页面以访问图像
- 解析每页图像集合上的所有图像并保存在光盘上
在这个快速的分步教程中,我们首先加载目标 PDF 文件,然后启动能够在 PDF 中的所有页面中搜索文本的 TextAbsorber 类对象。整个文本被返回成一个字符串,可以根据需要显示或处理。同样,我们可以解析图像集合中的所有图像,并将它们以任何格式保存在光盘上,就像我们在本教程中将其保存为 JPG 一样。
使用 Java 读取 PDF 的代码
import com.aspose.pdf.License; | |
import com.aspose.pdf.Document; | |
import com.aspose.pdf.Page; | |
import com.aspose.pdf.TextAbsorber; | |
import com.aspose.pdf.XImage; | |
public class HowToReadPDFFileInJava { | |
public static void main(String[] args) throws Exception {//main() function for HowToReadPDFFileInJava | |
// Instantiate the license to remove trial version restrictions while reading the PDF file | |
License license = new License(); | |
license.setLicense("Aspose.PDF.lic"); | |
// Load the PDF file from which text and images are to be read | |
Document pdf = new Document("Input.pdf"); | |
// 1. Read entire text from the PDF file | |
// Instantiate a TextAbsorber Class object to read Text from PDF file | |
TextAbsorber textAbsorberObject = new TextAbsorber(); | |
// Call PageCollection.accept() method to let TextAbsorber find text in PDF Pages | |
pdf.getPages().accept(textAbsorberObject); | |
// Write the extracted text from the sample PDF to console | |
System.out.println(textAbsorberObject.getText()); | |
// 2. Extract images from PDF file | |
int imageCount = 1; | |
// Iterate through all the PDF pages to access images collection and save them on the disc | |
for (Page pdfPage : pdf.getPages()) | |
{ | |
// Iterate through images collection in the PDF file | |
for (XImage image : pdfPage.getResources().getImages()) | |
{ | |
java.io.FileOutputStream outputImageFromPdfFile = new java.io.FileOutputStream(pdfPage.getNumber() + "-"+ imageCount+"-output.jpg"); | |
// Save each image in the PDF file images collection to a JPG file | |
image.save(outputImageFromPdfFile); | |
outputImageFromPdfFile.close(); | |
imageCount++; | |
} | |
// Reset image index | |
imageCount = 1; | |
} | |
} | |
} |
在此示例代码中,我们使用了 Page.getResources() 的 TextAbsorber 类和 getImages() 函数使用 Java 读取 PDF。 TextAbsorber 对象用于通过 PDF PageCollection 中的 accept 函数读取文本。而 getResources() 集合的 getImages() 函数返回页面上的所有图像。
请注意,这些用 Java 阅读 PDF 的步骤可以在 Windows、Linux 或 macOS 等任何操作系统中执行。如果您想了解有关使用 PDF 文件的更多信息,请参阅有关 如何使用 Java 读取 PDF 中的书签 的文章。