通过 Python 创建 PDF

无需安装 Adobe Acrobat 即可使用 Python 创建原生高性能 PDF 文件

如何通过 Python 生成 PDF 文件

要创建 PDF,请使用 Aspose.PDF for Python via .NET 这个强大且易于使用的 API。打开 PyPI,搜索 aspose-pdf 并安装。或者,运行以下命令:

Console

pip install aspose-pdf

如何通过 Python 创建 PDF


开发人员只需几行代码即可轻松地直接从 Python for .NET 应用程序创建、加载、修改和转换 PDF 文件。

  1. 在类文件中包含命名空间
  2. 初始化文档类对象。
  3. 使用 Pages.Add () 方法添加页面。
  4. 创建一个新的 TextFragment 对象并设置其文本。
  5. 将 TextFragment 添加到页面的段落集合中。
  6. 使用保存(字符串)方法保存 PDF。

以下源代码展示了如何使用 Python 创建 PDF 文件。

此示例代码展示了如何使用 Python 创建 PDF

import aspose.pdf as apdf

from os import path
path_outfile = path.join(self.data_dir, outfile)

# Initialize document object
document = apdf.Document()
# Add page
page = document.pages.add()
# Add text to new page
textFragment = apdf.text.TextFragment("Hello, world!")
textFragment.position = apdf.text.Position(100, 600)

textFragment.text_state.font_size = 12
textFragment.text_state.font = apdf.text.FontRepository.find_font(
    "TimesNewRoman"
)
textFragment.text_state.background_color = apdf.Color.blue
textFragment.text_state.foreground_color = apdf.Color.yellow

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

# Append the text fragment to the PDF page
textBuilder.append_text(textFragment)

document.save(path_outfile)