Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Convert a pdf to an image using PHP

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

$imagick = new Imagick('file.pdf[0]');
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');

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) {
Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band.
  • Hi Freek, Than’s great job.
    But, i have a problem.
    When i use saveAllPagesAsImages, get error “500 Internal Server Error”.
    i looked the error log and i saw Timeout errors. Whats is the problems?

  • Alex Pavlov

    Hi. There is an error in your last example:
    instead of