Simple PDFkit example in Rails 3
J u n
2 6
2 0 1 0
I couldn't find a good example of using PDFkit in rails, so I figured it out and am now making one.
1 2 3 |
gem 'pdfkit' # add in Gemfile bundle install |
Also register a pdf mimetype in config/initializers/mime_types.rb (Thanks to ravi for pointing this out)
1 |
Mime::Type.register_alias "application/pdf", :pdf |
Here's what I do in my controller:
1 2 3 4 5 6 7 8 9 10 |
respond_to do |format| format.html format.pdf { html = render_to_string(:layout => false , :action => "show.html.haml") kit = PDFKit.new(html) kit.stylesheets << "#{Rails.root}/public/stylesheets/screen.css" send_data(kit.to_pdf, :filename => "labels.pdf", :type => 'application/pdf') return # to avoid double render call } end |
It's pretty simple. The main thing I had to do was specify the format as html in the render_to_string call. You could make a show.pdf.haml I guess, but we're converting html to pdf so why duplicate the view?