Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...