Export to pdf using Rails 4 application by Mahidhar
- In gem file add
gem 'wicked_pdf', '~> 1.1'
bundle install
- Now goto
config/initializers/mime_types.rb
, add
Mime::Type.register “application/pdf”, :pdf - Because wicked_pdf is a wrapper for wkhtmltopdf, you’ll need to install that, too. The simplest way to install all of the binaries (Linux, OSX, Windows) is through the gem wkhtmltopdf-binary. To install that, add a second gem,
gem 'wkhtmltopdf-binary'
bundle install
- To generate the Initializer :
rails generate wicked_pdf
- And at particular controller,
respond_to do |format| format.html format.pdf do render pdf: “your file-name” end end
7. And restart the server (Because changes are made in config) .
8. To reference this using link,
<%= link_to “generate pdf”, your_path(format: :pdf) %>
( here your path will be a specific action in a controller )
9. After this is done, create a view file in the particular Folder, ie if suppose used link is in index action of products controller, then create index.pdf.erb
and write the code into that.
Till here it can be used in local host, in order to use in heroku then,
- Add gem
gem ‘wkhtmltopdf-heroku’
bundle install
- Goto http://wkhtmltopdf.org/obsolete-downloads.html and download the latest version specific to your operating system, extract the file content then paste into the bin folder in your rails project.
- Make sure that after downloading, extracted name you’ve to use in initialisers. In my case it is wkhtmltopdf-amd64, so I’ve used the same.
- And goto
wicked_pdf.rb
in initializers, and add this code:-if Rails.env.production? wkhtmltopdf_path = “#{Rails.root}/bin/wkhtmltopdf-amd64” else wkhtmltopdf_path = “/usr/local/bin/wkhtmltopdf” end WickedPdf.config = { exe_path: wkhtmltopdf_path, wkhtmltopdf: wkhtmltopdf_path}
- To add charts to pdf,
- Instead of using
gem ‘wkhtmltopdf-binary’
replace it withgem ‘wkhtmltopdf-binary-edge’, ‘~> 0.12.2.1’
- And next goto
wickef_pdf.rb
,- Replace this
WickedPdf.config = { exe_path: wkhtmltopdf_path, wkhtmltopdf: wkhtmltopdf_path}
with this
WickedPdf.config = { exe_path: wkhtmltopdf_path, javascript_delay: 2000, wkhtmltopdf: wkhtmltopdf_path}
Note:
javascript_delay: 2000
, is for wicked_pdf to take the screen shot and generate the chart, I’ve used 2000, if it doesn’t work try increasing the value upto 6000.
- Replace this
- At the top, add these two lines in a file where you need a charts in pdf,
<%= javascript_include_tag "https://www.google.com/jsapi" %>
<%= wicked_pdf_javascript_include_tag "chartkick" %>
Restart the server, and reload the page. Wait And Have Fun..
- Instead of using