首页 > 解决方案 > WickedPdf 在生产中不显示来自 S3 的远程图像

问题描述

首先,一切都在我的开发环境中运行良好,在生产环境中运行良好,直到我将我的 Rails 应用程序更新到 Rails 5.2.2 和 Ruby 到 2.5.3(两者都只有几个小版本)。我更新了许多其他的 gem,但邪恶的 pdf 或 wkhtmltopdf-binary 都没有更新。我不确定他们的依赖关系。在生产中(使用 Heroku)wicked_pdf不会从我的域之外渲染图像。

这是我正在使用的宝石:

gem 'wicked_pdf' #version 1.1.0
gem 'wkhtmltopdf-binary' #version 0.12.4

以下代码在开发中有效,但在生产中无效:

<%= image_tag @invoice.job.customer.account.logo.url, width: 220 %>
<%= image_tag @invoice.job.customer.account.logo_url, width: 220 %>
<%= wicked_pdf_image_tag @invoice.job.customer.account.logo_url, width: 220 %>
<img  src="<%= @invoice.job.customer.account.logo_url %>" width="220">

显示本地图像适用于生产:

 <%= image_tag "logo.png" width: 220 %>

我认为这与 Heroku 有关,因为我已经阅读了有关 wkhtmltopdf-binary 和 Heroku 的问题,但我所做的尝试没有运气。

标签: ruby-on-railsrubyherokuruby-on-rails-5wicked-pdf

解决方案


所以我不得不使用不同的功能并从中获得帮助。该embed_remote_image方法可能是您最感兴趣的,也是我在较大的助手中使用它的方式(确定它是项目的正面还是背面图像,如果缺失则显示自定义缺失图像)。

  # PDF image include - dont' need link logic, needed for https images
  # per https://github.com/mileszs/wicked_pdf/issues/36#issuecomment-91027880
  require 'open-uri'
  def embed_remote_image(url, content_type)
    asset = open(url, "r:UTF-8") { |f| f.read }
    base64 = Base64.encode64(asset.to_s).gsub(/\s+/, "")
    "data:#{content_type};base64,#{Rack::Utils.escape(base64)}"
  end

  def issue_image_pdf_display(issue, graphic, size, sizeinpx, issuer = nil, nolink = false, chapter_issue = false)
    if !graphic.blank?
      if graphic == issue.imageback
        image_tag(embed_remote_image(issue.imageback_url(size), 'image/png'))
      else
        image_tag(embed_remote_image(issue.image_url(size), 'image/png'))
      end
    else
      missing_image_display(issue, size, sizeinpx)
    end
  end

您还需要构建包。https://github.com/dscout/wkhtmltopdf-buildpack.git


推荐阅读