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

1

5

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?

Carnegie answered 6/11, 2012 at 18:3 Comment(0)
F
2

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!

Frequentation answered 6/11, 2012 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.