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

懵懂的女人 提交于 2019-12-23 12:15:09

问题


So I am trying to embed a PNG image of canvas to PDF using Prawn gem. Base64 string is generated by using canvas' toDataURL() function. As the image is only needed in PDF I'm trying to avoid saving it on the server. Params[:base64string] is correctly passed to the server.

However, I am trying to use

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

to create the image but I get NoMethodError: undefined method `unpack' for nil:NilClass.

Any ideas what I'm doing wrong or how this should be done correctly?


回答1:


found here:

Prawn wants a file path rather than encoded image data. You could use a 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

Hope this helps!



来源:https://stackoverflow.com/questions/13256723/how-to-convert-base64-string-to-png-using-prawn-without-saving-on-server-in-rail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!