Converting a PDF to a series of images with Python

PythonPdfImagemagickJpegPython Imaging-Library

Python Problem Overview


I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.

PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.

Are there any Python libraries out there that can do this?

Python Solutions


Solution 1 - Python

Solution 2 - Python

Here's whats worked for me using the python ghostscript module (installed by '$ pip install ghostscript'):

import ghostscript

def pdf2jpeg(pdf_input_path, jpeg_output_path):
    args = ["pdf2jpeg", # actual value doesn't matter
            "-dNOPAUSE",
            "-sDEVICE=jpeg",
            "-r144",
            "-sOutputFile=" + jpeg_output_path,
            pdf_input_path]
    ghostscript.Ghostscript(*args)

I also installed Ghostscript 9.18 on my computer and it probably wouldn't have worked otherwise.

Solution 3 - Python

You can't avoid the Ghostscript dependency. Even Imagemagick relies on Ghostscript for its PDF reading functions. The reason for this is the complexity of the PDF format: a PDF doesn't just contain bitmap information, but mostly vector shapes, transparencies etc. Furthermore it is quite complex to figure out which of these objects appear on which page.

So the correct rendering of a PDF Page is clearly out of scope for a pure Python library.

The good news is that Ghostscript is pre-installed on many windows and Linux systems, because it is also needed by all those PDF Printers (except Adobe Acrobat).

Solution 4 - Python

If you're using linux some versions come with a command line utility called 'pdftopbm' out of the box. Check out netpbm

Solution 5 - Python

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJaearessView Question on Stackoverflow
Solution 1 - PythonAdam RosenfieldView Answer on Stackoverflow
Solution 2 - PythonIdan YacobiView Answer on Stackoverflow
Solution 3 - PythonFranzView Answer on Stackoverflow
Solution 4 - PythonJayView Answer on Stackoverflow
Solution 5 - PythonmattbastaView Answer on Stackoverflow