2017-09-13 92 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文件,但我不想將該文件保存到任何位置,而是想要一些可以附加到郵件而不保存到磁盤的文件對象作爲臨時文件 –

相關問題