ASP.NET MVC5 - Rotativa📦 - Easy Way To Create PDF And Image Files

In this article, we will see how to generate image/PDF/print PDF documents using Rotativa. It's a framework and provides free APIs to convert our HTML to PDF and Image.

Introduction
 
We have used many tools to generate/print the PDF documents from our application or database but this Rotativa will work like a Crystal Report to generate PDF documents and additionality, Rotativa will help us to convert the layout in an image. It is a framework and it provides free APIs to achieve this. Okay! Now, let's move forward to use this.
 
Prerequisites
  • Visual Studio
  • Basic knowledge of C#
Article Flow
  • Introduction to Rotativa
  • Create ASP.NET MVC Empty project
  • Create a Model
  • Load Employees and design a View
  • Flow of Rotativa
  • Generate PDF
  • Generate Image
Introduction to Rotativa
 
Rotativa is an open source package. We can easily generate the pdf using their library. Rotativa uses the web kit engine which is used by Chrome browser to render the HTML. Most of the HTML tags and styles are supported by this framework. The Rotativa framework provides Rotativa namespace. This namespace contains the following classes.
 
ActionAsPdf 
 
It accepts a View named as string parameter so that it can be converted into PDF and also, we are able to pass the second parameter, i.e., the action input params.
 
Syntax
  • public ActionAsPdf(string action);
  • public ActionAsPdf(string action, RouteValueDictionary routeValues);
  • public ActionAsPdf(string action, object routeValues);
PartialViewAsPdf
 
It's used to return the partial view as PDF.
 
Syntax
  • public PartialViewAsPdf();
  • public PartialViewAsPdf(string partialViewName);
  • public PartialViewAsPdf(object model);
  • public PartialViewAsPdf(string partialViewName, object model);
UrlAsPdf
 
It enables us to return any URL as PDF.
 
Syntax 
  • public UrlAsPdf(string url); 
ViewAsPdf
 
It returns the result as PDF instead of HTML Response.
 
Like this, Rotativa has more than 10 classes to generate pdf and images. We will see one by one.
 
Create ASP.NET MVC Empty project
  • To create an ASP.NET MVC empty project, follow the below steps one by one. Here, I have used Visual Studio 2017.
  • Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "GeneratePDF".
  • Now, click OK.
  • Then, select Empty ASP.NET MVC template and click OK to create the project.
  • Once you click OK, the project will be created with the basic architecture of MVC. If you are not aware of how to create an Empty ASP.NET Web Application, please visit Step 1 and Step 2 to learn.
 Once you complete these steps, you will get the screen as below.
 
 
 
Create a Model
 
Now we are going to create a model to hold the values of the employee. Here, I have created one with the name of "EmployeeModel".
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace GeneratePDF.Models {  
  6.     public class EmployeeModel {  
  7.         public int ID {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string Name {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Designation {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public decimal Salary {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  
Load Employees and design a view
 
I have created the list of an employee under "GeneratePDF" controller as below
  1. /// <summary>  
  2. /// Load all Employees  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. private List < EmployeeModel > LoadEmployees() {  
  6.     List < EmployeeModel > employees = new List < EmployeeModel > () {  
  7.         new EmployeeModel() {  
  8.                 ID = 1, Name = "Gnanavel Sekar", Designation = "Sr.Software Engineer", Salary = 1500000  
  9.             },  
  10.             new EmployeeModel() {  
  11.                 ID = 2, Name = "Subash S", Designation = "Sr.Software Engineer", Salary = 1700000  
  12.             },  
  13.             new EmployeeModel() {  
  14.                 ID = 3, Name = "Robert A", Designation = "Sr.Application Developer", Salary = 1800000  
  15.             },  
  16.             new EmployeeModel() {  
  17.                 ID = 4, Name = "Ammaiyappan", Designation = "Sr.Software Developer", Salary = 1200000  
  18.             }  
  19.     };  
  20.     return employees;  
  21. }  
Create Action and View
 
Now let's create an action to return the list of an employee detail to the respective view 
  1. public ActionResult Employees()  
  2. {  
  3.    return View(LoadEmployees());  
  4. }  
And now create a strongly typed view as the list for this "Employees" action to view the list of an employee in table format using employee model.
  1. @model IEnumerable<GeneratePDF.Models.EmployeeModel>  
  2. @{  
  3. ViewBag.Title = "Employees";  
  4. Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <br />  
  7. <table class="table table-bordered">  
  8.     <tr>  
  9.         <th> @Html.DisplayNameFor(model => model.Name) </th>  
  10.         <th> @Html.DisplayNameFor(model => model.Designation) </th>  
  11.         <th> @Html.DisplayNameFor(model => model.Salary) </th>  
  12.         <th></th>  
  13.     </tr> @foreach (var item in Model) { <tr>  
  14.         <td> @Html.DisplayFor(modelItem => item.Name) </td>  
  15.         <td> @Html.DisplayFor(modelItem => item.Designation) </td>  
  16.         <td> @Html.DisplayFor(modelItem => item.Salary) </td>  
  17.         <td> @Html.ActionLink("Details""Employee"new { id=item.ID }) </td>  
  18.     </tr> }  
  19. </table>  
Run your application,
 
 
Flow of Rotativa
 
Step 1 - Install Rotativa From Nuget Package
 
 
 
Step 2 - Rotativa Folder Creation 
 
After Installing Rotativa package from NuGet, the 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. You will able to see of two features available in the below screenshot such as Html to Image and Html to PDF
 
 
 
Rotativa Lifecycle as below for developers
 
Generate PDF
 
Now let's try to convert the employee List view to PDF. In the below code, I have created a "PrintAllEmployee" action and called the Rotativa Action method "actionasPdf" which is used to convert the action result as pdf. The Action method PrintAllEmployee() creates an instance of ActionAdPdf() class. The constructor of this class accepts a View Name as a string parameter. In this case, the Index view is passed to it. This class prints the HTML rendered output of the "Employees" view as a PDF document.
  1. /// <summary>  
  2. /// Print Employees details  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public ActionResult PrintAllEmployee()  
  6. {  
  7.    var report = new Rotativa.ActionAsPdf("Employees");  
  8.    return report;  
  9. }  
 Now call this "PrintAllEmployee" from our view
  1. <div style="text-align:right">@Html.ActionLink("Print Employees""PrintAllEmployee")</div>  
Now run your application,
 
 
 
In the above result, we can see that page has been converted as pdf. Now let's try to do this for a particular employee.
 
Now, write logic in the controller to get respective employee details. The Action method Employee() accepts an id parameter. This method searches an Employee based on its id and returns a view object showing an Employee information
  1. public ActionResult Employee(int id)  
  2. {  
  3.    var employee = LoadEmployees().Where(a => a.ID == id).FirstOrDefault();  
  4.    return View(employee);  
  5. }  
Create a view for this and load the same.
  1. @model GeneratePDF.Models.EmployeeModel  
  2. @{  
  3. ViewBag.Title = "Employee";  
  4. Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <h2>Employee Details</h2>  
  7. <br />  
  8. <table class="table table-bordered">  
  9.     <tr>  
  10.         <th> @Html.DisplayNameFor(model => model.Name) </th>  
  11.         <th> @Html.DisplayNameFor(model => model.Designation) </th>  
  12.         <th> @Html.DisplayNameFor(model => model.Salary) </th>  
  13.         <th></th>  
  14.     </tr>  
  15.     <tr>  
  16.         <td> @Html.DisplayFor(modelItem => Model.Name) </td>  
  17.         <td> @Html.DisplayFor(modelItem => Model.Designation) </td>  
  18.         <td> @Html.DisplayFor(modelItem => Model.Salary) </td>  
  19.         <td> @Html.ActionLink("Back To List""Employees") </td>  
  20. </table>  
Now let's write Rotativa logic to get selected employee details,
  1. /// <summary>  
  2. /// Print employee details  
  3. /// </summary>  
  4. /// <param name="id"></param>  
  5. /// <returns></returns>  
  6. public ActionResult PrintEmployee(int id)  
  7. {  
  8.    var report = new Rotativa.ActionAsPdf("Employee"new { id=id });  
  9.    return report;  
  10. }  
Now call this PrintEmployee from employee view and pass the employee id as input param
  1. <div style="text-align:right">@Html.ActionLink("Print Employee""PrintEmployee"new { id=Model.ID })</div>  
Now Run your application. In the below image, you can see that the employee detail is converted as a pdf document.
 
 
 
Generate Image 
 
As of now, we have seen how to generate pdf. Now let's convert the layout as an image using Rotativa. In the below code, you can see that I have used the "ActionAsImage" class to convert the respective employee details to the image.
  1. /// <summary>  
  2. /// employee details as image  
  3. /// </summary>  
  4. /// <param name="id"></param>  
  5. /// <returns></returns>  
  6. public ActionResult EmployeeImage(int id)  
  7. {  
  8.    var report = new Rotativa.ActionAsImage("Employee"new { id=id });  
  9.    return report;  
  10. }  
Now call this action by passing input parameter from view
  1. <div style="text-align:right">@Html.ActionLink("Convet to Image""EmployeeImage"new { id=Model.ID })</div>   
Run your application
 
 
 
Complete Controller 
  1. using GeneratePDF.Models;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Mvc;  
  5. namespace GeneratePDF.Controllers {  
  6.     public class GeneratePDFController: Controller {  
  7.         #region Grid Portion  
  8.         public ActionResult Employees() {  
  9.             return View(LoadEmployees());  
  10.         }  
  11.         public ActionResult Employee(int id) {  
  12.             var employee = LoadEmployees().Where(a => a.ID == id).FirstOrDefault();  
  13.             return View(employee);  
  14.         }  
  15.       #endregion  
  16.       #region Rotativa  
  17.         /// <summary>  
  18.         /// Print Employees details  
  19.         /// </summary>  
  20.         /// <returns></returns>  
  21.         public ActionResult PrintAllEmployee() {  
  22.             var report = new Rotativa.ActionAsPdf("Employees");  
  23.             return report;  
  24.         }  
  25.         /// <summary>  
  26.         /// Print employee details  
  27.         /// </summary>  
  28.         /// <param name="id"></param>  
  29.         /// <returns></returns>  
  30.         public ActionResult PrintEmployee(int id) {  
  31.             var report = new Rotativa.ActionAsPdf("Employee"new {  
  32.                 id = id  
  33.             });  
  34.             return report;  
  35.         }  
  36.         /// <summary>  
  37.         /// employee details as image  
  38.         /// </summary>  
  39.         /// <param name="id"></param>  
  40.         /// <returns></returns>  
  41.         public ActionResult EmployeeImage(int id) {  
  42.             var report = new Rotativa.ActionAsImage("Employee"new {  
  43.                 id = id  
  44.             });  
  45.             return report;  
  46.         }#endregion  
  47.         /// <summary>  
  48.         /// Load all Employees  
  49.         /// </summary>  
  50.         /// <returns></returns>  
  51.         private List < EmployeeModel > LoadEmployees() {  
  52.             List < EmployeeModel > employees = new List < EmployeeModel > () {  
  53.                 new EmployeeModel() {  
  54.                         ID = 1, Name = "Gnanavel Sekar", Designation = "Sr.Software Engineer", Salary = 1500000  
  55.                     },  
  56.                     new EmployeeModel() {  
  57.                         ID = 2, Name = "Subash S", Designation = "Sr.Software Engineer", Salary = 1700000  
  58.                     },  
  59.                     new EmployeeModel() {  
  60.                         ID = 3, Name = "Robert A", Designation = "Sr.Application Developer", Salary = 1800000  
  61.                     },  
  62.                     new EmployeeModel() {  
  63.                         ID = 4, Name = "Ammaiyappan", Designation = "Sr.Software Developer", Salary = 1200000  
  64.                     }  
  65.             };  
  66.             return employees;  
  67.         }  
  68.     }  
  69. }  
Employees.cshtml 
  1. @model IEnumerable<GeneratePDF.Models.EmployeeModel>  
  2. @{  
  3. ViewBag.Title = "Employees";  
  4. Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <br />  
  7. <div style="text-align:right">@Html.ActionLink("Print Employees""PrintAllEmployee")</div>  
  8. <br />  
  9. <table class="table table-bordered">  
  10.     <tr>  
  11.         <th> @Html.DisplayNameFor(model => model.Name) </th>  
  12.         <th> @Html.DisplayNameFor(model => model.Designation) </th>  
  13.         <th> @Html.DisplayNameFor(model => model.Salary) </th>  
  14.         <th></th>  
  15.     </tr> @foreach (var item in Model) { <tr>  
  16.         <td> @Html.DisplayFor(modelItem => item.Name) </td>  
  17.         <td> @Html.DisplayFor(modelItem => item.Designation) </td>  
  18.         <td> @Html.DisplayFor(modelItem => item.Salary) </td>  
  19.         <td> @Html.ActionLink("Details""Employee"new { id=item.ID }) </td>  
  20.     </tr> }  
  21. </table>  
Employee.cshtml 
  1. @model GeneratePDF.Models.EmployeeModel  
  2. @{  
  3. ViewBag.Title = "Employee";  
  4. Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <h2>Employee Details</h2>  
  7. <div style="text-align:right">@Html.ActionLink("Print Employee""PrintEmployee"new { id=Model.ID })</div>  
  8. <br />  
  9. <div style="text-align:right">@Html.ActionLink("Convet to Image""EmployeeImage"new { id=Model.ID })</div>  
  10. <br />  
  11. <table class="table table-bordered">  
  12.     <tr>  
  13.         <th> @Html.DisplayNameFor(model => model.Name) </th>  
  14.         <th> @Html.DisplayNameFor(model => model.Designation) </th>  
  15.         <th> @Html.DisplayNameFor(model => model.Salary) </th>  
  16.         <th></th>  
  17.     </tr>  
  18.     <tr>  
  19.         <td> @Html.DisplayFor(modelItem => Model.Name) </td>  
  20.         <td> @Html.DisplayFor(modelItem => Model.Designation) </td>  
  21.         <td> @Html.DisplayFor(modelItem => Model.Salary) </td>  
  22.         <td> @Html.ActionLink("Back To List""Employees") </td>  
  23. </table>  
Refer to the attached project for reference and I did attach the demonstrated project without a package and Rotativa exe due to the size limit. 
 
Summary 
 
The Rotativa package provides an extremely easy way to convert an HTML response directly into a PDF document, print the PDF document and generate the image in an ASP.NET MVC.
 
I hope you enjoyed this article. Your valuable feedback and comments about this article are always welcome.