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?
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 %>">
instead of <%= image_tag url_for(@student_course.try(:avatar)) %> i used <%= image_tag polymorphic_url(@student_course.try(:avatar)) %>
worked for me.
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
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
© 2022 - 2024 — McMap. All rights reserved.
File.exist?(save_path)
. For that to work, thesave_path
must be unique to each attachment, for examplesave_path = Rails.root.join('tmp', 'wicked', "#{asset.attachment.record_type.downcase}-#{asset.attachment.record_id}-#{asset.blob.filename}")
– Anniceannie