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 -

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. ALTER DATABASE [DbPrintPDF] SET AUTO_CLOSE OFF
  29. GO
  30. ALTER DATABASE [DbPrintPDF] SET AUTO_CREATE_STATISTICS ON
  31. GO
  32. ALTER DATABASE [DbPrintPDF] SET AUTO_SHRINK OFF
  33. GO
  34. ALTER DATABASE [DbPrintPDF] SET AUTO_UPDATE_STATISTICS ON
  35. GO
  36. ALTER DATABASE [DbPrintPDF] SET CURSOR_CLOSE_ON_COMMIT OFF
  37. GO
  38. ALTER DATABASE [DbPrintPDF] SET CURSOR_DEFAULT GLOBAL
  39. GO
  40. ALTER DATABASE [DbPrintPDF] SET CONCAT_NULL_YIELDS_NULL OFF
  41. GO
  42. ALTER DATABASE [DbPrintPDF] SET NUMERIC_ROUNDABORT OFF
  43. GO
  44. ALTER DATABASE [DbPrintPDF] SET QUOTED_IDENTIFIER OFF
  45. GO
  46. ALTER DATABASE [DbPrintPDF] SET RECURSIVE_TRIGGERS OFF
  47. GO
  48. ALTER DATABASE [DbPrintPDF] SET DISABLE_BROKER
  49. GO
  50. ALTER DATABASE [DbPrintPDF] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
  51. GO
  52. ALTER DATABASE [DbPrintPDF] SET DATE_CORRELATION_OPTIMIZATION OFF
  53. GO
  54. ALTER DATABASE [DbPrintPDF] SET TRUSTWORTHY OFF
  55. GO
  56. ALTER DATABASE [DbPrintPDF] SET ALLOW_SNAPSHOT_ISOLATION OFF
  57. GO
  58. ALTER DATABASE [DbPrintPDF] SET PARAMETERIZATION SIMPLE
  59. GO
  60. ALTER DATABASE [DbPrintPDF] SET READ_COMMITTED_SNAPSHOT OFF
  61. GO
  62. ALTER DATABASE [DbPrintPDF] SET HONOR_BROKER_PRIORITY OFF
  63. GO
  64. ALTER DATABASE [DbPrintPDF] SET RECOVERY SIMPLE
  65. GO
  66. ALTER DATABASE [DbPrintPDF] SET MULTI_USER
  67. GO
  68. ALTER DATABASE [DbPrintPDF] SET PAGE_VERIFY CHECKSUM
  69. GO
  70. ALTER DATABASE [DbPrintPDF] SET DB_CHAINING OFF
  71. GO
  72. ALTER DATABASE [DbPrintPDF] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
  73. GO
  74. ALTER DATABASE [DbPrintPDF] SET TARGET_RECOVERY_TIME = 0 SECONDS
  75. GO
  76. ALTER DATABASE [DbPrintPDF] SET READ_WRITE
  77. 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 = ON) ON [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. namespace PrintViewPDF.Controllers
  8. {
  9. public class CustomerController : Controller
  10. {
  11. //DbPrintPDFEntities
  12. // GET: Customer
  13. public ActionResult Index()
  14. {
  15. using (DbPrintPDFEntities db = new DbPrintPDFEntities())
  16. {
  17. var customerList = db.Customers.ToList();
  18. return View(customerList);
  19. }
  20. }
  21. public ActionResult PrintViewToPdf()
  22. {
  23. var report = new ActionAsPdf("Index");
  24. return report;
  25. }
  26. public ActionResult PrintPartialViewToPdf(int id)
  27. {
  28. using (DbPrintPDFEntities db = new DbPrintPDFEntities())
  29. {
  30. Customer customer = db.Customers.FirstOrDefault(c => c.CustomerId == id);
  31. var report = new PartialViewAsPdf("~/Views/Shared/DetailCustomer.cshtml", customer);
  32. return report;
  33. }
  34. }
  35. }
  36. }

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

DetailCustomer.cshtml

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