It makes sense now!

I just got through a few days of using jdpace’s PDFKit gem for rails. It is a very straightforward PDF generation tool for Rails which uses the wkhtmltopdf tool to generate PDF documents from HTML and CSS3. After watching the great-as-usual Railscast on the topic, there were just a couple of missing pieces that I had to put together from the PDFKit github wiki and few other sources. Here’s what the problem was:

I wanted to respond_to requests as either PDF or HTML, but only for certain actions. I also wanted to send formatting instructions to wkhtmltopdf. Here’s what filled in the blanks for me:

In environment.rb (this is a Rails 2.3.8 project):

require 'pdfkit' #above the run block
#code below belongs within the run block
config.middleware.use PDFKit::Middleware
  Mime::Type.register 'application/pdf', :pdf

In my controller I want to make the default layout nil (so my reports either use no layout, or use their own), and I want to respond to requests with pdf of the source page…

layout nil
def my_report
respond_to do |format|
      format.pdf {
        html = render_to_string(:action => "my_report")
       kit =, :page_size => 'Letter', :margin_bottom=>".25", :margin_top=>".25", :margin_left=>".25", :margin_right=>".25")
        kit.stylesheets << "#{Rails.root}/public/stylesheets/my_stylesheet.css"
        send_data(kit.to_pdf, :filename => "generate_a_file_name", :type => 'application/pdf')

That is all. You can also change the disposition option for the generated pdf in the respond_to block to have the pdf render in the browser rather than download. There are many references to using the extended help feature of wkhtmltopdf to find more formatting options to pass to the generator. Be sure to use the correct names! Some names in the help file will not be the same as their equivalent labels in your app.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s