使用 Python 编辑 PDF

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

如何使用 Python 库编辑 PDF 文件

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

通过 Python 编辑 PDF 文档


你需要 通过.NET for Python 的 Aspose.PDF 才能在你的环境中试用代码。

1。使用 Document 实例加载 PDF。 1。使用搜索词作为参数创建 TextFragmentAbsorber 对象。 1。设置搜索选项。 1。循环浏览收集的每个片段进行编辑。 1。保存 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)