Retrieve Database Table and Print PDF in ASP.NET MVC 5

In this article you will learn
  1. How to retrieve Database Table and Print as PDF in asp.net mvc?

In the previous article, I explained how can you convert and download any view page into PDF using Rotativa. In this article, I will explain how to print database output partial view as PDF.

Project Description

Here, I am creating a project and retrieving database table in view page. I will put a button to print each column detail as PDF. Here, I am using AdventureWorks database that is freely available to download for testing and learning purpose. You may use your own database or download AdventureWorks database from the Microsoft Site. Just google for it and you will see the download page.


1: Create a New Project.

Create a New MVC Project with any Name. Here, I am creating a new MVC Project PartialView_as_PDF_Example.

  1. Open Visual Studio 2015/2017/2019
  2. Go to File > New > Project
  3. Select Web in the left Pane and then select ASP.NET Web Application (.Net Framework) from the middle pane.

More Info: Create First ASP.NET MVC5 Project

2: Install Rotativa

Step 1: Click on Tools menu > NeGet Package Manager > Package Manager Console.
Note: You never install Rotativa v1.7.3 because it is not stable and gives you error. That's why I am suggesting you to install rotativa v1.7.4 using the following method.
Nuget Package Manager Console Rotativa
Step 2: Write or Paste following code and press Enter. Wait for the process finish installation.

Install-Package Rotativa -Version 1.7.4-rc

Installing Rotativa from Console

3: Add ADO.NET Entity Data Model

ADO.NET Entity Data Model Provides Dedicated and Easy way to implement Functionality for CRUD Operation. You don't need to write data logic as Entity Data Model automatically cares for most of the coding part.

Step 1: Right click on Project Name in Solution Explorer > Add > New Item. Select Data in Left Pane and then Select ADO.NET Entity Data Model. Rename it PrintPDF_DataModel.
Entity Data Model
Step 2: Select EF Designer from database template.
EF Designer
Step 3: click on New Connection button.

Step 4: Select Server name, database and click on Test Connection to check the connection between project and database. After that click on OK button.
Make Server Connection
Step 5: You can see that Entity Data Model created a connection string and connected database with your project.

Step 6: In this window, select Table which you want to work with. Here, I have selected Employee table only. Click on Finish button.
EDMX Design

4: Create a New EmployeeController.cs

Step 1: Go to Solution Explorer > Right Click on Controller > Add > Controller. Select MVC 5 Controller – Empty and give the name EmployeeController.
Add Controller Add Empty Controller EmployeeController
Step 2: Go to EmployeeController and Add the following code:

using System.Linq;
using System.Web.Mvc;
using Rotativa;

namespace PartialVew_as_PDF_Example.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        // Print the List of Employee Details
        public ActionResult Index()
        {
            using (AdventureWorks2017Entities db = new AdventureWorks2017Entities())
            {
                var employeeList = db.Employees.ToList();
                return View(employeeList);
            }                
        }

        //Convert Index Page as PDF
        public ActionResult PrintViewToPdf()
        {
            var report = new ActionAsPdf("Index");
            return report;
        }

        //Convert partial Page as PDF
        public ActionResult PrintPartialViewToPdf(int id)
        {
            using (AdventureWorks2017Entities db = new AdventureWorks2017Entities())
            {
                Employee employee = db.Employees.FirstOrDefault(e => e.BusinessEntityID == id);
                var report = new PartialViewAsPdf("~/Views/Shared/DetailEmployee.cshtml", employee);
                return report;
            }
        }

    }
}
Step 3: Press CTRL + SHIFT + B to build the project.

5: Adding View

Step 1: Add View: Right Click on Index() Action Method and select Add View. Select following details:
Add View
View name: Index
Template: List
Model class: Employee
Data context class: AdventureWorks2017Entities

Step 2: Your Index view will look like. I have removed unwanted column from the result and added some line of highlighted code.

@model IEnumerable<PartialVew_as_PDF_Example.Employee>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
    @Html.ActionLink("Convert View To PDF", "PrintViewToPdf")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.NationalIDNumber)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LoginID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.OrganizationLevel)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.JobTitle)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.BirthDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MaritalStatus)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>       
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.NationalIDNumber)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LoginID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.OrganizationLevel)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.JobTitle)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.BirthDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MaritalStatus)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>        
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.BusinessEntityID }) |
            @Html.ActionLink("Print Details View To PDF", "PrintPartialViewToPdf", new { id = item.BusinessEntityID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.BusinessEntityID })
        </td>
    </tr>
}

</table>
Step 3: Add DetailEmployee partial view. Go to Solution Explorer > Views > Shared. Right click on Shared > Add > View. Fill the following detail:
DetailEmployee Partial View
View Name: DetailEmployee
Template: Details
Model class: Employee
Data context class: AdventureWorks2017Entities

Select the checkbox Create as a partial view and then click on Add button.

6: Run your Project

Press F5 to run your project

. PDF Output

Summary

In this article, I have used database and table to show the result in table and convert them into PDF using Rotativa tool. This is very easy to convert any page into PDF using Rotativa.

 

Share your thought