【问题标题】:Wicked-PDF image render with Rails Active Storage使用 Rails Active Storage 渲染 Wicked-PDF 图像
【发布时间】:2018-11-16 04:47:04
【问题描述】:
我无法让 wicked_pdf 将图像从活动存储显示到 pdf 文件。
我是否在 pdf 模板中使用:wicked_pdf_image_tag 或 wicked_pdf_asset_base64 或仅使用 image_tag。那我是给rails_blob_path(company.logo) 还是只给company.logo 给任何其他方法?
【问题讨论】:
标签:
wicked-pdf
rails-activestorage
ruby-on-rails-5.2
【解决方案1】:
目前正在进行一些工作,以在 this GitHub issue thread 中为 wicked_pdf 添加 Active Storage 支持
在添加之前(你可以帮忙!),你可以创建一个类似这样的辅助方法(这是上面线程示例的略微修改版本):
# 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
或者,如果您可以在 PDF 创建过程中直接使用网络资源:
<img src="<%= @user.avatar.service_url %>">
<img src="<%= @user.avatar.variant(resize: "590").processed.service_url %>">
【解决方案3】:
Unixmonkey 建议的解决方案有效,但我不喜欢每次都下载资产,即使它已经存在于 tmp 目录中。
这是最适合我的修改版本。我基于 blob 键的路径,这应该确保呈现我们资产的最新版本。需要Pathname 以确保为路径创建目录:
# 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