Jan 25, 2009

PDF generation with Prawn in Merb

In my company, the customer service representatives asked me to generate a PDF file format of the price letter for our customers, because those are relative sensitive files, which was used to be in M$ word format.

I started using HTMLDOC at first, which is fine if you've already had the HTML version. Really, I like it. It is pretty simple to set up and running. You do not need to care about too much about the layout and format of the file, because it is relatively easy to do that in a html.erb file. But there is a catch on production servers, if you have, like me, several different types of environment, Red Hat, Ubuntu, OS X, you really have to be care of the PATH to the binary htmldoc command. Otherwise the Phusion Passenger will throw out very strange error message.

After I came back from Ruby Conf 2008(if you were there, you problaly knew Gregory Brown, he held a hack session with Prawn.), so I decide to give Prawn a try.

Here are the steps( of cause within Merb):

1. Add mime type in your config file

2. In the view file, the form for the PDF request:

Please notice the :format => 'pdf'
3. In controller, provides the pdf format:


From here, you have two ways to send the PDF file:
In the controller/action

Or, in a pdf.erb file

Now, you should be able to get a PDF file.

UPDATE(Feb-23-2009):
Someone asked what if you using 'GET' instead of post?
Well, it is pretty simple, you can just add the format like:
resource(:ordering, @price_letter, :print, :format => :pdf)
I am hoping this is helpful.

3 comments:

Gregory Brown said...

Thanks for this post, feel free to link it on the Prawn mailing list.

But... have you tried Prawnto?

http://www.cracklabs.com/prawnto

-greg

Gregory Brown said...

Oh hmm... I'm sorry it must have been late (or early) when I read this. Prawnto isn't going to work with Merb, but it'd be cool if it did!

-greg

zhhz said...

Thanks for your comments, Greg. I will look at Prawnto to see if I can make it working with Merb.