How to convert PDF files to images using RMagick and Ruby

tybro0103 picture tybro0103 · Jun 4, 2010 · Viewed 19.1k times · Source

I'd like to take a PDF file and convert it to images, each PDF page becoming a separate image.

"Convert a .doc or .pdf to an image and display a thumbnail in Ruby?" is a similar post, but it doesn't cover how to make separate images for each page.

Answer

Akash Agrawal picture Akash Agrawal · Jun 16, 2011

Using RMagick itself, you can create images for different pages:

require 'RMagick'
pdf_file_name = "test.pdf"
im = Magick::Image.read(pdf_file_name)

The code above will give you an array arr[], which will have one entry for corresponding pages. Do this if you want to generate a JPEG image of the fifth page:

im[4].write(pdf_file_name + ".jpg")

But this will load the entire PDF, so it can be slow.

Alternatively, if you want to create an image of the fifth page and don't want to load the complete PDF file:

require 'RMagick'
pdf_file_name = "test.pdf[5]"
im = Magick::Image.read(pdf_file_name)
im[0].write(pdf_file_name + ".jpg")