How to Render Blob Images in a Prawn Document

Is it possible to render blob images in a prawn document?

You should be able pass the image data as a StringIO

require 'stringio'
require 'pdf'

Prawn::Example.generate("foo.pdf") do |pdf|
data = StringIO.new(render_my_image_to_a_string)
pdf.image(data)
end

How to put an image on a label using Prawn/labels?

The answer appears to be to use something called StringIO, which apparently provides a File interface to an in-memory (blob) image.

So, I added the middle line, below:

    png = Barby::PngOutputter.new(tag[2]).to_png
str_png = StringIO.new(png)
pdf.image(str_png)

instead of trying to pass binary data via embed_image, and I am now getting the barcode in the final PDF output. (It still needs some tweaking, but the basic concept is now working.)

I had searched here many ways — really! But the word "blob" is what got the answer on this site.

Generating a PDF With Images from Base64 with Prawn

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

why ruby prawn draw from bottom

This is because, as stated in the manual - https://github.com/prawnpdf/prawn/blob/c504ae4e683017d7afadece084734a9190230cd8/manual/basic_concepts/origin.rb#L5, PDF documents have their origin (0,0) at the bottom left of the page. Therefore when you specifically tell something to draw at [0,0] it will draw at the bottom left of its encapsualating bounding box, which in your case is the page.

How to save a base64 string as an image using ruby

When writing binary data to a file, such as is the case with an image, you cannot use text printing tools like IO#puts.

There's two things you need to ensure:

  • You need to be writing in binary mode to avoid any possible LF to CRLF expansion.
  • You must use write instead of puts as write can work on arbitrary data, but puts (literally "put string") is exclusively for text.

Combining these you get:

File.open('shipping_label.gif', 'wb') do |f|
f.write(Base64.decode64(base_64_encoded_data))
end


Related Topics



Leave a reply



Submit