2017-09-13 61 views
5

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

任何人都可以指向我,我缺少的是什么?

+0

@Med:OK,我们来试试将更新你很快 –

+0

@Med:收到此错误:'无效字节顺序UTF-8' –

+0

你的问题还不清楚。首先你说你在数据库中存储了一个PDF文件。然后你问你如何从数据库中的数据生成一个PDF文件。但你只是说数据*是一个PDF文件!那么,这是什么? –

回答

5

答案是解码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数据的情况下(来自Prawn对象)对字符串进行编码(而是将其保存为String对象)。即:

    encoded_string = Base64.encode64(my_pdf.render) 
    
  3. String数据可直接仅使用String直接而不是读从文件的任何数据被用来作为电子邮件附件,类似于图案provided here。即:

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

感谢您的回答,我可以作为附件发送,而无需另存为我的系统中的物理文件? –

+0

@GaganGami - Yap,您可以将该字符串作为附件发送,而不必将其保存到磁盘。我不记得袖口上的“Rails方式”。您也可以将Prawn数据呈现为字符串(在对其进行编码之前),而不是将其渲染为文件(使用'#render'而不是'#render_file')。不需要临时文件。 – Myst

+0

'render'工作正常,我已经将编码字符串转换为物理pdf文件,但我不想将该文件保存到任何位置,而是想要一些可以附加到邮件而不保存到磁盘的文件对象作为临时文件 –

相关问题