pdfkit不样式pdf [英] pdfkit does not style pdfs

查看:563
本文介绍了pdfkit不样式pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rails 3.1应用程序使用pdfkit创建pdf文档,一切正常工作,除了生成的pdf没有任何样式的事实。我假设wkhtmltopdf没有访问我的样式表,这不是一个更大的问题。任何人都有一个线索,如何将允许访问这些样式表?我已经基本上按照railscast#220上的主题,但是我不得不创建一个新的初始化来获得pdfkit使用rails 3.1。

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.

这是一个初始化程序,我不得不使用它来获取pdfkit使用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
 } 

指向pdf的链接如下: p>

The link to the pdf looks like this:

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

这将给我一个没有样式的pdf链接。

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

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

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

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



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

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

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


推荐答案

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

Stealing a couple of lines from the middleware code found at 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')

我的示例是:

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)

这篇关于pdfkit不样式pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆