通过 Python 编辑 PDF

PDF 文档的敏感编辑信息。使用 Aspose.PDF for Python for .NET 以编程方式修改 PDF 文档

如何使用 Python 库编辑 PDF 文件

要编辑 PDF 文件,请使用 Aspose.PDF for Python via .NET,这是一个功能强大且易于使用的 API。打开 PyPI,搜索 aspose-pdf 并安装。或者,运行以下命令:

通过 Python 编辑 PDF 文档


你需要 Aspose.PDF for .NET 在你的环境中试用代码。

  1. 使用 “文档” 实例加载 PDF。
  2. 使用搜索词作为参数创建 TextFragmentAbsorber 对象。
  3. 设置搜索选项。
  4. 循环浏览每个片段收集以进行编辑。
  5. 保存 PDF 文件。

编辑 PDF 文件-Python

import aspose.pdf as apdf

from os import path
path_infile = path.join(self.data_dir, infile)
path_outfile = path.join(self.data_dir, outfile)

document = apdf.Document(path_infile)

searchTerm = "Secret word"
textFragmentAbsorber = apdf.text.TextFragmentAbsorber(searchTerm)
textSearchOptions = apdf.text.TextSearchOptions(True)
textFragmentAbsorber.text_search_options = textSearchOptions

document.pages.accept(textFragmentAbsorber)
textFragmentCollection = textFragmentAbsorber.text_fragments
for textFragment in textFragmentCollection:
    page = textFragment.page
    annotationRectangle = textFragment.rectangle
    annot = apdf.annotations.RedactionAnnotation(page, annotationRectangle)
    annot.fill_color = apdf.Color.black
    document.pages[page.number].annotations.add(annot, True)
    annot.redact()

    document.save(path_outfile)