使用Prawn从Base64生成包含图像的PDF [英] Generating a PDF With Images from Base64 with Prawn

查看:84
本文介绍了使用Prawn从Base64生成包含图像的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个pdf中保存多个png.我正在从对Endicia Label Server的API调用中接收到PNG,这为我提供了Base64编码图像作为响应.

I am trying to save multiple pngs in one pdf. I'm receiving the PNGs from an API Call to the Endicia Label Server, which is giving me a Base64 Encoded Image as response.

基于此问题:

如何使用Prawn将base64字符串转换为PNG而不在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

但是我收到以下错误:

有什么想法吗?

推荐答案

问题是,Api在UTF-8中返回了此东西-所以我没有一个很好的选择. 无论如何,我发现此解决方案有效

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

这篇关于使用Prawn从Base64生成包含图像的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆