Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

ruby on rails - pdfkit does not style pdfs

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" %>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 + '32')

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 + '32')
kit = PDFKit.new(html, :print_media_type => true)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...