Get Number of pages in pdf by imagemagick

This one is work for me πŸ™‚


<?php
$document = new Imagick('file_name.pdf');
$pages_count = $document->getNumberImages(); //returns 2
?>
Advertisements

How to convert pdf page to image preview

A few months ago I was looking to create screenshots of PDF documents on the fly so that a preview could be shown to users of a website before downloading or opening the file.

The solution to my problem was simple…so simple in fact that I can’t believe I haven’t done it before.

This works on all the major OS’s – Windows, linux and Mac – you will just have to download and install the correct packages for the machine you want to run it on. Mac users may find it easier to use a package management tool such as Fink to handle the installation.

Install GhostScript

Download and install GhostScript which is an interpreter for PostScript and PDF. If your installing on a Linux machine it is likely that you will already have this installed, so check before hand.

Install ImageMagick

Download and install ImageMagick which is an fully feature laden image manipulation suite which we will use to convert the PDF. Again if your running Linux you may already have this installed – so double check and/or upgrade.

ImageMagick is an amazing tool and can handle pretty much anything you could think of doing to an image, and it’s fully command line based so you can use it on the fly from within your scripts.

The PHP Code

The PHP code that we will use to convert the PDF to a png will make use of the ImageMagick software that we just installed and call it from within the PHP script using the exec() function.

exec('convert "document.pdf" -colorspace RGB -geometry 200 "document.png"');

This line will convert the whole PDF document into individual images for each page at 200px wide. To just create an image of the first page of the PDF we use the following:

exec('convert "document.pdf[0]" -colorspace RGB -geometry 200 "document.png"');

To get the second page you would just replace ‘[0]’ with ‘[1]’ etc.

For more options check out the ImageMagick help pages or simply run ‘convert’ from the command line and play about with the options.

If your not a fan of PNG’s then simply change the extension to your favorite image type and it will output the screenshot in that format.

I found some image resolution and text DPI problem when converting pdf to images . So i have put density in function and get correct output

exec('convert -density 150 -quality 100% "document.pdf" -colorspace cmyk -geometry 1200 "document-7.png"');