Header add


In this example we will see how to create and print PDF using Rotativa in ASP .NET MVC.

What is Rotativa ?

Rotativa is a framework that provides free APIs for providing an extremely easy way to print PDF documents in ASP.NET MVC Applications. Rotativa is based on the wkhtmltopdf tool to create a PDF document from HTML that renders in the browser.

Rotativa uses the web kit engine which is used by chrome browser to render HTML. Most of the HTML Tags and styles are supported by this framework. The Rotativa framework provides Rotativa namespace. This namespace contains following classes:

1. ActionAsPdf - accepts a view name as string parameter so that it can be converted into PDF.
2. PartialViewAsPdf - returns partial view as PDF.
3. UrlAsPdf - enables to return any URL as PDF.
4. ViewAsPdf - returns the result as PDF instead of HTML Response.

Step-1
Let's Create an MVC application in VS 2019 and create and Print the list using Rotativa.
 Create New Project and then choose MVC as application. Please follow the link how-to-create-mvc-application-in-visual studio 2019.html
Step-2
Let's create a table in database named as "T_Employee" with below attributes.
    CREATE TABLE [dbo].[T_Employee] (
        [empId]       INT          IDENTITY (1, 1) NOT NULL,
        [empName]     VARCHAR (50) NOT NULL,
        [Salary]      INT          NOT NULL,
        [DeptName]    VARCHAR (50) NOT NULL,
        [Designation] VARCHAR (50) NOT NULL,
        [HRA]         AS           ([Salary]*(0.2)),
        [TA]          AS           ([Salary]*(0.15)),
        [DA]          AS           ([Salary]*(0.18)),
        [GrossSalary] AS           ((([Salary]+[Salary]*(0.2))+[Salary]*(0.15))+[Salary]*(0.18)),
        [TDS]         AS           (((([Salary]+[Salary]*(0.2))+[Salary]*(0.15))+[Salary]*(0.18))*(0.25)),
        [NetSalary]   AS           (((([Salary]+[Salary]*(0.2))+[Salary]*(0.15))+[Salary]*(0.18))-
                                     ((([Salary]+[Salary]*(0.2))+[Salary]*(0.15))+[Salary]*(0.18))*(0.25)),
        PRIMARY KEY CLUSTERED ([empId] ASC)
    );
Please follow the link for more details about the Employee table : How to calculate automatically HRA, TA, DA, Gross, Net and TDS of employee based on Salary in SQL Server table
Step-3
Please add the Entity Data Model inside model folder and connect the Database table.

 Step-4
Through Nuget Package Manager console add the Rotativa .
You can see after install a new folder of the name Rotativa will be created in the project containing wkhtmltopdf.exe. This exe is a command line tool to render HTML into PDF.
 Step-5
Let's create a Employee Controller class and add the following action methods.
    using System;  
     using System.Collections.Generic;  
     using System.Linq;  
     using System.Web;  
     using System.Web.Mvc;  
     using PrintPDF_Rotativa.Models;  
     using Rotativa;  
     namespace PrintPDF_Rotativa.Controllers  
     {  
       public class EmployeeController : Controller  
       {  
         EmployeeEntity _empContext;  
         public EmployeeController()  
         {  
           _empContext = new Models.EmployeeEntity();  
         }  
         public ActionResult Index()  
         {  
           var emps = _empContext.T_Employee.ToList();  
           return View(emps);  
         }  
         public ActionResult PrintAllReport()  
         {  
           var report = new ActionAsPdf("Index");  
           return report;  
         }  
         public ActionResult IndexById(int id)  
         {  
           var emp = _empContext.T_Employee.Where(e => e.empId == id).First();  
           return View(emp);  
         }  
         public ActionResult PrintSalarySlip(int id)  
         {  
           var report = new ActionAsPdf("IndexById", new { id = id });  
           return report;  
         }  
       }  
     }  
Code Explanation >>
>> The Action Method Index() returns View object showing all Employees.
>> The Action method PrintAllReports() creates an instance of ActionAdPdf() class.
   The constructor of this class accepts a View Name as string parameter. In this
   case, the Index view is passed to it. This class prints the HTML rendered output
   of the Index view as PDF document.
>> The Action method IndexById() accepts an id parameter. This method searches an
   Employee based on its id and returns a view object showing an Employee information.
>> The Action method PrintSalarySlip() accepts an id parameter. Like the
   PrintAllreport() action method, this method too creates an instance of ActionAsPdf 
   class. The constructor of this class accepts IndexById view. This method returns
   HTML rendered IndexById view as a PDF document.
 Step-6
Right click on the Index method and add the view page.
    @model IEnumerable<PrintPDF_Rotativa.Models.T_Employee>  
     @{  
       ViewBag.Title = "Index";  
       Layout = "~/Views/Shared/_Layout.cshtml";  
     }  
     <h2>Index</h2>  
     <p>  
       @Html.ActionLink("Print All", "PrintAllReport",null,new { @class="btn btn-primary"})  
     </p>  
     <table class="table">  
       <tr>  
         <th>  
           @Html.DisplayNameFor(model => model.empName)  
         </th>  
         <th>  
           @Html.DisplayNameFor(model => model.Salary)  
         </th>  
         <th>  
           @Html.DisplayNameFor(model => model.DeptName)  
         </th>  
         <th>  
           @Html.DisplayNameFor(model => model.Designation)  
         </th>  
         <th>  
           @Html.DisplayNameFor(model => model.NetSalary)  
         </th>  
         <th></th>  
       </tr>  
       @foreach (var item in Model)  
       {  
         <tr>  
           <td>  
             @Html.DisplayFor(modelItem => item.empName)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.Salary)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.DeptName)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.Designation)  
           </td>  
           <td>  
             @Html.DisplayFor(modelItem => item.NetSalary)  
           </td>  
           <td>  
             @Html.ActionLink("Print Salary", "PrintSalarySlip", new { id = item.empId,@class="btn btn-info" })  
           </td>  
         </tr>  
       }  
     </table>  
Step-7
In the RouteConfig.cs of the App_Start folder update the default value of the Route as shown in the following code:
    public static void RegisterRoutes(RouteCollection routes)  
         {  
           routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
           routes.MapRoute(  
             name: "Default",  
             url: "{controller}/{action}/{id}",  
             defaults: new { controller = "Employee", action = "Index",
     id = UrlParameter.Optional }  
           );  
         }  
Step-8
Run the application and click the PrintAll button and you can see the output like below
You can see it print the data as PDF.
Now we need to take print the salary slip according to the row wise so need to add the IndexById view page.
    @model PrintPDF_Rotativa.Models.T_Employee  
     @{  
       ViewBag.Title = "IndexById";  
       Layout = "~/Views/Shared/_Layout.cshtml";  
     }  
     <div>  
       <h2>Salary Details of : @Model.empName</h2>  
       <table class="table table-bordered table-condensed table-striped">  
         <tr>  
           <td>Department Name :</td>  
           <td>@Model.DeptName</td>  
         </tr>  
         <tr>  
           <td>Designation :</td>  
           <td>@Model.Designation</td>  
         </tr>  
       </table>  
       <table class="table table-bordered table-condensed table-striped">  
         <tr>  
           <td>  
             <table class="table table-bordered table-condensed table-striped">  
               <tr>  
                 <td colspan="2">Income Details</td>  
               </tr>  
               <tr>  
                 <td>Salary</td>  
                 <td>@Model.Salary</td>  
               </tr>  
               <tr>  
                 <td>HRA</td>  
                 <td>@Model.HRA</td>  
               </tr>  
               <tr>  
                 <td>TA</td>  
                 <td>@Model.TA</td>  
               </tr>  
               <tr>  
                 <td>DA</td>  
                 <td>@Model.DA</td>  
               </tr>  
               <tr>  
                 <td>Gorss Salary</td>  
                 <td>@Model.GrossSalary</td>  
               </tr>  
             </table>  
           </td>  
           <td>  
             <table class="table table-bordered table-condensed table-striped">  
               <tr>  
                 <td colspan="2">  
                   Deductions  
                 </td>  
               </tr>  
               <tr>  
                 <td>TDS</td>  
                 <td>@Model.TDS</td>  
               </tr>  
               <tr>  
                 <td>Net Salary</td>  
                 <td>  
                   @Model.NetSalary  
                 </td>  
               </tr>  
             </table>  
           </td>  
         </tr>  
       </table>  
       <p>  
         @Html.ActionLink("Back to List", "Index")  
       </p>  
     </div> 
Now click the Print Salary link and the details would like below;
Let's see the GIF image to see the full result.


</> The Source Code is available in Github.com/CoreProgramm/

Post a Comment

Previous Post Next Post