回答

6

如果你只是需要創建一個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 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 
5

此外,你可以這樣做:

render :pdf   => 'foo', 
     :save_to_file => Rails.root.join('public', "foo.pdf"), 
     :save_only => true 
+0

即時喜歡這個答案<3 – abhishek77in

+0

如果我在Heroku上運行這個命令,會發生什麼?它會拋出一個錯誤或掛起,因爲heroku不提供可寫文件系統。 – abhishek77in

+1

@ abhishek77in您可以寫入大多數現代Heroku堆棧中的文件系統,但是如果dyno重新啓動,則無法保證它會繼續存在。在這種情況下,最好將文件保存到Amazon S3存儲桶或類似的東西。如果您需要暫時保存到文件系統,最好使用'/ tmp'。 – Unixmonkey

5

這是頂端回答如何字符串轉換成PDF格式在軌道上的紅寶石
如果你不反對,我把其中一個答案:
一些服務返回pdf作爲像JVBERi0xLjQKJeLjz9MKNCAwIG9iago8PC9Ue. . .
您可以從刺痛PDF文件,具有:

f = File.new("/tmp/file.pdf", "w") 
f.write(Base64.decode64(invoice[:file]).force_encoding('UTF-8')) 
f.close 

然後你就可以打開PDF文件,AcrobatReader或其他PDF閱讀器。
希望它會有所幫助。

相關問題