Monday 23 December 2013

How To Generate PDFs in Rails With Prawn(ruby 1.9.3 and rails 3.2)

 way 1  
 For creating PDFs i refereed these links(http://www.railstips.org/blog/archives/2008/10/13/how-to-generate-pdfs-in-rails-with-prawn/, http://stackoverflow.com/questions/8641941/rails-plugin-install-git-github-com-thorny-sun-prawnto-git-is-not-working-in)  
 I found few updates have to do on it. So writing this blog. Found any correction comment down without fail.   
 ruby - 1.9.3  
 rails - 3.2  
 create new project in rails  
 rails new prawn_sample  
 you can find gem file inside project folder, add prawn gem.  
 gem 'prawn'  
 gem "prawnto_2", :require => "prawnto"  
 then bundle install  
 now, install prawnto plugin  
 rails plugin install git@github.com:forrest/prawnto.git  
 For sample data to display, let’s create a Book model with title,author and description.  
 rails generate scaffold book title:string author:string description:text  
 then  
 rake db:migrate  
 now start the server and enter sample data's to test   
 so,   
 rails s  
 localhost:3000/books  
 here enter the required amount of data's  
 next  
 Let’s get started with something simple and add a pdf version of the show action. Open up the books controller and add format.pdf  
 def show  
  @book = Book.find(params[:id])  
  respond_to do |format|  
   format.html # show.html.erb  
   format.xml { render :xml => @book }  
   format.pdf { render :layout => false }  
   end   
 end  
 create the show.pdf.prawn file inside app/views/books. For now, lets have hello world  
 pdf.text "Hello World!"  
 visit  
 http://localhost:3000/books/1  
 http://localhost:3000/books/1.pdf  
 you successfully generated PDF.  
 Let’s make the view specific to the books.  
 in show.pdf.prawn  
 pdf.font "Helvetica"  
 pdf.text "Book: #{@book.title}", :size => 16, :style => :bold, :spacing => 4  
 pdf.text "Author: #{@book.author}", :spacing => 16  
 pdf.text @book.description  
 now you see some text with format specified above . Browse more for format you required.  
 way 2  
 Reference (http://stackoverflow.com/questions/8658302/unable-to-render-pdf-to-browser-using-prawn-pdf-for-ruby-on-rails)  
 Gemfile  
 gem 'prawn'  
 /config/initializers/mime_types.rb  
 Mime::Type.register "application/pdf", :pdf  
 AuditsController  
 def show  
   @audit = Audit.find(params[:id])  
   respond_to do |format|  
      format.html  
      format.pdf do  
        pdf = Prawn::Document.new  
        pdf.text "This is an audit."  
        send_data pdf.render, type: "application/pdf", disposition: "inline"  
      end  
    end  
  end