开发者

PDFkit javascript issues

I have been looking into using PDFKit to gen开发者_C百科erate pdf reports for a Rail 3 app I'm working on. Basically if I use PDFKit as middleware any page in the app is nicely rendered to pdf including the javascript generated graphs.

However, I want to use a different layout for pdf reports that removes any of the sidebar or navigation details so instead of using the middleware option I have been playing around with adding the following to the relevant controller action

format.pdf {               
               html = render_to_string(:action => "show.html.erb", :layout => "report.html.erb")
               kit = PDFKit.new(html) 
               kit.stylesheets << "#{Rails.root}/public/stylesheets/application.css"
               send_data kit.to_pdf, :filename => "file.pdf", :type => :pdf}

(I also tried the neater option of extracting this functionality to a renderer option as Katz describes here but the logic and the problem are the same)

This definitely solves my layout problem but it appears that none of the app's javascripts are being run and the graphs are no longer appearing. I had a look at the PDFKit source but I couldn't spot any major differences in the way the pdfs are produced.

I'm still finding my feet with a lot of things with rails so I'm sure it is probably something pretty obvious that is staring me in the face. Any pointers that anyone might have would be greatly appreciated


This basically is the solution I went with which is roughly based on Katz's really great blog post

ActionController.add_renderer :pdf do |template, options|
  html = render_to_string template, options 
  html = translate_paths(html, env)
  kit = PDFKit.new(html) 
  css_files = Array.wrap(options.delete(:css)).each do |css_sheet|
    kit.stylesheets << "#{Rails.root}/public/stylesheets/#{css_sheet}.css"
  end
  send_data kit.to_pdf, :filename => options[:filename], :type => Mime::PDF
end 

The translate_paths method is basically the same as the one used in PDKKit rack middleware code which can be seen here and below

def translate_paths(body, env)
   # Host with protocol
   root = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/"
   body.gsub(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + root + '\3\2')
end


  1. add :print_media_type => true as an option with the middleware for example: config.middleware.use "PDFKit::Middleware", :print_media_type => true
  2. add :media => "all" while including your stylesheets
  3. in you stylesheet file add the following
@media print {     
  #id_of_divs_to_hide{
   display: none;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜