Convert a pdf to an image using PHP original

by Freek Van der Herten – 1 minute read

Converting a pdf to an image is easy using PHP, but the API kinda sucks.

$imagick = new Imagick('file.pdf[0]');
$imagick->setImageFormat('jpg');
file_put_contents($pathToImage, $imagick);

The pdf-to-image-package aims to fix that. Here is the equivalent code:

$pdf = new Spatie\PdfToImage\Pdf('file.pdf');
$pdf->saveImage($pathToImage);

If the path you pass to saveImage has an extension jpg, jpeg, or png the image will be saved in that format. Otherwise the output will be a jpg.

To convert all pages of the pdf to images you can run:

$pdf = new Spatie\PdfToImage\Pdf('file.pdf');
foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
   $pdf->setPage($pageNumber)
       ->saveImage('page'.$pageNumber.'jpg');
}

Join 9,500+ smart developers

Get my monthly newsletter with what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share? Submit a link to the community section.