Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine dimension of PDF pages with Ruby?

Tags:

ruby

pdf

Is there a good library that could determine the dimension of PDF pages?

I know of one way that is to use rghost gem to convert pdf to png then use image_size gem to read the png dimension. I dislike this method though.

like image 955
Trung Lê Avatar asked Dec 27 '22 05:12

Trung Lê


1 Answers

The pdf-reader gem can do this.

require 'pdf/reader'
require 'bigdecimal'

def pt2mm(pt)
  (pt2in(pt) * BigDecimal.new("25.4")).round(2)
end

def pt2in(pt)
  (pt / BigDecimal.new("72")).round(2)
end

reader = PDF::Reader.new("somefile.pdf")
reader.pages.each do |page|
  bbox   = page.attributes[:MediaBox]
  width  = bbox[2] - bbox[0]
  height = bbox[3] - bbox[1]

  puts "width: #{width}pts #{pt2mm(width).to_s("F")}mm #{pt2in(width).to_s("F")}in"
  puts "height: #{height}pts #{pt2mm(height).to_s("F")}mm #{pt2in(height).to_s("F")}in"
end
like image 151
James Healy Avatar answered Dec 30 '22 11:12

James Healy