Converting pdf file to image file using imagemagick and groovy

19 / Apr / 2010 by Uday Pratap Singh 1 comments

Recently in one of my project user have the requirement where he can upload the pdf file and its get converted into the image file, that can be used by the user for manipulations.

After looking at here and there finally we find out the imagemagick tool which converts pdf file to image file. Its very easy to use this tool, all you need to do is

sudo apt-get install imagemagick

This tool gives you so many commands that can be used for image manipulation as well.

For converting the pdf into image first we stored the file uploaded by the user on the predefined location of file system and then use the simple imagemagick command.

String command = "convert ${sourcePath} -resize 2000x2000 ${destinationPath}/${fileName}"
def proc = command.execute()
proc.waitFor()

As you can see we make a simple command of imagemagick that takes the path of pdf file i.e; sourcePath and the size of the image file which we need to be in 2000×2000 in our case. The other argument needed was the destinationPath and fileName where the image file would be stored.

Now use execute() method which will execute the command for you and make the images out of pdf files. Remember you need to use the waitFor() method as well as it make sure the next command after the execute will not get executed until the file are properly stored on the file system because sometimes the file system takes few seconds to convert the file.

It also takes care about the multi page pdf files. It will create image for each page.

I hope my learning in this project will help somebody.

Hope it helps
Uday Pratap Singh
uday@intelligrape.com
https://twitter.com/meudaypratap

FOUND THIS USEFUL? SHARE IT

comments (1 “Converting pdf file to image file using imagemagick and groovy”)

  1. Bhagwat Kumar

    Great blog… specially the waitFor method call when you want the things to be synchronous , it helped me a lot.

    Reply

Leave a comment -