Hey guys, It’s a quickly post about how to generate pdf with prawn and google charts. Prawn is a awesome lib in ruby for generating PDF documents and google charts is a API to generate charts. I like to create a class responsible to generate my pdf documents. Here is my implementation:
# encoding: UTF-8
require 'open-uri'
class GenderReportPdf < Prawn::Document
def initialize(mens, womans)
super(top_margin: 70)
add_title
@mens = mens
@womans = womans
add_count
add_image
end
def add_title
text "Report by Gender", size: 28, style: :bold, position: :center
end
def add_count
move_down 20
text "Mens #{@h_count}"
text "Womans #{@m_count}"
end
def add_image
move_down 20
image get_external_image, :position => :center
end
def get_external_image
img = URI.parse(URI.encode("https://chart.googleapis.com/chart?cht=p3&chd=t:#{@mens},#{@womans}&chs=250x100&chl=Mens|Womans")).to_s
img = open(img)
end
end
It’s a simple ruby code, very easy to understand (I guess). In the next post I will show you how to send this report to client using Rails.