通过 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 檔


若要在你的環境中嘗試代碼,你需要 [阿波斯.PDF Python](https://releases.aspose.com/pdf/net)。

  1. 使用 Document 實例載入 PDF。
  2. 建立 TextParagraph 並定義其屬性。
  3. 使用 TextBuilder 將 TextParagraph 新增到 Page。
  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 )