sivakrishna.m
Joined: 01 Jan 2008 Posts: 160 Location: Narsipatnam
|
Posted: Mon Jan 04, 2010 10:56 am Post subject: PDF Generation By Using HTMLDOC gem in Ruby on Rails |
|
|
HTMLDOC is for converting the html pages into adobe portable document format and also is available in both open source and commercial versions. The wrapper class around HTMLDOC , providing methods for setting the options from ruby application and retriving generated output as a file, diretory or string.
For this there is Ruby HTMLDOC Gem, before installing the gem we have to install HTMLDOC software or packages.
1.For Linux users
===============
Installing HTMLDOC
==================
curl -O http://ftp.easysw.com/pub/htmldoc/snapshots/htmldoc-1.9.x-r1521.tar.gz
tar zxvf htmldoc-1.9.x-r1521.tar.gz
cd htmldoc-1.9.x-r1521
./configure --prefix=/usr/local
make
sudo make install
2. For Windows Users.
=====================
Installing HTMLDOC
==================
Download the latest HTMLDOC software from the site http://www.htmldoc.org/ and install.
After that installing HTMLDOC Gem for all users, follow the below steps
Installing HTMLDOC Gem
======================
> sudo gem install htmldoc ============> for Linux users
> gem install htmldoc ================> for windows users
After installation configure your application :
================================================
open the file config/environment.rb file and place the lines below
Mime::Type.register 'application/pdf', :pdf
require 'htmldoc'
next for DRY up the code add the following method to your application.rb file
def render_to_pdf(options = nil)
data = render_to_string(options)
pdf = PDF::HTMLDoc.new
pdf.set_option :bodycolor, :white
pdf.set_option :toc, false
pdf.set_option :portrait, true
pdf.set_option :links, false
pdf.set_option :webpage, true
pdf.set_option :left, '2cm'
pdf.set_option :right, '2cm'
pdf << data
pdf.generate
end
after that write the below code in your controller
def index
@items = Item.find(:all)
respond_to do |format|
format.html # index.html
format.xml { head k }
format.pdf { send_data render_to_pdf({ :action => 'index.rpdf', :layout => 'pdf_report' }) }
end
end
by calling the render_to_pdf method for pdf format responds.
and finally write the code for @items list of items in index.erb.html file
<table><tbody>
<tr>
<th>Name</th>
<th>Description</th>
<th>Created at</th>
</tr>
<% @items.each do |item| %>
<tr>
<td><%= item.name %></td>
<td><%= item.desc %></td>
<td><%= item.created_at %></td>
</tr>
<% end %>
</tbody></table>
finally place the link_to tag for generating pdf file
<%= link_to 'PDF', formatted_items_path(:pdf) %>
Thank You,
Siva |
|