大虾如何将Base64字符串转成pdf文件gem

How to convert Base64 string to pdf file using prawn gem

我想从 DB 记录生成 pdf 文件。将其编码为 Base64 字符串并将其存储到数据库中。哪个工作正常。现在我想要反向操作,如何解码 Base64 字符串并再次生成 pdf 文件?

这是我到目前为止尝试过的方法。

def data_pdf_base64
  begin
    # Create Prawn Object
    my_pdf = Prawn::Document.new
    # write text to pdf
    my_pdf.text("Hello Gagan, How are you?")
    # Save at tmp folder as pdf file
    my_pdf.render_file("#{Rails.root}/tmp/pdf/gagan.pdf")
    # Read pdf file and encode to Base64
    encoded_string = Base64.encode64(File.open("#{Rails.root}/tmp/pdf/gagan.pdf"){|i| i.read})
    # Delete generated pdf file from tmp folder
    File.delete("#{Rails.root}/tmp/pdf/gagan.pdf") if File.exist?("#{Rails.root}/tmp/pdf/gagan.pdf")
    # Now converting Base64 to pdf again
    pdf = Prawn::Document.new
    # I have used ttf font because it was giving me below error
    # Your document includes text that's not compatible with the Windows-1252 character set. If you need full UTF-8 support, use TTF fonts instead of PDF's built-in fonts.
    pdf.font Rails.root.join("app/assets/fonts/fontawesome-webfont.ttf")
    pdf.text Base64.decode64 encoded_string
    pdf.render_file("#{Rails.root}/tmp/pdf/gagan2.pdf")
  rescue => e
    return render :text => "Error: #{e}"
  end
end

现在我遇到以下错误:

Encoding ASCII-8BIT can not be transparently converted to UTF-8. Please ensure the encoding of the string you are attempting to use is set correctly

我试过 How to convert base64 string to PNG using Prawn without saving on server in Rails 但它给我错误:

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

任何人都可以指出我所缺少的吗?

答案是将Base64编码后的字符串进行解码,要么直接发送,要么直接存盘(命名为PDF文件,不用大虾)。

解码后的字符串是PDF文件数据的二进制表示,所以不需要使用Prawn,也不需要重新计算PDF数据的内容。

 raw_pdf_str = Base64.decode64 encoded_string
 render :text, raw_pdf_str # <= this isn't the correct rendering pattern, but it's good enough as an example.

编辑

澄清评论中给出的一些信息:

  1. 可以将字符串作为附件发送而不将其保存到磁盘,使用 render text: raw_pdf_str#send_data method(这些是 4.x API 版本,我不记得 5.x API 样式)。

  2. 可以在不将呈现的 PDF 数据保存到文件(而是将其保存到 String 对象)的情况下对字符串(来自 Prawn 对象)进行编码。即:

    encoded_string = Base64.encode64(my_pdf.render)
    
  3. 字符串数据可以直接用作电子邮件附件,类似于模式 provided here 仅直接使用字符串而不是从文件中读取任何数据。即:

    # inside a method in the Mailer class
    attachments['my_pdf.pdf'] = { :mime_type => 'application/pdf',
                                  :content => raw_pdf_str }