我想從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
任何人都可以指向我,我缺少的是什麼?
@Med:OK,我們來試試將更新你很快 –
@Med:收到此錯誤:'無效字節順序UTF-8' –
你的問題還不清楚。首先你說你在數據庫中存儲了一個PDF文件。然後你問你如何從數據庫中的數據生成一個PDF文件。但你只是說數據*是一個PDF文件!那麼,這是什麼? –