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


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”:

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

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

         This will create new migration in db/migrate then run migration
         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/

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


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

         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

              <%= image_tag @user.image %>