Search code examples
ruby-on-rails-3ruby-on-rails-3.1pdf-generationwkhtmltopdfpdfkit

pdfkit not rendering correctly in rails 3.1


I have followed the following railscast about adding pdfkit to an application, and I am having some issues with the generation of pdfs. Here are the following things that I have done:

I downloaded wkhtmltopdf via the homebrew package manager

brew install wkhtmltopdf

Then I added the pdfkit gem to my gemfile and ran the bundle install command. I added the following to my config/application.rb file

require 'pdfkit'
...
config.middleware.use PDFKit::Middleware, :print_media_type => true

I then changed my application layout file to include all stylesheet types.

If I run rake middleware, the command works and I can see the pdfkit middleware

When I try to append pdf to the end of my routes the application just hangs and I have to exit via the command line. If I create a link to the page I want to make into a pdf, it changes all of the markup so it looks like a corrupted file. (it looks like you opened a text file into a word processor or vice versa I can provide images if that helps) If I try to make css changes in my stylesheet they do not go into effect when I view them with the link to pdf. I am assuming that this has something to do with the new asset pipeline in rails has anyone else experienced this issue?


Solution

  • So I was right in assuming that my error had something to do with the asset pipeline, after doing some research it looks like you need to create a new initializer and add the following code:

    ActionController::Base.asset_host = Proc.new { |source, request|
      if request.env["REQUEST_PATH"].include? ".pdf"
        "file://#{Rails.root.join('public')}"
      else
        "#{request.protocol}#{request.host_with_port}"
      end
    }