How do I create a PDF file, including images and text, from Python?

Catalin D Voinescu picture Catalin D Voinescu · Nov 4, 2013 · Viewed 43.9k times · Source

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.

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.

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.