为什么我的图像在使用 wicked_pdf_image_tag 时无法加载?

Why my image doesn't load when using wicked_pdf_image_tag?

我正在创建一项服务,将水印添加到客户端 pdf 文件的顶部。当我将它添加到 pdf 源时,html 文本加载正常但图像不加载(而是显示一个小方块)。

这是我的一些代码:

add_online_signature_to_partner_quote_pdf_service.rb:

class AddOnlineSignatureToPartnerQuotePdfService
  def initialize(quote)
    @quote = quote
  end

  def call
    pdf = CombinePDF.new

    source = CombinePDF.parse(@quote.document.download, { allow_optional_content: true })
    signature = CombinePDF.parse(generate_signature(@quote))

    pdf << source
    pdf << signature

    update_quote_with_signature(@quote, pdf)
  end

  private

  def generate_signature(quote)
    project = quote.project

    ac = ApplicationController.new

    pdf = WickedPdf.new.pdf_from_string(
      ac.render_to_string(
        template: "advanced_admin/quotes/form/_partner_quote_signature.pdf.erb",
        layout: "pdf.html",
        locals: { quote: quote, project: project, pdf: true }
      )
    )
  end

  def update_quote_with_signature(quote, pdf)
    quote.document.attach(
      io: StringIO.new(pdf.to_pdf),
      filename: "quote_complete.pdf",
      content_type: "application/pdf"
    )
  end
end

_partner_quote_signature.pdf.erb:

<div>
  <h1>my title</h1>
  <%= wicked_pdf_image_tag "logo-blue.png" %>
  <p>my paragraph</p>
</div>

我想在我的 PDF 中生成的图像通常位于我的资产管道中 app/assets/images/logo-blue.png

我尝试了很多我在其他主题上看到的不同语法,但似乎没有任何效果...... 'wkhtmltopdf-binary' gem 版本是 0.12.6.5

您知道如何让我的代码正常工作吗?非常感谢!

正如他们在 documentation 中所说:

The wkhtmltopdf binary is run outside of your Rails application; therefore, your normal layouts will not work. If you plan to use any CSS, JavaScript, or image files, you must modify your layout so that you provide an absolute reference to these files. The best option for Rails without the asset pipeline is to use the wicked_pdf_stylesheet_link_tag, wicked_pdf_image_tag, and wicked_pdf_javascript_include_tag helpers or to go straight to a CDN (Content Delivery Network) for popular libraries such as jQuery.

Using wicked_pdf_helpers with asset pipeline raises Asset names passed to helpers should not include the "/assets/" prefix. error. To work around this, you can use wicked_pdf_asset_base64 with the normal Rails helpers, but be aware that this will base64 encode your content and inline it in the page. This is very quick for small assets, but large ones can take a long time.

所以你可以这样做:

<%= image_tag wicked_pdf_asset_base64("logo-blue.png"), height: 300 %>