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 to convert from a PDF into an image file: Open your PDF in Adobe Acrobat Pro and choose file. Export it to the new file format by going to the right pane and choosing “Export PDF” tool. Or, go to the menu and select “File” > “Export to” > “Image.”
You need ImageMagick
and GhostScript
<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>
The [0]
means page 1
.
For those who don't have ImageMagick for whatever reason, GD functions will also work, in conjunction with GhostScript. Run the ghostscript command with exec()
to convert a PDF to JPG, and manipulate the resulting file with imagecreatefromjpeg()
.
Run the ghostscript command:
exec('gs -dSAFER -dBATCH -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r300 -sOutputFile=whatever.jpg input.pdf')
To manipulate, create a new placeholder image, $newimage = imagecreatetruecolor(...)
, and bring in the current image. $image = imagecreatefromjpeg('whatever.jpg')
, and then you can use imagecopyresampled()
to change the size, or any number of other built-in, non-imagemagick
commands
You can also get the page count using
$im->getNumberImages();
Then you can can create thumbs of all the pages using a loop, eg.
'file.pdf['.$x.']'
Use the php extension Imagick. To control the desired size of the raster output image, use the setResolution function
<?php
$im = new Imagick();
$im->setResolution(300, 300); //set the resolution of the resulting jpg
$im->readImage('file.pdf[0]'); //[0] for the first page
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>
(Extension on Paolo Bergantino his answer and Luis Melgratti his comment. You need to set the resolution before loading the image.)
If you're loading the PDF from a blob this is how you get the first page instead of the last page:
$im->readimageblob($blob);
$im->setiteratorindex(0);
You can also try executing the 'convert' utility that comes with imagemagick.
exec("convert pdf_doc.pdf image.jpg");
echo 'image-0.jpg';
I'm the author of PDFlib which is a GhostScript wrapper for php, advantage of using this library is, it is already tested and it does not require ImageMagic
Always GhostScript
commands are faster than ImageMagic
when it comes to pdf so you should either go for a GhostScript wrapper or pure GhostScript commands
$pdflib = new ImalH\PDFLib\PDFLib();
$pdflib->setPdfPath($pdf_file_path);
$pdflib->setOutputPath($folder_path_for_images);
$pdflib->convert();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With