【问题标题】:Rails 5 - wkhtmltopdf does not include bootstrapRails 5 - wkhtmltopdf 不包括引导程序
【发布时间】:2017-10-24 22:29:06
【问题描述】:

问题 - wkhtmltopdf 在生成显示 PDF 时不包含我的 Bootstrap 样式。我已经尝试了许多来自互联网的方法,但都没有运气。

系统规格

  • Rails 5.1.4
  • ruby 2.4.2p198(2017-09-14 修订版 59899)[x86_64-darwin17]

这里是sn-ps的代码:

# Gemfile
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
gem 'bootstrap-sass', '~> 3.3.6'

# app/controllers/forms_controller
def show
  @form = Form.find(params[:id])
  respond_to do |format|
    format.html
    format.pdf do
      render pdf: "#{@form.id}",
        template: 'forms/show.html.erb',
        locals: { f: @f }
    end
  end
end

# app/views/forms/show.html.erb
<%= render 'forms/form.html.erb' %>

【问题讨论】:

  • 您是否按照wicked_pdf 文档中的说明在form.html.erb 中包含了stylesheet_link_tagwicked_pdf_stylesheet_link_tag
  • @jvillian - 如果我使用 bootstrap-sass gem,我的 bootstrap 样式表在哪里?
  • 我这样做是为了包括引导程序:wicked_pdf_stylesheet_link_tag "bootstrap.css"。我不记得是否有进一步的配置。
  • 顺便说一句,如果您在 Heroku 上进行部署,您将需要使用 gem 'wkhtmltopdf-heroku',除非您希望 wkhtmltopdf-binary 立即吸收已知宇宙中的所有可用内存。
  • @jvillian - 感谢您让我知道那颗宝石。我会完全将wkhtmltopdf-binary 推到heroku。另一方面,我采纳了您的建议并将&lt;%= wicked_pdf_stylesheet_link_tag "bootstrap.css" %&gt; 放在app/views/layouts/application.html.erb 的标题中。不幸的是,一切都没有改变。

标签: ruby-on-rails ruby twitter-bootstrap wkhtmltopdf


【解决方案1】:

form.html.erb 应该是这样的:

<%= stylesheet_link_tag wicked_pdf_asset_base64("form_stylesheet") %> 
<%= wicked_pdf_stylesheet_link_tag "bootstrap.css" %>
<%= stylesheet_link_tag "http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css", media: "all" %>

我在其中添加了一条包含 Fontawesome 字体的行 - 只是为了让您可以看到那一点。

然后,在您的form_stylesheet.sass(应该位于app/assets/stylesheets)中,您应该有类似的内容:

@import 'bootstrap-sprockets'
@import 'bootstrap'
@import 'some_other_styling'

注意事项:

  • 我使用sass 作为我的css 预处理器。如果您使用的是直接 css 或 scss,则需要进行适当的修改。
  • 'some_other_styling' 是您可以放置​​其他 css 规则的地方。如果您没有,请不要包含该行。

所有这些似乎都对我有用...

哦,在config/initializers/wicked_pdf.rb,我有:

WickedPdf.config ||= {}
WickedPdf.config.merge!({
  # your extra configurations here
})

def wicked_pdf_asset(*sources)
  sources.collect { |source|
    asset = Rails.application.assets.find_asset("#{source}.sass")

    if asset.nil?
      #raise "could not find asset for #{source}.css"
    else
      "<style type='text/css'>#{asset.body}</style>"
    end
  }.join("\n").gsub(/url\(['"](.+)['"]\)(.+)/,%[url("#{wicked_pdf_image_location("\\1")}")\\2]).html_safe
end

我不记得这是否有助于我解决问题。

【讨论】:

  • 感谢您发布该解决方案。但是,在阅读本文之前,我发现了一个 Git 存储库,我环顾四周并弄清楚了! github.com/eltonsantos/wicked_pdf_example
  • 好消息!答案在我发布的任何内容中吗?如果没有,也许您可​​以添加自己的答案,以便未来的读者可以看到您是如何解决它的,而无需翻阅 git 存储库。
  • 您间接为我指明了正确的方向,所以我知道如何在 Google 中搜索“更智能”!今天晚些时候我会发布解决方案:)
  • 很想看看你添加了什么@JeffreyWen
猜你喜欢
  • 2013-11-14
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多