ruby-on-rails - 使用 Prawn 从 Base64 生成带有图像的 PDF

标签 ruby-on-rails png base64 prawn

我正在尝试将多个 png 保存在一个 pdf 中。我从对 Endicia 标签服务器的 API 调用接收 PNG,它给我一个 Base64 编码图像作为响应。

基于这个问题:

How to convert base64 string to PNG using Prawn without saving on server in Rails

def batch_order_labels
  @orders = Spree::Order.ready_to_ship.limit(1)
  dt = Date.current.strftime("%d %b %Y ")
  title = "Labels - #{dt} - #{@orders.count} Orders"

  Prawn::Document.generate("#{title}.pdf") do |pdf|
    @orders.each do |order|
      label = order.generate_label
      if order.international?
        @image = label.response_body.scan(/<Image PartNumber=\"1\">([^<>]*)<\/Image>/imu).flatten.last
      else
        @image = label.image
      end

      file = Tempfile.new('labelimg', :encoding => 'utf-8')
      file.write Base64.decode64(@image)
      file.close


      pdf.image file
      pdf.start_new_page
    end
  end

  send_data("#{title}.pdf")
end

但我收到以下错误:

"\x89"从 ASCII-8BIT 到 UTF-8

任何的想法?

最佳答案

无需将图像数据写入临时文件,Prawn::Document#image 可以接受 StringIO。

尝试替换这个:

file = Tempfile.new('labelimg', :encoding => 'utf-8')
file.write Base64.decode64(@image)
file.close
pdf.image file

有了这个:
require 'stringio'
.....
image_data = StringIO.new( Base64.decode64(@image) )
pdf.image(image_data)

关于ruby-on-rails - 使用 Prawn 从 Base64 生成带有图像的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15081079/

相关文章:

sql - Rails 3 中的 ActiveRecord 生成的 SQL

javascript document.getElementById().value 仅适用于数字而不适用于字符串

java - PPTX 到 PNG 颜色渲染 – Apache POI

delphi - PNGImage "Access violation"程序结束时出现错误

PHP + GD : imagetruecolortopalette not keeping transparency

javascript - 压缩捕获的图像并将其保存到 localStorage

android - 在 Android 中解码 JSON base64 数据(来自 PHP 的 base64_encode)?

ruby-on-rails - 启动 Rails 服务器时 "Uncaught exception: no acceptor (port is in use or requires root privileges)"

ruby-on-rails - ERB 中的不同标签

javascript - 使用javascript将base64string转换为可下载文件