PDF to Image Conversion in PHP ImageMagick
Introduction
This requirement I have achieved using imagick, a native php extension to create and modify images using the ImageMagick API. ImageMagick® is a software suite to create, edit, and compose bitmap images.. It can read, convert and write images in a variety of formats (fover 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF.
So prior to the execution of the below code, You have to make sure that Imagick is properly installed in your machine. To check whether the Imagick has already installed, try the below code: If it is already installed, phpinfo should show Imagick module like below:
For installing Imagick in Linux, use the following commands in terminal:
sudo apt-get install php5-imagick
Finally you need to restart your web-server, if you are using Apache, run the following command
sudo /etc/init.d/apache2 restart
If you are using PHP-FPM instead of Apache2 then restart it by following command
sudo /etc/init.d/php5-fpm restart
After installation try the above code to ensure the Imagick installation(phpinfo()).
PDF Uploading Page:
<html>
<body>
<form action="ConvertPdfToImg.php" enctype="multipart/form-data" method="post" name="f1">
<input id="templateDoc" name="templateDoc" type="file" />
<input type="submit" />
</form>
</body>
</html>
ConvertPdfToImg.php:
<?php
$pdfAbsolutePath = __DIR__."/test.pdf";
if (move_uploaded_file($_FILES['templateDoc']["tmp_name"], $pdfAbsolutePath)) {
$im = new imagick($pdfAbsolutePath);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < $noOfPagesInPDF; $i++) {
$url = $pdfAbsolutePath.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->writeImage(__DIR__."/".($i+1).'-'.rand().'.jpg');
}
echo "All pages of PDF is converted to images";
}
echo "PDF doesn't have any pages";
}
?>
please send me codes
ReplyDeletewith zip format
DeleteYou can copy from here itself.
DeleteOf course, the ImageMagick is the best choice for open source to convert pdf to image, however it's not allowed to use the open source library in my project, so i found one nice and cheaper commercial library to convert pdf to jpg in my .net application https://www.iditect.com/tutorial/pdf-to-image/
ReplyDeleteOkay. Cool
Deleteplease how can i add resolution on this Imagemagick using your own code above
ReplyDelete