pdfkit does not style pdfs

tomciopp picture tomciopp · Nov 8, 2011 · Viewed 8.9k times · Source

I have a rails 3.1 app that creates pdf documents using pdfkit, and everything works as specified, except for the fact that the generated pdfs don't have any styling. I am assuming that wkhtmltopdf doesn't have access to my stylesheets and that it is not a larger issue than that. Would anyone have a clue as to how you would allow access to these stylesheets? I have basically followed railscast #220 on the subject, however I have had to create a new initializer to get pdfkit to work with rails 3.1.

This is the initializer that I had to use to get pdfkit to work with rails 3.1

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
 } 

The link to the pdf looks like this:

<%= link_to 'Download PDF', load_path(@load, :format => "pdf") %>

This will give me a link to the pdf that has no styling.

In my application.rb I have configured pdfkit as such:

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

I have also added this to my layouts/application.html.erb file:

<%= stylesheet_link_tag    "application", :media => "all" %>

Answer

user2185938 picture user2185938 · Aug 12, 2013

Stealing a couple of lines from the middleware code found at https://github.com/pdfkit/pdfkit/blob/master/lib/pdfkit/middleware.rb

You can use:

root = PDFKit.configuration.root_url || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
html.gsub!(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + root + '\3\2')

My example is:

html = render_to_string #render current action to string
root = PDFKit.configuration.root_url || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
html.gsub!(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + root + '\3\2')
kit = PDFKit.new(html, :print_media_type => true)