Blog

Export to pdf using Rails 4 application by Mahidhar

  1. In gem file add
    gem 'wicked_pdf', '~> 1.1'
  2. bundle install
  3. Now goto config/initializers/mime_types.rb, add
    Mime::Type.register “application/pdf”, :pdf
  4. 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

  5. To generate the Initializer :
    rails generate wicked_pdf
  6. 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,

  1. Add gem
    gem ‘wkhtmltopdf-heroku’ 
  2. bundle install
  3. 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.
  4. 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.
    1. 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}
  1. To add charts to pdf,
    1. Instead of using gem ‘wkhtmltopdf-binary’ replace it with
      gem ‘wkhtmltopdf-binary-edge’, ‘~> 0.12.2.1’
    2. And next goto wickef_pdf.rb,
      1. 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.

    3. 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..