在页面上使用状态替换文本
Contents
[
Hide
]
有时在 PDF 中替换文本还需要进行格式更改,如颜色或字体大小。使用 TextState,您可以定义样式属性并在替换时应用它们。这使您能够突出显示已修改的文本或在文档间强制一致的格式。
- 创建一个 PdfContentEditor 实例。
- 绑定输入的 PDF 文档。
- 定义具有自定义格式的 TextState。
- 配置替换策略。
- 在特定页面上替换文本。
- 保存更新后的 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_with_state(infile, outfile):
# Create PdfContentEditor object
content_editor = pdf_facades.PdfContentEditor()
# Bind document to PdfContentEditor
content_editor.bind_pdf(infile)
text_state = ap.text.TextState()
text_state.foreground_color = ap.Color.red
text_state.font_size = 12
# Replace text on a specific page with explicit text formatting
content_editor.replace_text_strategy.replace_scope = (
pdf_facades.ReplaceTextStrategy.Scope.REPLACE_ALL
)
content_editor.replace_text("software", 1, "SOFTWARE PAGE 1", text_state)
# Save updated document
content_editor.save(outfile)