Right Now i am using Rails 3.0.0.i already installed the gem wicked_pdf.Now to want to save the pdf file inside the public folder.please help me.
Asked
Active
Viewed 1.5k times
3 Answers
11
If you need to just create a pdf and not display it:
# 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

arcooverbeek
- 185
- 8
7
Also, you can do this:
render :pdf => 'foo',
:save_to_file => Rails.root.join('public', "foo.pdf"),
:save_only => true

Unixmonkey
- 18,485
- 7
- 55
- 78
-
instant love for this answer <3 – abhishek77in Nov 20 '15 at 19:44
-
what happens if I run this command on something like Heroku ? Will it throw an error or hang, since heroku doesn't provide a writeable file system. – abhishek77in Nov 20 '15 at 19:54
-
2@abhishek77in You can write to the filesystem in most modern Heroku stacks, but you can't guarantee it will stick around if the dyno gets restarted. In that kind of situation, it would be better to save the file to an Amazon S3 bucket or something like that. If you need to save to the file system temporarily, it might be better to use `/tmp`. – Unixmonkey Nov 21 '15 at 00:42
-
@Unixmonkey do you know what route needs to be added to be able to access/open files saved to `/tmp`? Thanks. – Marklar Feb 14 '17 at 02:27
-
1@Marklar You wouldn't want a route to access `/tmp`, that'd be pretty bad from a security standpoint. I just used it for illustration of a place to save in the example above. In a real-world app, you'd likely want to save it to `public` or S3 or wherever you keep files for later retrieval. – Unixmonkey Feb 16 '17 at 19:54
7
This is top answer on How to convert string in pdf in ruby on rails
And if you aren't against i put one of the answer:
Some services returns pdf as a string like: JVBERi0xLjQKJeLjz9MKNCAwIG9iago8PC9Ue. . .
You can create a pdf file from the sting, with:
f = File.new("/tmp/file.pdf", "w")
f.write(Base64.decode64(invoice[:file]).force_encoding('UTF-8'))
f.close
And then you can open pdf file with AcrobatReader
or another pdf reader.
Wish it helps.

Azeez Ibrahim
- 13
- 5

itsnikolay
- 17,415
- 4
- 65
- 64