Generating a PDF With Images from Base64 with Prawn

依然范特西╮ 提交于 2019-12-05 07:11:55

There's no need to write the image data to a tempfile, Prawn::Document#image can accept a StringIO.

Try replacing this:

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

With this:

require 'stringio'
.....
image_data = StringIO.new( Base64.decode64(@image) )
pdf.image(image_data)

The Problem is, that the Api is returning this thing in UTF-8 - So I dont have a great choice. Anyhow, I found this solution to be working

  file = Tempfile.new('labelimg', :encoding => 'utf-8')
  File.open(file, 'wb') do |f|
    f.write Base64.decode64(@image)
  end

you can't convert the Base64 to UTF-8. Leave it as plain ASCII:

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

or even better - leave it as binary:

  file = Tempfile.new('labelimg')
  file.write Base64.decode64(@image)
  file.close

UTF-8 is multibite format and it's not usable for transferring binary data such as pics.

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