Convert PDF to Image using PHP
Recently one of my friends asked me if there is a way to convert a PDF to an Image file. I tried to do that a few months ago by following some tutorial that was using a combination of Ghostscript and Imagemagick tools. But I didn’t succeed at that time as there were so many version conflicts on Imagemagick with PHP on windows.
So this time I did some more research and found that this can be done just by using Ghostscript commands on PHP. On a Linux server this is very easy as we just have to run the exec() function and use the Ghostscript command “gs” through it with passing necessary arguments. But on windows(local system), this is a little tricky as you have to download and install Ghostscript. And add that Ghostscript folder to the system environment variable so that you can run the “gs” command from any directory. But then, how to do this on actually Windows server?
To overcome this issue, I tried to do something funny. I copied the installation folder of Ghostscript to my project’s folder. And run the command using the absolute path of my project directory. And it worked perfectly. I tried running the same source code on a different machine too where I didn’t even install Ghostscript and there also it worked. Below is the example Ghostscript command.
Windows :
C:\xampp\htdocs\pdfimage/gs/win/bin/gs.exe -q -sDEVICE=pngalpha -dBATCH -dNOPAUSE -dFirstPage=1 -dLastPage=2 -r150x150 -sOutputFile=C:\xampp\htdocs\pdfimage/output/DESTINATION_FILE.png C:\xampp\htdocs\pdfimage/input/SOURCE_FILE.pdf
Linux :
gs -q -sDEVICE=pngalpha -dBATCH -dNOPAUSE -dFirstPage=1 -dLastPage=2 -r150x150 -sOutputFile=/my_server/public_html/pdfimage/output/DESTINATION_FILE.png /my_server/public_html/pdfimage/input/SOURCE_FILE.pdf
Once I had both these commands working perfectly, I decided to optimize the code so that it can work on both Windows and Linux servers and can be useful to others too. Please follow the below links :