Using GChart with Prawn

I have been using the prawn gem in ruby to create PDF files. It’s a nifty little gem. It does what I need it to do easily. The only thing it really lacks is being able to control the look more. It seems limited to me.

Here is a quick snippet in creating a simple PDF file with an image.

require ‘prawn’
Prawn::Document.generate(“test.pdf”) do
image “test-image.jpg”
end

Simple enough.

I have also been using the gchart gem to create chart images via Google Charts.

require ‘gchart’
jsdata= Array.new
legenddata=Array.newjsdata=[60,25,15]
legenddata=[“Yahoo”,”Google”,”MSN”]Gchart.pie(:data => jsdata, :labels=> legenddata)

Now combining the two gems does not always work. Technically, the following technique can work:

require ‘prawn’
require ‘gchart’
require “open-uri”jsdata= Array.new
legenddata=Array.newjsdata=[60,25,15]
legenddata=[“Yahoo”,”Google”,”MSN”]imagepic=Gchart.pie(:data => jsdata, :labels=> legenddata)

Prawn::Document.generate(“test.pdf”) do
open(imagepic)
end

Note the open-uri gem. That is used because the following a url to the image created via Google Charts:

Gchart.pie(:data => jsdata, :labels=> legenddata)

The problem here is that the url is not always readable by the open-uri gem. In the example I have been using the url looks like the following:

http://chart.apis.google.com/chart?chd=s:9ZP&chl=Yahoo|Google|MSN&cht=p&chs=300×200&chxr=0,60,25,15

THE WORK AROUND

Instead of using open-uri gem, lets use mechanize:

mechanize.rubyforge.org

Mechanize can resolve the Google charts url better. Instead to embed the link to the image via url, I save a copy of the image and use the prawn command to embed the image.

require ‘prawn’
require ‘gchart’
require “mechanize”jsdata=Array.new
legenddata=Array.new
mechdata=Mechanize.newjsdata=[60,25,15]
legenddata=[“Yahoo”,”Google”,”MSN”]imagepic=Gchart.pie(:data => jsdata, :labels=> legenddata)

mechdata.get(imagepic).save “savedimage.jpg”

Prawn::Document.generate(“test.pdf”) do
image “savedimage.jpg”
end

There might be a better way to do this but this method works for me. So far so good!

Be Sociable, Share!

Author: Mike

Share This Post On

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>