Yet another blog (hopefully a useful one though)
How to get ImageMagick to Convert pdf’s with GhostScript
Ok, this is one for the nerds. I have spent most of today trying to figure out how to get ImageMagick to convert a pdf file to an image.
First I installed ImageMagick fine:
> wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz
> tar xvfz ImageMagick.tar.gz
> cd ImageMagick-6.5.8
> ./configure
> make
> make install
Then I installed the Imagick PECL module in cPanel.
I ran a test on the command line:
> /usr/local/bin/convert test.pdf test.jpg
And like Magick we had a jpg!
So, simple I thought, run an exec() function on the above and it will do the job. However…
Basically it didn’t work. It wouldn’t work with an Imagic script either:
<?php try { $im = new Imagick(); $im->readImage( "test.pdf" ); $im->pingImage("test.pdf"); $im->readImage( $image ); $im->setImageFormat( "jpg" ); $im->writeImage( 'test.jpg' ); echo 'Image Converted'; } catch(Exception $e) { echo $e->getMessage(); } ?>
Hmmm!?
So, I tried to simplify the situation and converted a jpg to a png whit the script as above and both worked perfectly. So I checked the Apache error log and found that aparently “gs” did not exist. So I installed Ghostscript (which is apparently required for converting pdf’s and ps’s with exact same procedure as for Imagemagick except with the appropriate ghostscript tar.gz file. And…
Still nothing!
So, I did a bit of trawling and it turned out that Apache did not have the path to Ghostscript in the environmental path. To cut a fairly long story short I could not get httpd.conf, php.ini or .htaccess to cooperate in adding the path so I created a symbolic link from a directory already in the Apache path (/usr/bin/) to the actual location with:
> ln /usr/local/bin/ /usr/bin/
And by some minor miracle it worked!
So, if you have Imagemagick and Ghostscript installed and images work fine but pdf’s will not convert (like about 100 people I found in google-land), find your path with:
<?php echo getenv("PATH"); ?>
Then run:
> whereis gs
To find GhostScript (gs)
and run:
> ln /usr/local/bin/ /usr/bin/
Or equivalent.
Enjoy!