如何从 Python 创建 PDF 文件,包括图像和文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19768495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create a PDF file, including images and text, from Python?
提问by Catalin D Voinescu
I am looking for a way to create a sheet of labels, as a PDF file, from a Python program. Each label has one or two images, and a few lines of text (same font, e.g. Helvetica or Arial, but possibly different sizes, and using bold and italic). These being labels, it is important that the elements are positioned correctly on the page. Some of the labels are addresses, so the text can vary and have different line lengths and number of lines.
我正在寻找一种方法来从 Python 程序创建一张标签,作为 PDF 文件。每个标签有一个或两个图像,以及几行文本(相同的字体,例如 Helvetica 或 Arial,但可能大小不同,并使用粗体和斜体)。这些是标签,元素在页面上的正确定位很重要。一些标签是地址,因此文本可能会有所不同,并且具有不同的行长和行数。
I would like to be able to tell when text did not fit in the space available for it, so that the program could try a few strategies automatically (e.g. change font to Arial Narrow, reduce font size) before bailing out. I definitely don't want the text to overrun or wrap without notice.
我希望能够判断文本何时不适合它的可用空间,以便程序可以在退出之前自动尝试一些策略(例如将字体更改为 Arial Narrow,减小字体大小)。我绝对不希望文本在没有通知的情况下溢出或换行。
I have looked at pypdf, but it doesn't seem to be able to do what I need (or maybe I'm missing something). I don't mind creating a document in a different format using a library that supports the features I need, as long as it can be converted to PDF programmatically. As a last resort, I can also use a library that can create a raster image, because that can be converted trivially to PDF, but I prefer a PDF that contains native text, not just a bitmap of it.
我看过pypdf,但它似乎不能做我需要的(或者我可能遗漏了一些东西)。我不介意使用支持我需要的功能的库创建不同格式的文档,只要它可以以编程方式转换为 PDF。作为最后的手段,我还可以使用可以创建光栅图像的库,因为它可以轻松转换为 PDF,但我更喜欢包含本机文本的 PDF,而不仅仅是它的位图。
采纳答案by T. Christiansen
Take a look at reportlab.
看看reportlab。
Here is the userguide: https://www.reportlab.com/docs/reportlab-userguide.pdf
这是用户指南:https: //www.reportlab.com/docs/reportlab-userguide.pdf
Here is a nice Tutorail: http://www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/
这是一个不错的教程:http: //www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/