3

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?

tomciopp
  • 2,602
  • 2
  • 31
  • 60

1 Answers1

15

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
}
tomciopp
  • 2,602
  • 2
  • 31
  • 60
  • 1
    create a new file in config/initializers (I named mine assets.rb) and paste the code into the file. – tomciopp Nov 30 '11 at 23:36
  • Thank you! You saved my second day of trying to fix it! – Nicolas Guillaume Mar 18 '12 at 21:09
  • 1
    I have `nil` for `request.env["REQUEST_PATH"]` in production mode – ka8725 Apr 17 '12 at 23:34
  • This didn't get it working for me - note also the problem with wkhtmltopdf versions, see this thread. http://stackoverflow.com/questions/12517640/why-does-pdfkit-wkhtmltopdf-hang-but-renders-pdf-as-expected-when-rails-app-is-k And this thread, the combination of the two resolved the issue for me on OSX 10.8 http://stackoverflow.com/questions/7531005/rails-3-and-pdfkit – benz001 Jan 24 '13 at 08:54