Page-by-page PDF to JPG conversion in PHP

In this post, I will tell you how to save a PDF file page by page as a set of jpg images using PHP on the server-side. The information will be useful only for absolutely novice PHP web developers.

The PHP module ImageMagick must be installed and configured on your hosting. This module for working with images. Support for PDF files by this module must be installed as well. But that is not all! To work correctly with the PDF format, Ghostscript must be installed and properly configured too. If all this is not there, write to support your hosting or look for another hosting.

A simple example of converting a PDF to a set of jpg images:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
$pdf_file = 'test.pdf';
$im = new imagick($pdf_file);
$i=0;
foreach($im as $_img) {
   $i++;
   $_img->setResolution(300, 300);
   $_img->setImageFormat('jpeg');
   $_img->writeImage('p-'.$i.'.jpg');
}
$im->destroy();

$_img->setResolution(300, 300) β€” set the resolution, the quality of the image depends on it.
$_img->setImageFormat(‘jpeg’) β€” set the image format.
$_img->writeImage(‘p-’.$i.’.jpg’) β€” well, let’s save it.

If necessary, you can resize the image.

This example is very simple, but it makes it clear how simple and easy to convert a PDF to a set of jpg images using ImageMagick. In the same way, you can convert multi-page TIFF files and animated GIF images.

In general, the ImageMagick library is a very powerful thing.

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy