8

I cannot get wicked_pdf to display an image from active storage to a pdf file. Do I use: wicked_pdf_image_tag or wicked_pdf_asset_base64 or just image_tag in the pdf template. Then do I give a rails_blob_path(company.logo) or just company.logo to any other method?

Kazmin
  • 1,003
  • 1
  • 10
  • 26

4 Answers4

6

There is some ongoing work to add Active Storage support to wicked_pdf in this GitHub issue thread

Until that is added (you can help!), you can create a helper method something like this (which is a slightly modified version of an example from the thread above):

# Use like `image_tag(wicked_active_storage_asset(user.avatar))`
def wicked_active_storage_asset(asset)
  return unless asset.respond_to?(:blob)
  save_path = Rails.root.join('tmp', asset.id.to_s)
  File.open(save_path, 'wb') do |file|
    file << asset.blob.download
  end
  save_path.to_s
end

Or, if you can use web resources directly in your PDF creation process:

<img src="<%= @user.avatar.service_url %>">
<img src="<%= @user.avatar.variant(resize: "590").processed.service_url %>">
webaholik
  • 1,619
  • 1
  • 19
  • 30
Unixmonkey
  • 18,485
  • 7
  • 55
  • 78
1

instead of <%= image_tag url_for(@student_course.try(:avatar)) %> i used <%= image_tag polymorphic_url(@student_course.try(:avatar)) %>

worked for me.

Abhijith
  • 21
  • 1
0

I use service_url like this

image_tag(company.logo.service_url)

More info here: https://api.rubyonrails.org/v5.2.0/classes/ActiveStorage/Variant.html#method-i-service_url

cseelus
  • 1,447
  • 1
  • 20
  • 31
  • This worked great. Previously the active storage URL (redirect) would cause wickedPDF to hang, and lock up the rails app. – freshop Mar 08 '22 at 21:43
0

Unixmonkey's suggested solution worked, but I don't like that the asset is downloaded every time, even if it already exists in the tmp directory.

This is the modified version that worked best for me. I've based the path on the blob key, which should ensure the latest version of our asset is rendered. Pathname is required to ensure that the directories are created for the path:


    # Use like `image_tag(wicked_active_storage_asset(facility.logo))`
    def wicked_active_storage_asset(asset)
      return unless asset.respond_to?(:blob)
      save_path = Rails.root.join('tmp', asset.blob.key)
      begin
        require 'pathname'
        some_path = Pathname(save_path)
        some_path.dirname.mkpath
        File.open(save_path, 'wb') do |file|
          file << asset.blob.download
        end
      end unless File.exist?(save_path)
      save_path
    end
webaholik
  • 1,619
  • 1
  • 19
  • 30