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:

Step1:-
            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 = PDFKit.new(<<-HTML)
            HTML CODE
            HTML

            kit.to_file("html.pdf")

Wednesday, November 1, 2017

Image upload using paperclip gem in rails5

Image uploading is an important feature in web application. Here are few steps to enable image uploading function using “Paperclip gem”:

Step-1:
         Paperclip requires the installation of ImageMagick on your Mac machine:
              brew install imagemagick

Step-2:
         Open gemfile and add gem:
                gem 'paperclip'
         then run bundle install
                 
Step-3:
         After adding gem add the image column in your table, here users table. Run 
         command:
               rails generate migration add_image_to_users

         This will create new migration in db/migrate then run migration
Step-4:
         We also need to add validation for your image attribute. Add following code in your model                    'user.rb'

             has_attached_file :img, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"

             validates_attachment_content_type :img, content_type: /\Aimage\/.*\z/

Step-5:
         After that you need to edit in your users new form and edit form with following HTML code

            app/views/users/new.html.erb
            app/views/users/edit.html.erb   

               <div class="field">
                   <%= f.file_field :image %>
              </div>

Step-6:
         After submitting the form if you want to show the image you need to add following code to the  app/views/users/show.html.erb

            <p>
              <strong>Image:</strong>
              <%= image_tag @user.image %>
            </p>