I want to generate a pdf file from a DB record. Encode it into a Base64 string and store it in the database. Which works well. Now I want the opposite action, how can I decode the Base64 string and generate the pdf file again?
this is what i have tried so far.
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 not compatible with the Windows-1252 character set. If you need full UTF-8 support, use TTF fonts instead of PDF 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
Now I am getting below the error:
ASCII-8BIT encoding cannot be transparently converted to UTF-8. Make sure that the encoding of the string you are trying to use is set correctly
I tried How to convert a base64 string to PNG using a shrimp without saving on the server in Rails , but this gives me an error:
"\ xFF" from ASCII-8BIT to UTF-8
Can someone point me what I am missing?
source share