通过 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. 設定搜尋選項。
  3. 迴圈遍歷每個片段收集以進行密文。
  4. 儲存檔。

編輯 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)