25
Feb2011

Converting PDF files to images using PHP and Ghostscript

Posted by: Ward De Langhe

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
    ini_set('display_errors', 1);
    $pdf='test.pdf';
    $quality=90;
    $res='300x300';
    $exportName="pdf_export_" . time();
    $exportPath=realpath(dirname(__FILE__))."/$exportName/fullres/%03d.jpg";
   
    mkdir(realpath(dirname(__FILE__))."/$exportName");
    mkdir(realpath(dirname(__FILE__))."/$exportName/fullres");
   
    set_time_limit(900);
    exec("'gs' '-dNOPAUSE' '-sDEVICE=jpeg' '-dUseCIEColor' '-dTextAlphaBits=4' '-dGraphicsAlphaBits=4' '-o$exportPath' '-r$res' '-dJPEGQ=$quality' '$pdf'",$output);
   
    for($i=0;$i<count($output);$i++)
        echo($output[$i] .'<br/>');
?>

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.

24 Responses to “Converting PDF files to images using PHP and Ghostscript”

  1. jasim akhtar says:

    Hi
    I did the same , i am getting following error.

    Please help

    regards
    jas

    GPL Ghostscript 8.70 (2009-07-31)
    Copyright (C) 2009 Artifex Software, Inc. All rights reserved.
    This software comes with NO WARRANTY: see the file PUBLIC for details.
    Processing pages 1 through 4.
    Page 1
    Substituting font Helvetica-Bold for Arial-BoldMT.
    Can’t find (or can’t open) font file /usr/share/ghostscript/8.70/Resource/Font/NimbusSansL-Bold.
    Can’t find (or can’t open) font file NimbusSansL-Bold.
    Can’t find (or can’t open) font file /usr/share/ghostscript/8.70/Resource/Font/NimbusSansL-Bold.
    Can’t find (or can’t open) font file NimbusSansL-Bold.
    Querying operating system for font files…
    Can’t find (or can’t open) font file /usr/share/ghostscript/8.70/Resource/Font/NimbusSansL-Bold.
    Can’t find (or can’t open) font file NimbusSansL-Bold.
    Didn’t find this font on the system!
    Unable to substitute for font.
    Error: /invalidfont in /findfont
    Operand stack:
    –dict:8/17(L)– TT2 1 FontObject –dict:8/8(L)– –dict:8/8(L)– Arial-BoldMT –dict:13/13(L)– Helvetica-Bold Helvetica-Bold
    Execution stack:
    %interp_exit .runexec2 –nostringval– –nostringval– –nostringval– 2 %stopped_push –nostringval– –nostringval– –nostringval– false 1 %stopped_push 1846 1 3 %oparray_pop 1845 1 3 %oparray_pop 1829 1 3 %oparray_pop –nostringval– –nostringval– 2 1 4 –nostringval– %for_pos_int_continue –nostringval– –nostringval– –nostringval– –nostringval– %array_continue –nostringval– false 1 %stopped_push –nostringval– %loop_continue –nostringval– –nostringval– –nostringval– –nostringval– –nostringval– –nostringval– –nostringval– 1804 10 9 %oparray_pop
    Dictionary stack:
    –dict:1156/1684(ro)(G)– –dict:1/20(G)– –dict:75/200(L)– –dict:75/200(L)– –dict:106/127(ro)(G)– –dict:285/300(ro)(G)– –dict:22/25(L)– –dict:4/6(L)– –dict:26/40(L)–
    Current allocation mode is local
    Last OS error: 2

  2. munees says:

    hi
    I have installed the gs864w32.exe in my C drive but my wamp is located in D drive with the above script.how to connect the gs to my php code. help me.

  3. I couldn’t get it to work with wamp myself (although I didn’t gave it much time). I installed ghostscript on our test server.

  4. k00dez says:

    Hi!

    How do I get only the first page of the pdf?

    Tks!

  5. I don’t know this by heart. It’s been some time since I last used Ghostscript. But I think you can use the -dFirstPage and -dLastPage parameters to define where ghostscript should start interpreting the document and where it should stop.
    So something like -dFirstPage=1 and -dLastPage=1 will tell Ghostscript to only interpret the first page.

  6. Anthony says:

    Thanks for the useful example; it did not work for me at first and the problem was a white space in the filename. Changing that to _ made the code work.

  7. silvia says:

    Hi, how I can resize the images?
    to 992×1403

  8. Ipsita says:

    Thanks for your code. It is working.. You are great…

  9. Thanks for the function. works well.

  10. David Flood says:

    Hi,
    Thanks great code! I got it to work with WAMP too, just what I needed!

  11. nachiket says:

    hi….
    i have installed ghostscript but how to run .php file in ghostscript please help me.

    i am new in php.

  12. nachiket says:

    hi….
    i can able to create image by follwing code in commnd prompt line

    “c:\program Files\gs\gs9.06\bin\gswin32c.exe” -dQuite -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -dFirstPage=1 -dLastPage=13 -sOutputfile=c:\sta\sta%03d.jpg -fC:\STA.pdf

    and by these code image are created but in these code i have to manualy add gswin32.exe path.

    but in your code only “gs “how can do this

    plese help me…

  13. developer says:

    I have followed your codes. But i couldn’t create the images.

    ini_set(‘display_errors’, 1);
    $pdf = realpath(dirname(__FILE__)).’/calendar.pdf’;
    $quality = 90;
    $res = ‘300×300′;
    $exportName = “pdf_export_” . time();
    $root = realpath(dirname(__FILE__));
    $exportPath = realpath(dirname(__FILE__)).”/$exportName/test.jpg”;
    mkdir(realpath(dirname(__FILE__)).”/$exportName”);

    set_time_limit(900);

    exec(“‘gs’ ‘-dQuite’ ‘-dSAFER’ ‘-dNOPAUSE’ ‘-sDEVICE=jpeg’ ‘-dUseCIEColor’ ‘-dTextAlphaBits=4′ ‘-dFirstPage=1′ ‘-dLastPage=13′ ‘-dGraphicsAlphaBits=4′ ‘-sOutputfile=sta%03d.jpg’ ‘-r$res’ ‘-dJPEGQ=$quality’ ‘$pdf’”,$output);

    echo ”; print_r($output); echo ”;

    for($i=0;$i<count($output);$i++)
    echo($output[$i] .'’);

  14. And what errors are you seeing?

  15. ahmed says:

    It’s not working for me. it just keep loading and exec call don’t return.

  16. sylvain says:

    Hi worked directly for me but I am running Linux Ubuntu not windows !

  17. Jeremy says:

    I am using this script on a Namecheap hosted VPS. when I run the script I get no error messages, and the folders for the converted jpegs are created, but there are no images inside.

    Ghostscript version is 8.70

    Any thoughts?

  18. Jeremy says:

    Got it working, had a Ghostscript config issue.

  19. moises says:

    error — >

    GPL Ghostscript 8.71 (2010-02-10)
    Copyright (C) 2010 Artifex Software, Inc. All rights reserved.
    This software comes with NO WARRANTY: see the file PUBLIC for details.
    Warning: the map file cidfmap was not found.

    help me

  20. Kumar says:

    am using ubuntu OS and this function working fine in localhost.. but its not working in online.. it gives me the below error..

    502 – Web server received an invalid response while acting as a gateway or proxy server.
    There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.

    can anyone help me..!!

  21. dishelt says:

    Hi! when i do that, chrome just doesnt answer, just loading, do you know why?

  22. Mario says:

    Hallo there !
    I ‘ve downloaded the gs9.07 version and everything seemed to work fine.
    Although the folder and the “fullres” subfolder is created , there are no converted images inside.Do you know whats happening or does anyone came across with the same issue?
    I am using wampp.

    Thank you

  23. Scott says:

    Hello friends,

    I am trying to compress a PDF file using php and Ghostscript

    My code stands below:
    exec(‘gs -sDEVICE=pdfwrite’ ‘-dCompatibilityLevel=1.4′ ‘-dPDFSETTINGS=/screen’ ‘-dNOPAUSE’ ‘-dQUIET’ ‘-dBATCH’ ‘-sOutputFile=output.pdf’ ‘ART11223.pdf’);

    Which is not working, any kind of help is appreciated.

    Thanks,
    Scott

  24. Thank you for taking the time to put this script up. I have been round and round with imagick for 2 days and going straight to ghostscript was the answer.

    Do you have suggestions for handling font errors.?


Leave a Reply