Posts Tagged ‘Imagick’

Imagick – Postscript delegate failed

Wednesday, August 10th, 2011

This new project I’m working on requires me to extract an image from a PDF file and show a preview on the web page. I knew this was possible but I didn’t knew how.

After googling it for a while I ended with some interesting results that pointed me to ImageMagick. It’s a nice tool to transform/extract images from one format to another. It is supported by many languages as C, Perl, Python and PHP. Since I am coding with PHP I went for it and activated the imagick extension for PHP on my Zend Server CE.

I’m using a Mac with Lion OS X.

I found a really good blog that has a whole section for Imagick with pretty neat results here.

After reading for a while I was ready to do my first test, so I used a code similar to this one:

<?php
/* Read page 1 */
$im = new imagick( 'test.pdf[0]' );
/* Convert to png */
$im->setImageFormat( "png" );
/* Send out */
header( "Content-Type: image/png" );
echo $im;
?>

And then ran it on my browser but to my surprise it was throwing an exception:

Postscript delegate failed `test.pdf': No such file or directory

The path was fine, I tested it with a jpg and a png image and it worked so I was really confused and started to dig into the issue. After a while I ended up reading ImageMagick documentation and somewhere I read that it uses third party commands to accomplish format transformations from vector images (like the ones stored within a pdf). Lastly I went to the server error logs and found this:

sh: gs: command not found

I guessed from previous experience that this message meant the following:

sh -> execute a shell command
gs -> ghostscript command
[text] -> error message

So it meant that the server was not being able to execute the ghostscript command, ¿really?
I went to a console and typed in:

which gs

It returned the command path so I knew I had ghostscript installed so the problem should be that the server user didn’t had the path set properly.
To check if my assumption was correct I typed the following in the console:

echo $PATH

And I got the PATH env variable.
On my PHP script I added the following line:

echo getenv('PATH');

And my script displays the PATH env variable being used by my web server. The result was different and the path where the ghostscript executable was not being included.
Now I was able to solve the issue and it was really simple. It required for me to provide the correct path for my server.
Now my script look like this:

<?php
putenv('PATH=' . getenv() . ':[absolute_path_where_the_ghostscript_executable_is]');
/* Read page 1 */
$im = new imagick( 'test.pdf[0]' );
/* Convert to png */
$im->setImageFormat( "png" );
/* Send out */
header( "Content-Type: image/png" );
echo $im;
?>

And finally everything works fine.