Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render format in pdf in rails

I want the the table to be displayed in pdf format .

we are using

format.html
format.json{render json: @user}

etc for generating html ,json format

Similarly

  • I want to render the page as pdf .

so what steps are there if it is possible in rails???

like image 921
Mohammad Sadiq Shaikh Avatar asked Aug 25 '12 07:08

Mohammad Sadiq Shaikh


1 Answers

Step one:

register PDF type for use in respond_to blocks

# config/mime_types.rb
Mime::Type.register "application/pdf", :pdf

Step two:

in your controller respond to PDF format request

respond_to do |format|
    format.html
    format.json{render json: @user}
    format.pdf do
        # ...
        # here your PDF generating code
        # ...
        send_data(your_generated_pdf, filename: 'your_filename.pdf', type: 'application/pdf')
    end
end

For generating PDF you can use pdfkit with wkthmltopdf, Prawn and some other. Refer to the respective documentations on their usage.

Starting from Rails 5:

Step three:

add gem 'responders' as Rails 5 changelog says: "Remove respond_to/respond_with placeholder methods, this functionality has been extracted to the responders gem"

like image 125
silverdr Avatar answered Jan 03 '23 22:01

silverdr