首页 > 解决方案 > 如何在 Python 中从头开始创建 PDF 文档

问题描述

如何在 Python 中从头开始创建 PDF 文档?

我想要

标签: pythonpython-3.xpdf

解决方案


免责声明:我是此答案中使用的库的作者。

使用pText您可以轻松实现这一目标。

让我们从创建一个空的开始Document

# create document
pdf = Document()

然后我们可以添加一个空PageDocument

# add page
page = Page()
pdf.append_page(page)

现在我们需要选择一个PageLayout. 此类将充当布局管理器。它将跟踪可用空间的位置,并将在该空间中布置组件(考虑到边距、前导等)

在这里,我使用MultiColumnLayout2 列:

layout = MultiColumnLayout(page, number_of_columns=2)

现在我要添加 2 个Paragraph对象,一个用于标题,一个用于作者:

layout.add(Paragraph("The Raven", font_size=Decimal(20)))
layout.add(Paragraph("Edgar Allen Poe", font="Helvetica-Oblique", font_size=Decimal(8), font_color=X11Color("SteelBlue")))

请注意,我指定了字体、font_size 和 font_color。我还可以指定一个理由(左、右、全、中心)。但我暂时保留它。

最后,我们将添加“The Raven”第一节的一些重复

for _ in range(0, 10):
    layout.add(Paragraph(
        "Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore- While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. Tis some visitor, I muttered, tapping at my chamber door- Only this and nothing more.",
        font_size=Decimal(12),
        font_color=X11Color("SlateGray"),
        justification=Justification.FLUSH_LEFT,
    ))

现在剩下的就是存储Document

# attempt to store PDF
with open("output.pdf", "wb") as in_file_handle:
    PDF.dumps(in_file_handle, pdf)

结果应该是这样的:

在此处输入图像描述

查看其他示例以了解如何使用表和列表:


推荐阅读