Create PDF with shrimp Base64 images

I am trying to save multiple png in one pdf. I get a PNG from an API call to the Endicia label server, which gives me a Base64 encoded image as an answer.

Based on this question:

How to convert a base64 string to PNG using shrimp without saving to the 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

But I get the following error:

"\ x89" from ASCII-8BIT to UTF-8

Any idea?

+5
source share
3 answers

The problem is that Api returns this thing in UTF-8. Therefore, I do not have much choice. Anyway, I found this solution to work

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

temp, Prawn:: Document # 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)
+6

you cannot convert Base64 to UTF-8. Leave this as normal 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 a multibyte format and cannot be used to transmit binary data such as photographs.

0
source

All Articles