I am using ruby 1.9.2 and rails 3. I think Wicked pdf is better than other rails pdf generation plugins. To start with wicked follow the steps :
- $ cd /home/MyApp
Install wkhtmltopdf first .Open gem file, and add the line
gem ‘wkhtmltopdf’
$ bundle install
Wicked pdf is using the wkhtmltopdf to create a pdf document from a rails html template.
With wicked pdf we can,- Define documents structure through a simple html document.
- Theme them through CSS
Just Download the static complied version from wkhtmltopdf home page. Extract it and place it under /usr/local/bin.
Note : If your system is 64-bit download the 64Bit version. Else you get error, Something like ‘Exec Error’,’Executable format error’, etc.
Step 1: Open the terminal and go to your rails application folder.
- $ rails plugin install git://github.com/mileszs/wicked_pdf.git
now a configuration file is needed, we can use plugins generator script for it . But in rails 3 it will not work. Just copy the wicked_pdf.rb to initializers.
$ cp vendor/plugins/wicked_pdf/lib/wicked_pdf.rb config/initializers
and add the following to the config/initializers/wicked_pdf.rb
WICKED_PDF = {
:exe_path => ‘/usr/local/bin’
}
Step 2: Install wicked pdf plugin
- In my rails app I created an action index_pdf. Under the action put the following line.
def index_pdf
render :pdf => “my_pdf”,:layout => false,:template => ‘/users/index_pdf’,:footer => {:center =>
“Center”, :left => “Left”, :right => “Right”}
end
The render :pdf call has a lot of options. you can use these.
Step 3:Add pdf instructions to your controller.
- Put the link in your app, in your home page or somewhere.
<%= link_to ‘Create PDF document’, index_pdf_path(@user, :format => :pdf) %>
the index_pdf_path is the path I mentioned in the route.rb file,
match “/download_pdf(.:format)” => “users#index_pdf”, :method => :get, :as=>:index_pdf
When all are set click the link to download the pdf.
Step 4: Create a view file in app/view/index_pdf.erb
-
Include image in Wicked pdf
write a function in application helper to take your images in wicked pdf.
def pdf_image_tag(image, options = {})
options[:src] = File.expand_path(RAILS_ROOT) + ‘/public/images’ + image
tag(:img, options)
end
Add your image in public/images.
Write the following code in view <%= pdf_image_tag(‘photo.png’, :style=>”margin:0px;padding:0px”,:width=>”160″, :height=>”160″)%>
Its ‘wicked!!’ isn’t it?
I would like to know , can we use a pdf file as template to write the content using WickedPDF using Ruby on Rails. That means i will be accessing a PDF file with Header and footer on it and WickedPdf will use that template to write text on it.