通过 Python 向 PDF 添加文本

使用 Python for .NET 向 PDF 文档添加文本。使用 Aspose.PDF 以编程方式修改 PDF 文档

如何使用 Python for .NET 库处理 PDF 中的文本

要将文本添加到 PDF 文件,我们将使用 Aspose.PDF for Python,这是一个功能强大且易于使用的 API。打开 PyPI,搜索 aspose-pdf 并安装它。或者,运行以下命令:

Console

pip install aspose-pdf

通过 Python 将文本添加到 PDF 文件


要在你的环境中试用代码,你需要 Aspose.PDF for Python

  1. 使用文档实例加载 PDF。
  2. 创建文本段落并定义其属性。
  3. 使用 TextBuilder 将文本段落添加到页面。
  4. 再次保存该文件。

向 PDF 添加文本-Python

此示例代码说明如何在 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)

# Get particular page
page = document.pages[1]

# Create text fragment
text_fragment = apdf.text.TextFragment("Hello, world!")
text_fragment.position = apdf.text.Position(100, 600)

# Set text properties
text_fragment.text_state.font_size = 12
text_fragment.text_state.font = apdf.text.FontRepository.find_font("TimesNewRoman")
text_fragment.text_state.background_color = apdf.Color.light_gray
text_fragment.text_state.foreground_color = apdf.Color.red

# Create TextBuilder object
builder = apdf.text.TextBuilder(page)

# Append the text fragment to the PDF page
builder.append_text(text_fragment)

# Save resulting PDF document.
document.save(path_outfile )