Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PDF to JPEG with PHP and ImageMagick

I'm using a litte script to convert PDF to JPG. That works but the quality is very poor.

The script:

$im = new imagick( 'document.pdf[ 0]' );  $im->setImageColorspace(255);  $im->setResolution(300, 300); $im->setCompressionQuality(95);  $im->setImageFormat('jpeg');  $im->writeImage('thumb.jpg');  $im->clear();  $im->destroy(); 

One more thing, I want to keep the original size of the PDF but the conversion crops the size of the JPG.

like image 771
Leon van der Veen Avatar asked Feb 10 '12 11:02

Leon van der Veen


People also ask

How to convert PDF file to image using PHP?

Step 1: Open the PHP coding environment and start by creating imagic object using the code. $imagick = new Imagick(); Step 2: Now read the image from the target PDF file using the code: $imagick->readImage('myfile.

How do I install imagick?

Navigate to Home - Software - Module Installers, then click on the Manage button next to PHP Pecl. In the next screen, select the required PHP version, then click Apply. You can now enter “imagick” in the Install a PHP Pecl field, and click the Install Now button.


1 Answers

It can be done using setResolution, but you need to do it before loading an image. Try something like this:

// instantiate Imagick  $im = new Imagick();  $im->setResolution(300,300); $im->readimage('document.pdf[0]');  $im->setImageFormat('jpeg');     $im->writeImage('thumb.jpg');  $im->clear();  $im->destroy(); 
like image 159
wojtek Avatar answered Oct 06 '22 06:10

wojtek