Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

Export to PDF from WebGrid in MVC5 with Razor view and entity framework 6

Posted By: Ajay Saptaputre, 17 Oct,2015  |  Total View : 5431

In my previous article I discussed about create CRUD operation using Scaffolding with ASP.NET MVC 5 and database first approach using ASP.NET MVC 5 and Entity Framework 6 and WebGrid in MVC 5 with Razor view and Entity Framework 6

In this article I am going to discuss export data from WebGrid to PDF file. If you are new to WebGrid, please refer my previous article WebGrid in MVC 5 with Razor view and Entity Framework 6 to know more about WebGrid. In this article I will cover all the necessary steps to build ASP.NET MVC 5 application with export to PDF functionality.

In order to start our sample application we will need database table, entity and DBContect classes to fetch the data from database. In this article I am not covering steps those are already covered in my previous article. If you did not read, please refer database first approach using ASP.NET MVC 5 and Entity Framework 6 and follow Step 1 to Step 16 it will help you to understand this article.

Step 1: Before going to start, we will need to add "iTextSharp" and "iTextSharp XML Worker" packages that will help us to export WebGrid data to PDF file. All right, right click on project or go to "Tool" menu and select "Library Package Manager" and then select "Manage NuGet Package for Solution..." option.


Step 2: Now, search for "iTextSharp" and select "iTextSharp" from list and clicks on "Install" button. See below screen shot:


Step 3: Now, search again for "iTextSharp XML Worker" and select "iTextSharp XML Worker" from list and clicks on "Install" buton. See below screen shot:


Step 4: Once installed click on close button. This will installed all the required assembly references in your project.

Step 5: All right, now select MVC 5 empty controller, rename controller name as "EmployeeController". Click on "Add" button.


Step 6: Now add below code to controller's "Index" method. The "Index" method will send list of "Employees" object to view. I have already discussed about WebGrid creation please refer my previous article WebGrid in MVC 5 with Razor view and Entity Framework 6.

EmployeeDBContext db = new EmployeeDBContext();
 return View(db.Employees.ToList());		

Step 7: In ordre to use "iTextSharp" object, you need to add reference in EmployeeController.cs file.

using iTextSharp.text;
using iTextSharp.text.pdf;

Step 8: Now, Add another method called "ExportData" in controller. This method will provide response when user clicks on "Export to PDF" link. In this method I am creating WebGrid object and setting all the necessary columns using "GetHtml" method of WebGrid. Now create "Document" by making use of "iTextSharp" object and then create "PdfWriter" from "Document". Finally, creating instance of "XMLWorkerHelper" object and returning "FileStreamResult" as a result. See below code snippet:

public void ExportData()
{
EmployeeDBContext db = new EmployeeDBContext();
	List employees = new List();
	employees = db.Employees.ToList();

	WebGrid webGrid = new WebGrid(employees, canPage: true, rowsPerPage: 10);
	string gridData = webGrid.GetHtml(
		columns: webGrid.Columns(
		webGrid.Column(columnName: "Name", header: "Name"),
		webGrid.Column(columnName: "Designation", header: "Designation"),
		webGrid.Column(columnName: "Gender", header: "Gender"),
		webGrid.Column(columnName: "Salary", header: "Salary"),
		webGrid.Column(columnName: "City", header: "City"),
		webGrid.Column(columnName: "State", header: "State"),
		webGrid.Column(columnName: "Zip", header: "Zip")
	)).ToString();
			
	StringBuilder pdfExportData = new StringBuilder();
	pdfExportData.AppendLine("<html><head><style>.webgrid-table 
	{font-family: Arial,Helvetica,sans-serif;font-size: 14px;font-weight: normal;width: 650px;display: 
	table;border-collapse: collapse;border: solid px #C5C5C5;background-color: white;}</style>");
	pdfExportData.AppendLine("</head><body>" + gridData + "</body></html>");

	var bytes  = System.Text.Encoding.UTF8.GetBytes(pdfExportData.ToString());
	using(var stream = new MemoryStream(bytes))
	{
		var outStream = new MemoryStream();
		var doc= new iTextSharp.text.Document(PageSize.A4,50,50,50,50);
		var writer = PdfWriter.GetInstance(doc,outStream);
		writer.CloseStream = false;
		doc.Open();

		var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
		xmlWorker.ParseXHtml(writer,doc,stream,System.Text.Encoding.UTF8);
		doc.Close();
		outStream.Position = 0;
		return new FileStreamResult(outStream,"application/pdf");
	}
}
Step 9: Now right click on "Index" action method, select "Add View" and select "Empty" template from dropdown. To build view we will need to specify model class as "Employee" and data context class as "EmployeeDBContext" as below screen shot illustrate. Click "Add" button. This will add IEnumerable Employee object in view page as below.


Step 10: In order to apply custom theme or CSS style to WebGrid, you need to create css classes first and set respective properties of the WebGrid. See below code snippet:

<style type="text/css">
        .webgrid-table {
        font-family: Arial,Helvetica,sans-serif;
        font-size: 14px;
        font-weight: normal;
        width: 650px;
        display: table;
        border-collapse: collapse;
        border: solid px #C5C5C5;
        background-color: white;
    }

        .webgrid-table td, th {
            border: 1px solid #C5C5C5;
            padding: 3px 7px 2px;
        }

    .webgrid-header, .webgrid-header a {
        background-color: #0094ff;
        color:#ffffff;
        text-align: left;
        text-decoration: none;
    }

    .webgrid-footer {
    }

    .webgrid-row-style {
        padding: 3px 7px 2px;
    }

    .webgrid-alternating-row {
        background-color:azure;
        padding: 3px 7px 2px;
    }

    .col1Width {
        width: 55px;
    }

    .col2Width {
        width: 220px;
    }
</style>

Step 11: All right, now add below code to "Index" page to display data using WebGrid. See below code snippet:

@{
    ViewBag.Title = "Index";
    var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 10);
    grid.Pager(WebGridPagerModes.All);
}

<div id="gridContent" style="font-family: Arial; padding: 20px;">
    @grid.GetHtml(tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    columns: grid.Columns(
                grid.Column(columnName: "Name", header: "Name"),
                grid.Column(columnName: "Designation", header: "Designation"),
                grid.Column(columnName: "Gender", header: "Gender"),
                grid.Column(columnName: "Salary", header: "Salary"),
                grid.Column(columnName: "City", header: "City"),
                grid.Column(columnName: "State", header: "State"),
                grid.Column(columnName: "Zip", header: "Zip")

    ))
</div>

Step 12: Now add below code that will add "Export to PDF" link. Notice that I am passing "ExportData" action method to Html helper "ActionLink" method as action that will execute when user clicks on link. See below code snippet:

 Export to PDF : @Html.ActionLink("Export to PDF", "ExportData", "Employee")

Step 13: All right, our sample ASP.NET MVC 5 export to PDF application is ready to fly. Run the application and click on "Export to PDF" link. This will start downloading PDF file.



Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

Download Code ⇩