这个简短的教程详细介绍了如何通过加载输入 PDF 文档并将其保存为 Text 格式来将 PDF 转换为 Java 中的文本。此外,与源 PDF 文件相比,可以自定义使用 Java PDF 到文本转换器 来控制是否希望输出带有或不带格式的文本。
在 Java 中将 PDF 转换为文本的步骤
- 通过从 Maven 存储库中添加对 Aspose.PDF 的引用来配置您的应用程序,以将 PDF 转换为文本文件
- 使用 Document 类对象加载输入 PDF 文件,以将 PDF 转换为文本文件
- 创建一个 TextAbsorber 类的对象来设置文本提取选项
- 将提取的文本写入文本文件
上述步骤详细说明了开发基于 PDF 到 Text Java 的转换器应用程序的过程。第一步,使用 Document 类实例加载输入的 PDF 文档,然后选择是否需要带格式的文本。最后,您可以使用文本字符串写入文件或根据您的要求进一步处理它。
在 Java 中将 PDF 转换为文本的代码
import com.aspose.pdf.Document; | |
import com.aspose.pdf.License; | |
import com.aspose.pdf.TextAbsorber; | |
import com.aspose.pdf.TextExtractionOptions; | |
import java.io.BufferedWriter; | |
import java.io.FileWriter; | |
import java.nio.file.Files; | |
public class ConvertPdfToTextInJava { | |
public static void main(String[] args) throws Exception { // main method to convert a PDF document to Text file | |
// Instantiate the license to avoid trial limitations while converting the PDF to a text file | |
License asposePdfLicenseText = new License(); | |
asposePdfLicenseText.setLicense("Aspose.pdf.lic"); | |
// Load the source PDF file that is to be converted to Text file | |
Document convertPDFDocumentToText = new Document("input.pdf"); | |
// Instantiate a TextAbsorber class object for converting PDF to Text | |
TextAbsorber textAbsorber = new TextAbsorber(new TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure)); | |
// Call the Accept method exposed by the TextAbsorber class | |
convertPDFDocumentToText.getPages().accept(textAbsorber); | |
// Read the text as string | |
String ExtractedText = textAbsorber.getText(); | |
// Create the BufferedWriter object to open the file | |
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("SampleOutput.txt"))); | |
// Write extracted contents to the file | |
writer.write(ExtractedText); | |
// Close writer | |
writer.close(); | |
System.out.println("Done"); | |
} | |
} |
此示例代码演示了通过使用 Java 将 PDF 转换为文本 并通过使用不同的选项(例如 TextAbsorber 类具有多个构造函数)进行完全控制,您可以在其中使用 TextSearchOptions ,它提供了将源 PDF 中的阴影文本转换为单独文本的选项。同样,您可以设置标志以仅在绑定的页面内搜索文本,或设置矩形以仅在所有页面中从指定区域搜索文本。
在这里,我们学习了如何将 PDF 转换为 Java 中的文本以及代码片段。如果您想了解将 PDF 转换为 Word 的过程,请参阅 如何在 Java 中将 PDF 转换为 Word 上的文章。