簡體   English   中英

使用 Rails Active Storage 渲染 Wicked-PDF 圖像

[英]Wicked-PDF image render with Rails Active Storage

我無法讓 wicked_pdf 將圖像從活動存儲顯示為 pdf 文件。 我是否在pdf模板中使用: wicked_pdf_image_tagwicked_pdf_asset_base64或只是image_tag 那么我是否給任何其他方法一個rails_blob_path(company.logo)或只是company.logo

此 GitHub 問題線程中,有一些正在進行的工作將 Active Storage 支持添加到wicked_pdf

在添加之前(您可以提供幫助!),您可以創建一個類似這樣的輔助方法(這是上面線程中示例的略微修改版本):

# 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 %>">

我像這樣使用service_url

image_tag(company.logo.service_url)

更多信息: https : //api.rubyonrails.org/v5.2.0/classes/ActiveStorage/Variant.html#method-i-service_url

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

而不是 <%= image_tag url_for(@student_course.try(:avatar)) %> 我使用了 <%= image_tag polymorphic_url(@student_course.try(:avatar)) %>

為我工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM