We have published an article on How to Convert HTML to PDF in PHP with fpdf and received many emails to write something on conversion from PDF to JPEG so today I am going to show you how we can convert PDF to JPEG and its a 4 lines script and very easy and simple to understand. We use PHP imagick extension which is mostly built-in in PHP installation so no need to include any thing.
Simple PHP Code:
<?php $imagick = new Imagick(); $imagick->readImage('mytest.pdf'); $imagick->writeImage('output.jpg'); ?>
In this code we have to give a PDF file and in output it will produce JPEG files for each page of your given PDF file.
If you want to convert first page of your PDF file only then define PDF file name like this mytest.pdf and run the script it will show convert only first page of your PDF file.
If you are using shared hosting and there is most of the time imagick extension not compiled with PHP only binaries available so here is to code to convert PDF to JPEG with imagick binaries.
<?php $location = "/usr/local/bin/convert"; // Binaries Location $name = "myfile.pdf"; //Source PDF File $nameto = "myfile.jpg"; // Output File $convert = $location . " " . $name . " ".$nameto; // Command creating exec ($convert); // Execution of complete command. echo "PDF converted to JPEG!!"; ?>
You have to change binaries location ($location = “/usr/local/bin/convert”;) to your server location which you can get from your hosting admin.
I have used binaries to perform this task in demo and download code if you have a PHP with compiled imageick then use first code and edit it as per your requirement.
This is a very simple and easy tutorial mostly for PHP Beginners I hope you like it please write down your reviews in comments.