Skip to content

Instantly share code, notes, and snippets.

@sr3d
Created May 25, 2010 20:10
Show Gist options
  • Save sr3d/413619 to your computer and use it in GitHub Desktop.
Save sr3d/413619 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'prawn'
require "prawn/measurement_extensions"
require 'ruby-debug'
# Put ignored bmml files here, one per line
src = ARGV[0]
output = ARGV[1]
ignored_files = [
"SKIP_ME.jpg"
]
# http://snippets.dzone.com/posts/show/805
class JPEG
attr_reader :width, :height, :bits
def initialize(file)
if file.kind_of? IO
examine(file)
else
File.open(file, 'rb') { |io| examine(io) }
end
end
private
def examine(io)
raise 'malformed JPEG' unless io.getc == 0xFF && io.getc == 0xD8 # SOI
class << io
def readint; (readchar << 8) + readchar; end
def readframe; read(readint - 2); end
def readsof; [readint, readchar, readint, readint, readchar]; end
def next
c = readchar while c != 0xFF
c = readchar while c == 0xFF
c
end
end
while marker = io.next
case marker
when 0xC0..0xC3, 0xC5..0xC7, 0xC9..0xCB, 0xCD..0xCF # SOF markers
length, @bits, @height, @width, components = io.readsof
raise 'malformed JPEG' unless length == 8 + components * 3
when 0xD9, 0xDA: break # EOI, SOS
when 0xFE: @comment = io.readframe # COM
when 0xE1: io.readframe # APP1, contains EXIF tag
else io.readframe # ignore frame
end
end
end
end
class Util
def self.dimension_of file
case file
when /\.png$/i
IO.read( file )[0x10..0x18].unpack('LL')
when /\.gif$/i
IO.read( file )[6..10].unpack('SS')
when /\.jpe?g$/i
jpg = JPEG.new( file )
return [ jpg.width, jpg.height ]
end
end
end
# Queue up the images
images = []
Dir.chdir src do
%w( *.png *.gif *.jpg *.jpeg ).each do |ext|
Dir.glob( ext ) do |file|
images << "#{src}/#{file}" unless ignored_files.include? file
end
end
end
images.sort!
# Baill out if there's no images
return if images.empty?
# Read the first image size to determine the initial layout
dim = Util.dimension_of images.first
Prawn::Document.generate( output, :page_size => "A4", :page_layout => dim[1] > dim [ 0 ] ? :portrait : :landscape ) do
# Append image to the pdf document
images.each_with_index do |img, i|
dim = Util.dimension_of( img )
start_new_page( :layout => dim[1] > dim [ 0 ] ? :portrait : :landscape ) if i > 0
image img, :position => :left, :vposition => :top , :fit => bounds.top_right
end
# Print the page #
number_pages "<page>", [bounds.left, 0]
# build the section outline
define_outline do
section 'Outline', :page => 1, :closed => true do
for i in 0...images.length
page i + 1, :title => images[i].split('/').last
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment