How to Export Webgrid to PDF in MVC4 Application


In this post, I explain How to Export webgrid to PDF in asp.net MVC4 Application.
Before this article, I have explained How to export webgrid to excel in asp.net, which also will be helpful to you if you want to export your webgrid data to excel file.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-6: Add new action into your controller for data in webgrid.

Here I have added "Index" Action into "Webgrid" Controller. Please write this following code

             public ActionResult Index()
                List<CustomerInfo> allCust = new List<CustomerInfo>();
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                    allCust = dc.CustomerInfoes.ToList();
                return View(allCust);

Step-7: Add view for the Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
[N:B:Please Rebuild solution before add view.]
Complete View
            @model List<MVCExportWebgrid.CustomerInfo>
                ViewBag.Title = "Index";
                var grid = new WebGrid(source: Model, canPage: false);

            @* Here I will add some css for Looks webgrid better *@

            <style type="text/css">
                table.gridtable {
                 font-family: verdana,arial,sans-serif;
                 border-width: 1px;
                 border-color: #666666;
                 border-collapse: collapse;
                table.gridtable th {
                 border-width: 1px;
                 padding: 8px;
                 border-style: solid;
                 border-color: #666666;
                 background-color: #dedede;
                table.gridtable td {
                 border-width: 1px;
                 padding: 8px;
                 border-style: solid;
                 border-color: #666666;
                 background-color: #ffffff;

            <h2>Customer Info</h2>
                        grid.Column("CustomerID","Customer ID"),
                        grid.Column("CustomerName","Customer Name"),
                        grid.Column("City", "City"),
                        grid.Column("PostalCode","Postal Code")
                Export Data : @Html.ActionLink("Export to PDF","GETPdf","Webgrid")


Step-8: Add References itextsharp.dll & itextsharp.xmlworker.dll

Here I have added from NuGet.
Go to Solution Explorer > Right Click on References > Manage NuGet Packages...> Search with itextsharp text > Install this 2 dll

Step-9: Add another action into your controller for export webgrid in PDF format.

Here I have added "GETPdf" Action into "Webgrid" Controller. Please write this following code
import following...
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web.Helpers;
using System.Web.Mvc;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace MVCExportWebgrid.Controllers;
          public FileStreamResult GETPdf()
            List<CustomerInfo> all = new List<CustomerInfo>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
                all = dc.CustomerInfoes.ToList();

            WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);
            string gridHtml = grid.GetHtml(
                    columns: grid.Columns(
                            grid.Column("CustomerID", "Customer ID"),
                            grid.Column("CustomerName", "Customer Name"),
                            grid.Column("Address", "Address"),
                            grid.Column("City", "City"),
                            grid.Column("PostalCode", "Postal Code")

            string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", gridHtml);
            var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
            using (var input = new MemoryStream(bytes))
                var output = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
                var writer = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                output.Position = 0;
                return new FileStreamResult(output, "application/pdf");

Step-10: Run Application.

Related Post : 
  1. How to Export Webgrid to Excel in MVC4 Application.
  2. Part 1: How to display database data in webgrid in mvc 4
  3. Part 2: How to Dynamically set row background color in a webgrid depending on the content in MVC4.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.