在页面上替换文本

Contents
[ ]

在更新 PDF 文档时,文本替换是一个常见需求。使用 PdfContentEditor, 您可以搜索特定文本并将其替换为新内容。‘replace_text_strategy’ 属性允许您控制要替换的出现次数。

  1. 创建一个 PdfContentEditor 实例。
  2. 绑定输入的 PDF 文档。
  3. 配置文本替换策略。
  4. 替换目标文本。
  5. 保存更新后的 PDF 文档。
import aspose.pdf as ap
import aspose.pdf.facades as pdf_facades
import sys
from os import path

sys.path.append(path.join(path.dirname(__file__), ".."))

from config import set_license, initialize_data_dir


def replace_text_on_page(infile, outfile):
    # Create PdfContentEditor object
    content_editor = pdf_facades.PdfContentEditor()
    # Bind document to PdfContentEditor
    content_editor.bind_pdf(infile)
    # Replace text on page 1
    content_editor.replace_text_strategy.replace_scope = (
        pdf_facades.ReplaceTextStrategy.Scope.REPLACE_FIRST
    )
    content_editor.replace_text("PDF", "Page 1 Replaced Text", 14)
    # Save updated document
    content_editor.save(outfile)