python - 如何在 Python 中从头开始创建 PDF 文档
问题描述
如何在 Python 中从头开始创建 PDF 文档?
我想要
- 以简单的方式放置文本(无需指定确切的坐标)
- 使用字体、颜色、斜体、粗体
- 使用表格
- 使用列表
- 使用图像
解决方案
免责声明:我是此答案中使用的库的作者。
使用pText
您可以轻松实现这一目标。
让我们从创建一个空的开始Document
# create document
pdf = Document()
然后我们可以添加一个空Page
的Document
# add page
page = Page()
pdf.append_page(page)
现在我们需要选择一个PageLayout
. 此类将充当布局管理器。它将跟踪可用空间的位置,并将在该空间中布置组件(考虑到边距、前导等)
在这里,我使用MultiColumnLayout
2 列:
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)
结果应该是这样的:
查看其他示例以了解如何使用表和列表:
推荐阅读
- electron - 电子打包程序分发文件是否应该包含在版本控制中?
- javascript - 如何在提交表单之前在页面刷新上设置警报框的样式
- sql - 如果值为“N/A”,则将权重分配给其他 KPI
- erlang - Elixir 累加器地图列表
- reactjs - 如何在 reactjs 中集成 bootstrap 4 数据表?
- sendgrid - 我们可以限制电子邮件链接在 Sengrid 中编码吗?
- r - 如何将所有组设置为等于具有最小组长度(行数)的组?
- ios - 在 TableView 控制器中将视图显示为内部应用程序通知
- daml - 如何在 DAML 中为原始类型和记录指定默认值?
- python - 分组排除异常值的最有效方法是什么