How to save pdf file inside the public folder using wicked_pdf
Asked Answered
S

3

5

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.

Scree answered 2/6, 2012 at 12:14 Comment(0)
G
12

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
Genetic answered 4/6, 2012 at 9:41 Comment(0)
S
7

Also, you can do this:

render :pdf          => 'foo',
       :save_to_file => Rails.root.join('public', "foo.pdf"),
       :save_only    => true
Subaltern answered 5/6, 2012 at 23:21 Comment(5)
instant love for this answer <3Whereat
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.Whereat
@Whereat 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.Subaltern
@Subaltern do you know what route needs to be added to be able to access/open files saved to /tmp? Thanks.Rear
@Rear 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.Subaltern
L
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.

Layamon answered 15/9, 2014 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.