How to create PDF files in Python

Stephen T. picture Stephen T. · Feb 12, 2010 · Viewed 370.3k times · Source

I'm working on a project which takes some images from user and then creates a PDF file which contains all of these images.

Is there any way or any tool to do this in Python? E.g. to create a PDF file (or eps, ps) from image1 + image 2 + image 3 -> PDF file?

Answer

Evgeni Sergeev picture Evgeni Sergeev · May 19, 2013

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.