Skip to content

Instantly share code, notes, and snippets.

@sahidursuman
Created April 23, 2019 09:26
Show Gist options
  • Save sahidursuman/5b71660212f9214e9960eed6c5e765d4 to your computer and use it in GitHub Desktop.
Save sahidursuman/5b71660212f9214e9960eed6c5e765d4 to your computer and use it in GitHub Desktop.
Is my code buggy or does prawn have a bug?
require 'rubygems'
require 'prawn'
require 'prawn/measurement_extensions'
class Sheet
SIZE = "LETTER"
LAYOUT = :portrait
ELEMENTS = {
:header => { :position => [(4.5).in, (10.0).in], :width => 3.in },
:address => { :position => [(0.0).in, ( 8.5).in], :width => 3.in },
:method => { :position => [(4.5).in, ( 8.5).in], :width => 3.in },
:table => { :position => [(0.0).in, ( 6.5).in], :width => (7.5).in },
:footer => { :position => [(0.0).in, ( 1.5).in], :width => 3.in }
}
class << self
def multiple(orders, pdf = nil)
first = !pdf
pdf ||= Prawn::Document.new(:size => SIZE, :layout => LAYOUT)
orders.each do |order|
pdf.start_new_page unless first
new(order, pdf).render
first = false
end
pdf # returns the prawn pdf instance
end
end
attr_reader :order, :pdf
def initialize(order, pdf)
@pdf = pdf
@order = order
end
def render
[:header, :address, :method, :table, :footer].each do |element|
settings = ELEMENTS[element]
pdf.bounding_box(settings[:position], settings) do
self.send(element)
end
end
pdf # returns the prawn pdf instance
end
def header
pdf.float do
pdf.text "Invoice #"
pdf.text "Date:"
end
pdf.text @order[:receipt], :align => :right
pdf.text Time.now.strftime("%b. %d, %Y"), :align => :right
end
def address
pdf.text "Ship To"
pdf.text @order[:name]
pdf.text @order[:addr]
pdf.text @order[:csz]
end
def method
pdf.text "Shipping Method"
pdf.text @order[:ship]
end
def table
pdf.text "Ordered Items", :align => :center
data = @order[:items].map do |item|
[
item[:sku],
item[:qty],
item[:desc],
item[:price],
item[:total]
]
end
pdf.table data.unshift(
["SKU #", "QTY", "Description", "Unit Price", "Total"]
)
end
def footer
pdf.text "Filled By:", :align => :right
pdf.text "Checked By:", :align => :right
pdf.text "Processed On:", :align => :right
pdf.text "Tracking Number:", :align => :right
end
end
OUTFILE = "output.pdf"
orders = []
(1..20).each do |i|
orders << {
:receipt => i.to_s.rjust(4, "0"),
:name => "Bob Jones #{i}",
:addr => "#{i} S. Main",
:csz => "Hometown, USA",
:ship => "EXPRESS",
:items => []
}
(1..5).each do |j|
orders.last[:items] << {
:sku => (1000 - i * j).to_s.rjust(4, "0"),
:qty => j,
:desc => "Fab. product #{j}",
:price => "$1000.00",
:total => "FREE!"
}
end
end
pdf = Sheet.multiple(orders)
pdf.render_file(OUTFILE)
puts "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment