Home > Back-end >  Why my image doesn't load when using wicked_pdf_image_tag?
Why my image doesn't load when using wicked_pdf_image_tag?

Time:09-21

I'm creating a service to add a watermark to the top of a client pdf file. When I add it to the pdf source, the html text loads fine but not the image (a small square is shown instead).

Here some piece of my code:

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>

The image I want to generate within my PDF is classically located in my asset pipeline app/assets/images/logo-blue.png

I tried a lot of different syntaxes I saw on other topics but nothing seems to work... The 'wkhtmltopdf-binary' gem version is 0.12.6.5

Do you have an idea how I could make my code working? Thanks a lot!

CodePudding user response:

As they said in the 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.

So you can do it like this :

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