How to create PDF files in Python

I suggest pyPdf. It works really nice. I also wrote a blog post some while ago, you can find it here.


Here is my experience after following the hints on this page.

  1. pyPDF can't embed images into files. It can only split and merge. (Source: Ctrl+F through its documentation page) Which is great, but not if you have images that are not already embedded in a PDF.

  2. pyPDF2 doesn't seem to have any extra documentation on top of pyPDF.

  3. ReportLab is very extensive. (Userguide) However, with a bit of Ctrl+F and grepping through its source, I got this:

    • First, download the Windows installer and source
    • Then try this on Python command line:

      from reportlab.pdfgen import canvas
      from reportlab.lib.units import inch, cm
      c = canvas.Canvas('ex.pdf')
      c.drawImage('ar.jpg', 0, 0, 10*cm, 10*cm)
      c.showPage()
      c.save()
      

All I needed is to get a bunch of images into a PDF, so that I can check how they look and print them. The above is sufficient to achieve that goal.

ReportLab is great, but would benefit from including helloworlds like the above prominently in its documentation.


I suggest Pdfkit. (installation guide)

It creates pdf from html files. I chose it to create pdf in 2 steps from my Python Pyramid stack:

  1. Rendering server-side with mako templates with the style and markup you want for you pdf document
  2. Executing pdfkit.from_string(...) method by passing the rendered html as parameter

This way you get a pdf document with styling and images supported.

You can install it as follows :

  • using pip

    pip install pdfkit

  • You will also need to install wkhtmltopdf (on Ubuntu).

Tags:

Python

Pdf