Friday, March 23, 2018

Generate PDF using rails view with PDFKit gem

PDFKit gem is used to generate PDF files using HTML from rails view and style code. We will use this gem to generate PDF for our Rails5 application.

Following are the steps where we need to change in code:

            Open a gemfile and install following gems
                 gem 'pdfkit'
                   gem 'render_anywhere'

            Then run bundle install.

Step 2:-
            Add following line in your config/application.rb
                config.middleware.use PDFKit::Middleware, :print_media_type => true

Step3 :-
           Add following line in your  layout/application.html.erb
               <%= stylesheet_link_tag 'application', :media => "all" %>

Step 4:-
          Give the link of pdf on view page so that it will convert the page in form pdf format. Add the following link your orders/show.html.erb
            <%= link_to "Download PDF",user_path(@user, format: "pdf") %></p>

Step5 :-
            If you want to convert some specific HTML data in pdf format, do following:

          require "pdfkit"
            kit =<<-HTML)
            HTML CODE