How to save pdf file inside the public folder using wicked_pdf

13,630

Solution 1

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

Solution 2

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.

Solution 3

Also, you can do this:

render :pdf          => 'foo',
       :save_to_file => Rails.root.join('public', "foo.pdf"),
       :save_only    => true
Share:
13,630

Related videos on Youtube

chandrashekar
Author by

chandrashekar

Hi....

Updated on June 04, 2022

Comments

  • chandrashekar
    chandrashekar almost 2 years

    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.

  • abhishek77in
    abhishek77in over 8 years
    instant love for this answer <3
  • abhishek77in
    abhishek77in over 8 years
    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.
  • Unixmonkey
    Unixmonkey over 8 years
    @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.
  • Marklar
    Marklar about 7 years
    @Unixmonkey do you know what route needs to be added to be able to access/open files saved to /tmp? Thanks.
  • Unixmonkey
    Unixmonkey about 7 years
    @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.