Gag*_*ami 8 ruby pdf ruby-on-rails prawn
我想pdf从DB记录生成文件.将其编码为Base64字符串并将其存储到DB.哪个工作正常.现在我想要反向操作,如何解码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
Run Code Online (Sandbox Code Playgroud)
现在我得到以下错误:
编码ASCII-8BIT无法透明地转换为UTF-8.请确保正确设置您尝试使用的字符串的编码
我已经尝试了如何使用Prawn将base64字符串转换为PNG而不保存在Rails中的服务器上,但它给了我错误:
"\ xFF"从ASCII-8BIT到UTF-8
任何人都可以指出我错过了什么吗?
答案是解码Base64编码的字符串,直接发送或直接保存到磁盘(将其命名为PDF文件,但不使用prawn).
解码后的字符串是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.
Run Code Online (Sandbox Code Playgroud)
编辑
澄清评论中提供的一些信息:
可以将字符串作为附件发送而不将其保存到磁盘,使用render text: raw_pdf_str或#send_data方法(这些是4.x API版本,我不记得5.x API样式).
可以对字符串进行编码(来自Prawn对象)而不将渲染的PDF数据保存到文件中(而是将其保存为String对象).即:
encoded_string = Base64.encode64(my_pdf.render)
Run Code Online (Sandbox Code Playgroud)String数据可以直接用作电子邮件附件,类似于此处提供的模式,只使用String直接而不是从文件中读取任何数据.即:
# inside a method in the Mailer class
attachments['my_pdf.pdf'] = { :mime_type => 'application/pdf',
:content => raw_pdf_str }
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
2615 次 |
| 最近记录: |