ASP.NET MVC - Export PDF Document From View Page

Introduction

In this article, we will learn how we can export view page to PDF using Rotativa framework.

Rotativa is an open source framework created by Giorgio Bazio in order to export view page to PDF. This framework is based on wkhtmltoPDF tool which is used to generate PDF from HTML view page.

To build our application, we are using ASP.NET MVC 5. I hope it will be helpful for you.

Prerequisites

Make sure you have installed Visual Studio 2017 (.NET Framework 4.6.1) and SQL Server.

In this post, we are going to -

  • Create Database.
  • Create MVC application.
  • Configuring Entity framework ORM to connect to the database.
  • Installing Rotativa.
  • Create Customer controller.
  • Create HTML page for demo.         

SQL Database part

Here, you find the scripts to create a database and its table.

Create Database

  1. USE [master]  
  2. GO  
  3. /****** Object:  Database [DbPrintPDF]    Script Date: 1/30/2018 8:56:29 PM ******/  
  4. CREATE DATABASE [DbPrintPDF]  
  5.  CONTAINMENT = NONE  
  6.  ON  PRIMARY   
  7. NAME = N'DbPrintPDF', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbPrintPDF.mdf' , SIZE = 4096KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  8.  LOG ON   
  9. NAME = N'DbPrintPDF_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbPrintPDF_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  10. GO  
  11. ALTER DATABASE [DbPrintPDF] SET COMPATIBILITY_LEVEL = 110  
  12. GO  
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  14. begin  
  15. EXEC [DbPrintPDF].[dbo].[sp_fulltext_database] @action = 'enable'  
  16. end  
  17. GO  
  18. ALTER DATABASE [DbPrintPDF] SET ANSI_NULL_DEFAULT OFF   
  19. GO  
  20. ALTER DATABASE [DbPrintPDF] SET ANSI_NULLS OFF   
  21. GO  
  22. ALTER DATABASE [DbPrintPDF] SET ANSI_PADDING OFF   
  23. GO  
  24. ALTER DATABASE [DbPrintPDF] SET ANSI_WARNINGS OFF   
  25. GO  
  26. ALTER DATABASE [DbPrintPDF] SET ARITHABORT OFF   
  27. GO  
  28.   
  29. ALTER DATABASE [DbPrintPDF] SET AUTO_CLOSE OFF   
  30. GO  
  31. ALTER DATABASE [DbPrintPDF] SET AUTO_CREATE_STATISTICS ON   
  32. GO  
  33. ALTER DATABASE [DbPrintPDF] SET AUTO_SHRINK OFF   
  34. GO  
  35. ALTER DATABASE [DbPrintPDF] SET AUTO_UPDATE_STATISTICS ON   
  36. GO  
  37. ALTER DATABASE [DbPrintPDF] SET CURSOR_CLOSE_ON_COMMIT OFF   
  38. GO  
  39. ALTER DATABASE [DbPrintPDF] SET CURSOR_DEFAULT  GLOBAL   
  40. GO  
  41. ALTER DATABASE [DbPrintPDF] SET CONCAT_NULL_YIELDS_NULL OFF   
  42. GO  
  43. ALTER DATABASE [DbPrintPDF] SET NUMERIC_ROUNDABORT OFF   
  44. GO  
  45. ALTER DATABASE [DbPrintPDF] SET QUOTED_IDENTIFIER OFF   
  46. GO  
  47. ALTER DATABASE [DbPrintPDF] SET RECURSIVE_TRIGGERS OFF   
  48. GO  
  49. ALTER DATABASE [DbPrintPDF] SET  DISABLE_BROKER   
  50. GO  
  51. ALTER DATABASE [DbPrintPDF] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  52. GO  
  53. ALTER DATABASE [DbPrintPDF] SET DATE_CORRELATION_OPTIMIZATION OFF   
  54. GO  
  55. ALTER DATABASE [DbPrintPDF] SET TRUSTWORTHY OFF   
  56. GO  
  57. ALTER DATABASE [DbPrintPDF] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  58. GO  
  59. ALTER DATABASE [DbPrintPDF] SET PARAMETERIZATION SIMPLE   
  60. GO  
  61. ALTER DATABASE [DbPrintPDF] SET READ_COMMITTED_SNAPSHOT OFF   
  62. GO  
  63. ALTER DATABASE [DbPrintPDF] SET HONOR_BROKER_PRIORITY OFF   
  64. GO  
  65. ALTER DATABASE [DbPrintPDF] SET RECOVERY SIMPLE   
  66. GO  
  67. ALTER DATABASE [DbPrintPDF] SET  MULTI_USER   
  68. GO  
  69. ALTER DATABASE [DbPrintPDF] SET PAGE_VERIFY CHECKSUM    
  70. GO  
  71. ALTER DATABASE [DbPrintPDF] SET DB_CHAINING OFF   
  72. GO  
  73. ALTER DATABASE [DbPrintPDF] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  74. GO  
  75. ALTER DATABASE [DbPrintPDF] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  76. GO  
  77. ALTER DATABASE [DbPrintPDF] SET  READ_WRITE   
  78. GO  

Create Table

After creating the database, we will move to create the customers table.

Customers Table

  1. USE [DbPrintPDF]  
  2. GO  
  3. /****** Object:  Table [dbo].[Customers]    Script Date: 1/30/2018 8:56:59 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. CREATE TABLE [dbo].[Customers](  
  11. [CustomerId] [int] IDENTITY(1,1) NOT NULL,  
  12. [CustomerName] [varchar](50) NULL,  
  13. [CustomerEmail] [varchar](50) NULL,  
  14. [CustomerPhone] [varchar](50) NULL,  
  15. [CustomerCountry] [varchar](50) NULL,  
  16.  CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED   
  17. (  
  18. [CustomerId] ASC  
  19. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  20. ON [PRIMARY]  
  21. GO  
  22. SET ANSI_PADDING OFF  
  23. GO  

Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

ASP.NET

Next, a new dialog will pop up for selecting the template. We are going to choose MVC template and click OK.

ASP.NET

Once our project is created, we will add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

In Solution Explorer, right-click on the project name, click Add >> Add New Item.

A dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model, and enter the name for your DbContext model as PrintPDFDB, then click Add.

ASP.NET

As you can see, we have 4 model contents. We are selecting the first approach (EF Designer from database).

ASP.NET

Next step, we need to select the server name, then via drop down list, connect to a database section. You must choose your database name and finally click OK.

ASP.NET

After that, the dialog Entity Data Model Wizard will pop up for choosing the objects which will be used in our application. We are selecting the customers table then click Finish.

Finally, we see that EDMX model generates customers table as object, as shown below.

ASP.NET

ASP.NET

Install Rotativa

In Solution Explorer, right-click on References >> Manage NuGet Packages.

Now, in search input, type Rotativa, select the first line as shown below, and then click "Install".

ASP.NET

After installing Rotativa successfully, notice that Rotaiva folder has been added in Solution Explorer.

ASP.NET

Create a controller

Now, we are going to create a Controller. Right-click on the Controllers folder> > Add >> Controller>> selecting MVC 5 Controller – Empty >> click Add. In the next dialog, name the controller as CustomerController and then click Add.

ASP.NET

ASP.NET

CustomerController.cs

  1. using Rotativa;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace PrintViewPDF.Controllers  
  9. {  
  10.     public class CustomerController : Controller  
  11.     {  
  12.         //DbPrintPDFEntities  
  13.         // GET: Customer  
  14.         public ActionResult Index()  
  15.         {  
  16.             using (DbPrintPDFEntities db = new DbPrintPDFEntities())  
  17.             {  
  18.                 var customerList = db.Customers.ToList();  
  19.   
  20.                 return View(customerList);  
  21.             }  
  22.         }  
  23.   
  24.         public ActionResult PrintViewToPdf()  
  25.         {  
  26.             var report = new ActionAsPdf("Index");  
  27.             return report;  
  28.         }  
  29.   
  30.   
  31.   
  32.         public ActionResult PrintPartialViewToPdf(int id)  
  33.         {  
  34.             using (DbPrintPDFEntities db = new DbPrintPDFEntities())  
  35.             {  
  36.                 Customer customer = db.Customers.FirstOrDefault(c => c.CustomerId == id);  
  37.   
  38.                 var report = new PartialViewAsPdf("~/Views/Shared/DetailCustomer.cshtml", customer);  
  39.                 return report;  
  40.             }  
  41.              
  42.         }  
  43.     }  
  44. }  

Now, let’s explain all the actions implemented within customer controller

  1. Index action is used to get customers list from database.
  2. PrintViewToPdf action is responsible to convert index action to PDF document. Note here, we have used ActionAsPdf class that accepts a string parameter. This string parameter represents action that we would convert to PDF.
  3. Finally, we have added PrintPartialViewToPdf which is responsible to convert DetailCustomer.cshtml partial view to PDF document by using PartialViewAsPdf class that accepts as parameters partial view name and an object which contains data to display within a partial view.

Adding Views

Right click on Index action >> Add view.

Then, add view dialog will be shown as below. Name your view as you like, and select List as template, finally click Add.

ASP.NET

Index.cshtml

  1. @model IEnumerable<PrintViewPDF.Customer>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Customer List</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Convert View To PDF""PrintViewToPdf")  
  11. </p>  
  12. <table class="table">  
  13.     <tr>  
  14.         <th>  
  15.             @Html.DisplayNameFor(model => model.CustomerName)  
  16.         </th>  
  17.         <th>  
  18.             @Html.DisplayNameFor(model => model.CustomerEmail)  
  19.         </th>  
  20.         <th>  
  21.             @Html.DisplayNameFor(model => model.CustomerPhone)  
  22.         </th>  
  23.         <th>  
  24.             @Html.DisplayNameFor(model => model.CustomerCountry)  
  25.         </th>  
  26.         <th></th>  
  27.     </tr>  
  28.   
  29. @foreach (var item in Model) {  
  30.     <tr>  
  31.         <td>  
  32.             @Html.DisplayFor(modelItem => item.CustomerName)  
  33.         </td>  
  34.         <td>  
  35.             @Html.DisplayFor(modelItem => item.CustomerEmail)  
  36.         </td>  
  37.         <td>  
  38.             @Html.DisplayFor(modelItem => item.CustomerPhone)  
  39.         </td>  
  40.         <td>  
  41.             @Html.DisplayFor(modelItem => item.CustomerCountry)  
  42.         </td>  
  43.         <td>  
  44.             @Html.ActionLink("Edit""Edit"new { id=item.CustomerId }) |  
  45.             @Html.ActionLink("Print Details View To PDF""PrintPartialViewToPdf"new { id=item.CustomerId }) |  
  46.             @Html.ActionLink("Delete""Delete"new { id=item.CustomerId })  
  47.         </td>  
  48.     </tr>  
  49. }  
  50.   
  51. </table>  

DetailCustomer.cshtml

  1. @model PrintViewPDF.Customer  
  2.   
  3. <div>  
  4.     <h4>Customer</h4>  
  5.     <hr />  
  6.     <dl class="dl-horizontal">  
  7.         <dt>  
  8.             @Html.DisplayNameFor(model => model.CustomerName)  
  9.         </dt>  
  10.   
  11.         <dd>  
  12.             @Html.DisplayFor(model => model.CustomerName)  
  13.         </dd>  
  14.   
  15.         <dt>  
  16.             @Html.DisplayNameFor(model => model.CustomerEmail)  
  17.         </dt>  
  18.   
  19.         <dd>  
  20.             @Html.DisplayFor(model => model.CustomerEmail)  
  21.         </dd>  
  22.   
  23.         <dt>  
  24.             @Html.DisplayNameFor(model => model.CustomerPhone)  
  25.         </dt>  
  26.   
  27.         <dd>  
  28.             @Html.DisplayFor(model => model.CustomerPhone)  
  29.         </dd>  
  30.   
  31.         <dt>  
  32.             @Html.DisplayNameFor(model => model.CustomerCountry)  
  33.         </dt>  
  34.   
  35.         <dd>  
  36.             @Html.DisplayFor(model => model.CustomerCountry)  
  37.         </dd>  
  38.   
  39.     </dl>  
  40. </div>  

Output

Now, our application is ready. We can run and see the output in the browser.

ASP.NET
When we click on Convert View To PDF link, we will convert index view to PDF as shown below.

ASP.NET

When we click on Print Details View To PDF link, we will convert DetailCustomer  partial view to PDF.

ASP.NET

That’s all. Please send your feedback and queries in comments box. 


Similar Articles