Conversion PDF to PNG or JPEG is very very slow us

2020-02-26 13:45发布

问题:

I have a working PDF to PNG conversion script using PHP and ImageMagick but I am having a problem with the speed of the conversion.

I know it works because with a very small PDF the time taken to convert is not that great, but with a 250kb file (still not that large really) it takes in excess of 20 minutes to convert.

Here's the PHP:

//***** GET PATH TO IMAGEMAGICK *****
$path_to_imagemagick = trim(`which convert`);

//***** PATH TO PDF TO CONVERT *****
$path_to_pdf = getcwd() . "/pdf/myfile.pdf[0]";

//***** PATH TO OUTPUT TO *****
$output_path = getcwd() . "/pdfimage/test_converted.png";

@exec($path_to_imagemagick . " -density 72 -quality 60 -resize 150x " . $path_to_pdf . " " . $output_path);

Are there any settings I can change to make this quicker?

If it helps, the image does not need to be a PNG. If JPEG is going to be quicker I'm happy to go with that.

回答1:

ImageMagick cannot convert PDF to raster images by itself at all.

ImageMagick uses a delegate for this job: that delegate is Ghostscript. If you hadn't installed Ghostscript on the same system as ImageMagick, the PDF conversion by convert wouldn't work.

To gain speed, don't use ImageMagick for PDF -> raster image conversion. Instead, rather use Ghostscript directly (also possible via PHP).

Command line for JPEG output:

gs                                 \
  -o ./pdfimage/test_converted.jpg \
  -sDEVICE=jpeg                    \
  -dJPEGQ=60                       \
  -r72                             \
  -dLastPage=1                     \
   pdf/myfile.pdf

Command line for PNG output:

gs                                 \
  -o ./pdfimage/test_converted.png \
  -sDEVICE=pngalpha                \
  -dLastPage=1                     \
  -r72                             \
   pdf/myfile.pdf 

Both of these commands will give you unscaled output.

To scale the output down, you may use something like

gs                                 \
  -o ./pdfimage/test_converted.png \
  -sDEVICE=pngalpha                \
  -dLastPage=1                     \
  -r72                             \
  -dDEVICEWIDTHPOINTS=150          \
  -dDEVICEHEIGHTPOINTS=150         \
  -dPDFFitPage                     \
   pdf/myfile.pdf 

Also please note: You used a -quality 60 setting for your PNG outputting command. But -quality for JPEG and -quality for PNG output do have a completely different meaning with ImageMagick (and you may not be aware of it). See also this answer for some details about this.