All formats

pdf-reader

LanguageRuby
LicenseMIT
Repositorygithub.com/yob/pdf-reader
DocumentationAPI docs on RubyDoc
Depends onAscii85, afm, hashery, ruby-rc4, ttfunk (gems)
Read / writeyes / no

pdf-reader parses PDF files in Ruby and exposes pages, text, metadata, fonts, images (XObjects) and the raw object graph. page.text returns the text with an approximate layout (spacing based on positions); page.runs returns text runs with coordinates and font sizes. For custom processing, it can walk a page’s content stream and call your receiver object for every operator. It decrypts files with RC4 and AES encryption when you have the password.

pdf-reader doesn’t render or modify PDFs. Text extraction quality depends on the file: fonts without a Unicode mapping produce garbage, and scanned PDFs need OCR.

Installation#

Shell
gem install pdf-reader

Basic usage: extract text from a PDF#

Ruby
require "pdf-reader"

reader = PDF::Reader.new("in.pdf")
puts "PDF #{reader.pdf_version}, #{reader.page_count} pages"
reader.pages.each do |page|
  puts "--- page #{page.number} ---"
  puts page.text
end

PDF::Reader.new also accepts an IO object, e.g. StringIO.new(data) for a PDF in memory.

How to read PDF metadata#

Ruby
reader = PDF::Reader.new("in.pdf")
info = reader.info      # Info dictionary as a Hash with symbol keys
puts info[:Title], info[:Author], info[:Producer]
puts reader.metadata    # XMP metadata XML, or nil

How to get text runs with positions#

Ruby
page = reader.page(1)
puts page.attributes[:MediaBox].inspect   # [0, 0, 595.28, 841.89]
page.runs.first(10).each do |run|
  puts "#{run.text} x=#{run.x} y=#{run.y} size=#{run.font_size}"
end

How to list fonts and images on a page#

Ruby
page = reader.page(1)
puts page.fonts.keys.inspect              # resource names, e.g. [:F1, :F2]
page.xobjects.each do |name, stream|
  puts "#{name}: #{stream.hash[:Subtype]} #{stream.hash[:Width]}x#{stream.hash[:Height]}"
end

How to open an encrypted PDF#

Ruby
reader = PDF::Reader.new("secret.pdf", password: "user")
puts reader.page(1).text

Tips#