pdfkit没有样式pdf

tom*_*opp 18 css pdf-generation ruby-on-rails pdfkit ruby-on-rails-3.1

我有一个使用pdfkit创建pdf文档的rails 3.1应用程序,除了生成的pdf没有任何样式这一事实外,一切都按指定的方式工作.我假设wkhtmltopdf无法访问我的样式表,并且它不是一个更大的问题.有人会知道如何允许访问这些样式表吗?我基本上已经关注了这个主题的railscast#220,但是我必须创建一个新的初始化程序来使pdfkit与rails 3.1一起使用.

这是我必须使用的初始化程序,以使pdfkit与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
 } 
Run Code Online (Sandbox Code Playgroud)

pdf的链接如下所示:

<%= link_to 'Download PDF', load_path(@load, :format => "pdf") %>
Run Code Online (Sandbox Code Playgroud)

这将为我提供一个没有样式的pdf链接.

在我的application.rb中,我已经配置了pdfkit:

config.middleware.use PDFKit::Middleware, :print_media_type => true
Run Code Online (Sandbox Code Playgroud)

我还将此添加到我的layouts/application.html.erb文件中:

<%= stylesheet_link_tag    "application", :media => "all" %>
Run Code Online (Sandbox Code Playgroud)

小智 5

https://github.com/pdfkit/pdfkit/blob/master/lib/pdfkit/middleware.rb上的中间件代码中窃取几行代码

您可以使用:

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

我的例子是:

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)
Run Code Online (Sandbox Code Playgroud)


Mar*_*Huk 1

我使用 gem 'wicked_pdf' 及其助手将 CSS 包含到页面中。在内部,帮助程序只是读取所有 CSS 文件并包含到页面本身中。因此,如果您更喜欢使用 PdfKit,请尝试研究如何包含非内联样式表。