How to render format in pdf in rails

后端 未结 5 905
长情又很酷
长情又很酷 2020-12-10 17:50

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

we are using

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

et

5条回答
  •  暖寄归人
    2020-12-10 18:19

    Finally its done with prawn and prawn-rails. Here are the details.

    To make my system ready

    # Add this to your Gemfile
    gem 'prawn'
    gem 'prawn_rails'
    
    # run
    bundle install
    

    I hit the url http://localhost:3000/regions i.e. to hit the index of RegionsController and it shows the page as pdf format.

    I have a Region Model with a single attribute name. Has two entries in regions table.

    [
     #,
     #
    ]
    

    My Controller Method:

    def index
        @regions = Region.all # Should return two region objects :)
    
        respond_to do |format|
            format.html # index.html.erb
            format.json { render json: @regions }
            format.pdf    # <---------- This will handle the pdf response
        end
    end
    

    I have created a view file in views/regions/index.pdf.prawn. Anyway the view file name format is :action.pdf.prawn and the view file is containing

    prawn_document() do |pdf|
        @regions.each {|r| pdf.text r.name}
    end
    

    This will just output the name of Regions.

    Thats it. You have your page in pdf format. Now just play with all other options provided by Prawn and Prawn-Rails. You can find some here - http://prawn-rails-demo.heroku.com/

    Just thinking to write a series of blogs guiding how to use different pdf generation tool with rails 3.

    Let me know if it solves your problem.

提交回复
热议问题