ruby-on-rails – 如何使用Prawn将base64字符串转换为PNG而不保存在Rails中的服务器上

所以我试图使用Prawn gem将Photoshop的PNG图像嵌入到PDF中. Base64字符串是使用canvas’toDataURL()函数生成的.由于图像仅在PDF中需要,我试图避免将其保存在服务器上. Params [:base64string]正确传递给服务器.

但是,我正在尝试使用

image = Prawn::Images::PNG.new(base64string)

创建图像,但我得到NoM​​ethodError:nil的未定义方法`unpack’:NilClass.

我有什么想法或者应该如何正确地做到这一点?

最佳答案 发现
here

Prawn想要文件路径而不是编码图像数据.你可以使用tempfile:

require 'prawn'
require 'tempfile'
require 'active_support' # for base64

Prawn::Document.generate('/tmp/test.pdf') do
  file = Tempfile.new('image')
  file.write ActiveSupport::Base64.decode64(image)
  file.close

  image file.path
end

希望这可以帮助!

点赞