Converting PDF files to images using PHP and Ghostscript
For a project at Epyc, I had to write a PHP module to convert a PDF file into a series of images. This is a key feature of the application I’m developing, so it was very important it worked flawlessly.
I have programmed some modules that generated PDF files before, but never the other way around. So my first stop was google.
Almost everyone will tell you to use ImageMagick and Ghostscript. ImageMagick uses Ghostscript to interpret the PDF file, so that’s why Ghostscript must also be installed on the server.
However, we just couldn’t get ImageMagick to communicate with Ghostscript. ImageMagick always gave us the following error:
Postscript delegate failed
It looks like a lot of people run into this problem, and I just couldn’t find a solution.
I was about to give up, when one of my collegues pointed out I could simply call Ghostscript directly through the command line (thanks Frederik ). In this way I don’t have all the fancy features of ImageMagick, but to edit the converted images I can use the PHP GD library, so I didn’t really need ImageMagick. Ghostscript ran fine on our server, so this was worth a shot.
So, here’s how you call Ghostscript directly trough PHP using the “exec” function:
$exportName="pdf_export_" . time();
exec("'gs' '-dNOPAUSE' '-sDEVICE=jpeg' '-dUseCIEColor' '-dTextAlphaBits=4' '-dGraphicsAlphaBits=4' '-o$exportPath' '-r$res' '-dJPEGQ=$quality' '$pdf'",$output);
This script creates a new folder for the export, and creates a subfolder named “fullres”. The exported images will be placed in this folder. When Ghostscript completes its job, the console output is rendered, so you can see what happened behind the screen.