« 25 Days of Ruby Gems - Ruby Advent Calendar 2020, December 1st - December 25th

Day 25 - hexapdf Gem - Read and Write PDF Documents. Start from Zero or Merge, Extract, Optimize and Much More

Written by gettalong Thomas Leitner

(Open source) software developer from Vienna, Austria. Creator of Kramdown and HexaPDF. Sci-Fi fan.

HexaPDF is a pure Ruby library with an accompanying application for working with PDF files. In short, it allows

HexaPDF was designed with ease of use and performance in mind. It uses lazy loading and lazy computing when possible and tries to produce small PDF files by default.

If you are concerned regarding the performance, have a look at the following gists which show that HexaPDF performs quite well:


Command Line

The manual page of the hexapdf command explains all functionality in detail. It basically strives to be a universal PDF manipulation tool.

The hexapdf command provides many other functionalities, like decrypting or encrypting a file, extracting images or files from a PDF file, inspecting a PDF file and more.

Ruby Code

Apart from providing the command line tool as one show-case application, the HexaPDF library can be used for all things PDFs (except for rendering). The examples section on the HexaPDF homepage shows some of the things you can do.

One person on Reddit needed to stitch individual pages together into a single file. The HexaPDF answer looks like this:

#!/usr/bin/env ruby
# Usage: stitch.rb column_count source.pdf dest.pdf
# Arranges the pages from source.pdf in a pattern where each +column_count+ pages
# are arranged from left to right. It is assumed that all pages are of the same
# size.
require 'hexapdf'

columns = ARGV[0].to_i
source_path, dest_path = *ARGV[1, 2]

source = HexaPDF::Document.open(source_path)
dest = HexaPDF::Document.new

rows = (source.pages.count / columns.to_f).ceil
page_width = source.pages[0].box.width
page_height = source.pages[0].box.height

puts "Source pages: #{source.pages.count} pages, #{page_width}pt x #{page_height}pt"
puts "Dest layout: #{columns} columns, #{rows} rows"

canvas = dest.pages.add([0, 0, page_width * columns, page_height * rows]).canvas
row = 1
column = 0
source.pages.each do |page|
  form = dest.import(page.to_form_xobject)
  canvas.xobject(form, at: [column * page_width, page_height * rows - row * page_height])
  column += 1
  if column == columns
    row += 1
    column = 0

And another one wanted to convert a huge text file into a single page PDF without too much whitespace. Solved with HexaPDF like this (note that the code in the link only worked with an older version of HexaPDF, the code below works with HexaPDF 0.6.0):

require 'hexapdf'
require 'hexapdf/layout/text_layouter'

# read the file given as first command line argument
text = File.read(ARGV[0])

# create a new PDF document
doc = HexaPDF::Document.new

# create a text box, calculate the height and width
box = HexaPDF::Layout::TextLayouter.create(text, width: 1_000_000,
                                           font: doc.fonts.add("Courier"))
rest, = box.fit
width = box.lines.map(&:width).max
height = box.actual_height
raise "error" unless rest.empty?

# use the width and height for a new page with this dimensions and get the painting canvas
canvas = doc.pages.add([0, 0, width, height]).canvas

# draw the text box on the canvas
box.draw(canvas, 0, height)

# write the resulting PDF

Yet another redditer wanted to remove the top 3cm of each page, the HexaPDF solution is this:

require 'hexapdf'

top_margin = 30 / 25.4 * 72
input = HexaPDF::Document.open(ARGV[0])
input.pages.each do |page|
  media_box = page.box.value.dup
  media_box[3] -= top_margin
  page[:MediaBox] = media_box

Sometimes one needs to create a PDF file from multiple JPEG images, one image per page, and wants to put them centered and scaled on the pages, with some space around. Here is the code to do that (note that placing images centered and scaled in a certain box will get much easier in the near future):

require 'hexapdf'

doc = HexaPDF::Document.new

ARGV.each do |image_file|
  image = doc.images.add(image_file)
  iw = image.info.width.to_f
  ih = image.info.height.to_f
  page = doc.pages.add(:A4, orientation: (ih > iw ? :portrait : :landscape))
  pw = page.box(:media).width.to_f - 72
  ph = page.box(:media).height.to_f - 72
  rw, rh = pw / iw, ph / ih
  ratio = [rw, rh].min
  iw, ih = iw * ratio, ih * ratio
  x, y = (pw - iw) / 2, (ph - ih) / 2
  page.canvas.image(image, at: [x + 36, y + 36], width: iw, height: ih)



If you need to work with PDFs in Ruby, HexaPDF is the way to go!

Find out more


Built with Ruby (running Jekyll) on 2021-07-25 15:15:02 +0000 in 0.371 seconds.
Hosted on GitHub Pages. </> Source on GitHub. (0) Dedicated to the public domain.