Download Webgrid data in a pdf file with MVC5


In this article, I am explain How to Download Webgrid data in a pdf file.

In previous post I explained display data In webgrid and delete multiple rows by using checkboxes. Now i will explain how to download that data in a pdf file.

So first check previous post and add Action Link in list.cshtml for Create pdf.

webgrid in mvc

 Create PDF : @Html.ActionLink("Create PDF", "CreatePdf", "Home")

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

NuGet Manager


Now Add CreatePdf Action into Home Controller and also add following namespace.

using iTextSharp.text;

using iTextSharp.text.pdf;

using System.IO;

using System.Web.Helpers;

Now Add CreatePdf Action code .

public FileStreamResult CreatePdf()


            List all = new List();          

            all = db.Employees.ToList();            

            WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);

            string gridHtml = grid.GetHtml(

                    columns: grid.Columns(

                           grid.Column("Id", "EmployeeId"),

                           grid.Column("Name", "Employee Name"),

                           grid.Column("City", "City"),

                           grid.Column("MobileNo", "Mobile No")



            string exportData = String.Format("{0}{1}", "", 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");




Create Pdf in mvc

Click on Create PDF. and get PDF.

pdf in mvc

Post a Comment