[Awesome Ruby Gem] Use poppler and imagemagick library with pdftoimage gem to convert a PDF document into images

pdftoimage

PDFToImage is a ruby gem which allows for conversion of a PDF document into images. It uses poppler_utils to first convert the document to PNG and then allows usage of ImageMagick to convert the image into other formats.

The reasoning behind using poppler_utils is due to the fact that ghostscript occasionally has trouble with certain PDF documents which poppler_utils seems to be able to parse without error.

Prerequisites

RMagick

These prerequisites are required for the latest version of RMagick.

On Ubuntu, you can run:

1
$ sudo apt-get install libmagickwand-dev

On Centos, you can run:

1
$ sudo yum install gcc ImageMagick-devel make which

On Arch Linux, you can run:

1
$ pacman -Syy pkg-config imagemagick

On Alpine Linux, you can run:

1
$ apk add pkgconfig imagemagick imagemagick-dev imagemagick-libs

On macOS, you can run:

1
$ brew install pkg-config imagemagick

poppler_utils

On macOS, you can run:

1
$ brew install poppler

Installation

You can install it as a gem:

1
$ gem install rmagick

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# robflynn/pdftoimage: A ruby gem for converting pdfs to images.
# https://github.com/robflynn/pdftoimage
gem 'pdftoimage', '0.1.7'

Then, run bundle install.

1
$ bundle install

Examples

1
2
3
4
5
6
7
8
9
10
require 'pdftoimage'
images = PDFToImage.open('somefile.pdf')
images.each do |img|
img.resize('50%').save("output/page-#{img.page}.jpg")
end

require 'pdftoimage'
PDFToImage.open('anotherpdf.pdf') do |page|
page.resize('150').quality('80%').save('out/thumbnail-#{page.page}.jpg")
end

References

[1] robflynn/pdftoimage: A ruby gem for converting pdfs to images. - https://github.com/robflynn/pdftoimage

[2] pdftoimage | RubyGems.org | your community gem host - https://rubygems.org/gems/pdftoimage

[3] poppler — Homebrew Formulae - https://formulae.brew.sh/formula/poppler

[4] imagemagick — Homebrew Formulae - https://formulae.brew.sh/formula/imagemagick

[5] pkg-config — Homebrew Formulae - https://formulae.brew.sh/formula/pkg-config