In this article I will explain with an example, how to export WebGrid to PDF file with formatting using iTextSharp in ASP.Net MVC Razor.
First the WebGrid will be populated from database using Entity Framework and then the generated HTML Table of WebGrid will be sent as HTML string to the Controller which ultimately will be exported to PDF file in ASP.Net MVC Razor.
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Installing and adding reference of iTextSharp XMLWorkerHelper Library
In order to install and add reference of ITextSharp XMLWorkerHelper library, you will need to:-
1. Right Click the Project in Solution Explorer and click Manage NuGet Packages from the Context Menu.
Export WebGrid with Formatting to PDF file in ASP.Net MVC
2. Now you will need to look for iTextSharp XMLWorker package and once found, you need to click the Install Button.
Export WebGrid with Formatting to PDF file in ASP.Net MVC
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
Export WebGrid with Formatting to PDF file in ASP.Net MVC
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 Customer records are fetched and returned to the View.
Action method for handling the PDF File Export and Download operation
This Action method is executed when the Export Submit button is clicked.
Note: The following Action method performs File Download and hence the return type is set to FileResult.
The HTML of the WebGrid sent from the View is extracted from the GridHtml parameter.
Note: By default posting of HTML content via input fields is disabled. For more details on enabling it, please refer What is ValidateInput(false) attribute, its Uses and Examples in ASP.Net MVC.
The HTML is read using an object of StringReader class which is then supplied to the ParseXHtml method of the XMLWorkerHelper class object which converts it to PDF document and saves to the MemoryStream class object.
Finally the MemoryStream class object is converted to Byte Array and exported and downloaded as PDF file using the File function.
public class HomeController : Controller
    // GET: Home
    public ActionResult Index()
        NorthwindEntities entities = new NorthwindEntities();
        return View(from customer in entities.Customers.Take(10)
                    select customer);
    public FileResult Export(string GridHtml)
        using (MemoryStream stream = new System.IO.MemoryStream())
            StringReader sr = new StringReader(GridHtml);
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            return File(stream.ToArray(), "application/pdf", "Grid.pdf");
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that the Model will be available as a Collection.
For displaying the records, the WebGrid is rendered using GetHtml function which renders the WebGrid  using Model.
Note: For more details on using WebGrid, please refer WebGrid Step By Step Tutorial with example in ASP.Net MVC.
The WebGrid will render as an HTML Grid (Table) consisting of the records from the Customers Table.
In order to export WebGrid with formatting, in-line CSS styles are applied to the WebGrid and its Header and Data rows using jQuery.
There is an HTML Hidden Field element which is used to send the HTML of the WebGrid's HTML content to the Controller’s Action method.
Finally there’s an HTML Submit button enclosed inside a Form with the Action method specified as Export.
When this Button will be clicked, first the HTML of the WebGrid's HTML is extracted and set into the Hidden Field element and finally the Form is submitted.
@model IEnumerable<Customer>
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canSort: false, canPage: false);
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    <div id="Grid">
        htmlAttributes: new { @id = "WebGrid" },
        columns: webGrid.Columns(
                 webGrid.Column("CustomerID", "Customer Id"),
                 webGrid.Column("ContactName", "Customer Name"),
                 webGrid.Column("City", "City"),
                 webGrid.Column("Country", "Country")))
    @using (Html.BeginForm("Export", "Home", FormMethod.Post))
        <input type="hidden" name="GridHtml"/>
        <input type="submit" id="btnSubmit" value="Export"/>
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        $(function () {
            //Add CSS to the Table for formatting.
            $("#Grid table").attr("cellpadding", "5");
            $("#Grid table").css({ "border-collapse": "collapse", "border": "1px solid #ccc" });
            $("#Grid th").css({ "background-color": "#B8DBFD", "border": "1px solid #ccc" });
            $("#Grid td").css({ "width": "150px", "border": "1px solid #ccc" });
            //Assign Click event to Button.
            $("#btnSubmit").click(function () {
Export WebGrid with Formatting to PDF file in ASP.Net MVC
Exported PDF File
Export WebGrid with Formatting to PDF file in ASP.Net MVC