简体   繁体   中英

Convert PDF to JPG image with PHP

I am using ImageMagik to try and convert the contents of a PDF to JPG, but keep getting an empty jpg. I have made sure the perms are 777 on everything for testing so I am a little lost how to continue.

Here is the script I am running

<?php

    exec('convert testfile.pdf output.jpg', $output, $return_var);

?>

Try this.

<?php
    $pdf = 'testfile.pdf';
    $save = 'output.jpg';

    exec('convert "'.$pdf.'" -colorspace RGB -resize 800 "'.$save.'"', $output, $return_var);

?>

Use the absolute path to the binary, like this:

exec('/usr/bin/convert testfile.pdf output.jpg', $output, $return_var);

But make sure your convert binary is actually on /usr/bin you can check that out with the following command:

which convert

convert -normalize yourfile.pdf[0] yourdestination.jpg

ImageMagick internally use GhostScript and Generally the conversion of ImageMagick is slow Comparing to Ghoastscript, so If you are only interested on getting convert pdf to images then Ghostscript gs command is faster. below is an sample wrapper around Ghostscript which I wrote few days back.

PDFLib-Php

$pdflib = new ImalH\PDFLib\PDFLib();
$pdflib->setPdfPath($pdf_file_path);
$pdflib->setOutputPath($folder_path_for_images);
$pdflib->setImageQuality(95);
$pdflib->setDPI(300);
$pdflib->setPageRange(1,$pdflib->getNumberOfPages());
$pdflib->convert();

Here you have my solution. Use Imagick directly in your php code.

Convert all PDF pages to JPG

 // create Imagick object
 $imagick = new Imagick();
 // Reads image from PDF
 $imagick->readImage('file.pdf');
 // Writes an image
 $imagick->writeImages('converted.jpg', false);

Convert specific PDF page to JPG

 // create Imagick object
 $imagick = new Imagick();
 // Read image from PDF
 $imagick->readImage('test.pdf[0]');
 // Writes an image
 $imagick->writeImages('converted_page_one.jpg');

Another way to deal with this problem is to use spatie/pdf-to-image library.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM