I am streaming a prawn PDF to the frontend of my application, but it shows the image as 100% black. The image is a gif file that I convert to png using rmagick. If I save the pdf file on the backend, it looks correct. I have tried other png files instead, and they render properly. What aspects of the png file could cause it to work fine on the backend, but show up as a black rectangle on the frontend?
Backend code:
png_blobs = []
gif_blobs.each do |gif_blob|
gif = ImageList.new
# gif_blob is streamed from UPS' API
gif = gif.from_blob(Base64.decode64(gif_blob))
gif.crop!(0, 0, 1202, 800) # get rid of whitespace that comes with UPS label
gif.rotate!(-90.0)
gif.format = 'png'
gif.profile!("8bim",nil)
blob = gif.to_blob
png_blobs.push(StringIO.open(blob)) # I have tried using the blob and the file
gif.write('/tmp/myfile.png'){ |options| options.quality = 50 }
# png_blobs.push('/tmp/myfile.png')
end
Prawn::Document.new(page_size: [386, 578], margin: 0) do |pdf|
pdf.define_grid(columns: 38, rows: 57, gutter: 0)
png_blobs.each_with_index do |gif_png_blob, idx|
pdf.grid([0, 0], [57, 38]).bounding_box do
pdf.image gif_png_blob, scale: 0.2
# Same problem with this attempt below, except it turns 100% gray due to transparency
# pdf.transparent(0.5) do
# pdf.image '/tmp/myfile.png', width: 386, scale: 0.48
# end
# This actually works, but it is a completely different png file
pdf.image Rails.root.join('app/assets', 'images', 'ups_barcode.png'), scale: 0.2
end
pdf.start_new_page if idx < png_blobs.length - 1
end
pdf.render_file('/tmp/myfile.pdf') # This looks good
# this shows a black rectangle on the frontend
body['ShipmentResponse']['ShipmentResults']['PackageResults']['ShippingLabel'] = Base64.encode64(pdf.render)
end
Using
send_dataas opposed torender(along with other json) in rails seemed to fix this problem. That said, all of my other images and pdfs that didn't use ImageMagick were fine in therenderfunction.