Ruby on rails 如何使用wicked_pdf将pdf文件保存在公用文件夹中
现在我正在使用Rails 3.0.0。我已经安装了gem wicked_pdf.Now以将pdf文件保存在公用文件夹中。请帮助我。如果您只需要创建pdf而不需要显示它:Ruby on rails 如何使用wicked_pdf将pdf文件保存在公用文件夹中,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-3.1,pdf-generation,wicked-pdf,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 3.1,Pdf Generation,Wicked Pdf,现在我正在使用Rails 3.0.0。我已经安装了gem wicked_pdf.Now以将pdf文件保存在公用文件夹中。请帮助我。如果您只需要创建pdf而不需要显示它: # create a pdf from a string pdf = WickedPdf.new.pdf_from_string('<h1>Hello There!</h1>') # create a pdf from string using templates, layouts and conten
# create a pdf from a string
pdf = WickedPdf.new.pdf_from_string('<h1>Hello There!</h1>')
# create a pdf from string using templates, layouts and content option for header or footer
WickedPdf.new.pdf_from_string(
render_to_string(:pdf => "pdf_file.pdf", :template => 'templates/pdf.html.erb', :layout => 'pdfs/layout_pdf'),
:footer => {:content => render_to_string({:template => 'templates/pdf_footer.html.erb', :layout => 'pdfs/layout_pdf'})}
# or from your controller, using views & templates and all wicked_pdf options as normal
pdf = render_to_string :pdf => "some_file_name"
# then save to a file
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
#从字符串创建pdf
pdf=WickedPdf.new.pdf\u from\u string('Hello There!')
#使用模板、布局和页眉或页脚的内容选项从字符串创建pdf
WickedPdf.new.pdf_from_string(
render_to_string(:pdf=>“pdf_file.pdf”,:template=>“templates/pdf.html.erb”,:layout=>“pdf/layout_pdf”),
:footer=>{:content=>render_to_string({:template=>'templates/pdf_footer.html.erb',:layout=>'pdfs/layout_pdf'})
#或者从您的控制器中,正常使用视图和模板以及所有pdf选项
pdf=呈现到字符串:pdf=>“一些文件名”
#然后保存到一个文件
save_path=Rails.root.join('pdf','filename.pdf'))
打开(保存路径,'wb')do |文件|
文件此外,您还可以执行以下操作:
render :pdf => 'foo',
:save_to_file => Rails.root.join('public', "foo.pdf"),
:save_only => true
这是关于如何在RubyonRails中转换pdf格式字符串的首要答案
如果你不反对,我会给出一个答案:
一些服务返回pdf作为一个类似于JVBERi0xLjQKJeLjz9MKNCAwIG9iago8PC9Ue…
您可以通过以下方式从sting创建pdf文件:
f = File.new("/tmp/file.pdf", "w")
f.write(Base64.decode64(invoice[:file]).force_encoding('UTF-8'))
f.close
然后,您可以使用AcrobatReader
或其他pdf阅读器打开pdf文件。
希望它能有所帮助。对这个答案的即时喜爱如果我在Heroku这样的东西上运行这个命令会发生什么?它会抛出错误还是挂起,因为Heroku不提供可写的文件系统。@abhishek77in在大多数现代Heroku堆栈中,你可以写入文件系统,但你不能保证它会在dyno重新启动时保持不变。在在这种情况下,最好将文件保存到Amazon S3存储桶或类似的地方。如果您需要临时保存到文件系统,最好使用/tmp
@Unixmonkey。您知道需要添加什么路由才能访问/打开保存到/tmp
的文件吗?谢谢。@Marklar您不想这样做访问/tmp
的路径,从安全角度来看,这是非常糟糕的。我只是在上面的示例中用它来说明要保存的位置。在现实世界的应用程序中,您可能希望将其保存到public
或S3,或者保存文件以供以后检索的任何位置。