这个简短的教程解释了如何使用 Java 查找和替换 PDF 中的文本。在您想要排除某些敏感或分类信息的情况下,它也很有帮助。要替换文本,请使用 Java** 加载 **PDF 搜索和替换,然后保存更新的 PDF 文档。
使用 Java 在 PDF 中查找和替换文本的步骤
- 配置您的应用程序以安装 Aspose.PDF for Java 以查找和替换文本
- 使用 Document 类加载输入 PDF 文件以替换文本
- 在 TextFragmentAbsorber 对象中指定需要搜索的文本短语
- 设置文本替换选项并接受所有页面的文本吸收器
- 在 PDF 中创建一组匹配的文本短语
- 通过用新文本替换找到的文本来更新它
- 替换文本后保存输出的 PDF 文件
这些步骤总结了如何在您的应用程序中借助 Java 替换 PDF 中的文本。我们可以根据应用程序工作流程对新创建的 PDF 文件以及现有 PDF 文档执行此操作。请注意,在替换文本时,您还可以更改文本字体、前景色和背景色。
使用 Java 替换 PDF 中的文本的代码
import com.aspose.pdf.Document; | |
import com.aspose.pdf.License; | |
public class FindAndReplaceTextInPdfUsingJava { | |
public static void main(String[] args) throws Exception { | |
// Instantiate license to create presentation in HTML | |
License pdfLicense = new License(); | |
pdfLicense.setLicense("Aspose.Pdf.lic"); | |
// Load the input PDF document | |
Document pdfDocument = new Document("Input.pdf"); | |
// Create TextFragmentAbsorber object | |
com.aspose.pdf.TextFragmentAbsorber textFragmentAbsorber = new com.aspose.pdf.TextFragmentAbsorber("Rack"); | |
// Set text replace options | |
com.aspose.pdf.TextReplaceOptions options = new com.aspose.pdf.TextReplaceOptions(); | |
options.setReplaceScope(com.aspose.pdf.TextReplaceOptions.Scope.REPLACE_FIRST); | |
textFragmentAbsorber.setTextReplaceOptions(options); | |
// Accept the text absorber for the entire collection of pages | |
pdfDocument.getPages().accept(textFragmentAbsorber); | |
// Get the extracted fragments in a collection | |
com.aspose.pdf.TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments(); | |
// Loop through all text fragments | |
for (com.aspose.pdf.TextFragment textFragment : textFragmentCollection) { | |
// Update the text | |
textFragment.setText("New Rack"); | |
} | |
// Save the updated PDF file | |
pdfDocument.save("Output.pdf"); | |
System.out.println("Done"); | |
} | |
} |
此代码示例展示了如何使用 Java 替换 PDF 中的文本。此外,您可以使用许多属性来增强代码片段。例如,更新文本外观属性、从特定页面区域查找文本、使用正则表达式查找文本、文本替换范围、文本替换策略等。
为了替换 PDF 中的文本,本文讨论了基于 Java 的环境配置和代码片段。但是,如果您想学习如何使用密码保护 PDF,请参阅 如何在 Java 中使用密码保护 PDF 上的文章。