使用 Python 編輯 PDF

PDF 文檔敏感的編輯信息。在 Python for .NET 使用 Aspose.PDF 以編程方式修改 PDF 文件

如何使用 Python 庫編輯 PDF 文件

若要編輯 PDF 文件,請使用功能強大且易於使用的 API—Aspose.PDF for Python via .NET。開啟 PyPI,搜尋 aspose-pdf 並安裝。或者,執行以下命令:

透過 Python 編輯 PDF 文件


您需要 Aspose.PDF for Python via .NET 才能在您的環境中嘗試程式碼。

1.載入帶有「文件」實例的 PDF。 1.使用搜索詞作為引數創建文本 FragmentAbsorber 對象。 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)