Download Webgrid Data in a PDF file with MVC 5

In previous article 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 article and add Action Link in list.cshtml for Create PDF.
 
webgrid in mvc  
 
  1. 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


iTextSharp
Now Add CreatePdf Action into Home Controller and also add following namespace.
  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. using System.IO;  
  4. using System.Web.Helpers;  
Now Add CreatePdf Action code.
  1. public FileStreamResult CreatePdf()  
  2. {  
  3.     List all = new List();            
  4.     all = db.Employees.ToList();              
  5.     WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);  
  6.     string gridHtml = grid.GetHtml(  
  7.            columns: grid.Columns(  
  8.                     grid.Column("Id""EmployeeId"),  
  9.                     grid.Column("Name""Employee Name"),  
  10.                     grid.Column("City""City"),  
  11.                     grid.Column("MobileNo""Mobile No")  
  12.                    )  
  13.             ).ToString();  
  14.     string exportData = String.Format("{0}{1}""", gridHtml);  
  15.     var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);  
  16.     using (var input = new MemoryStream(bytes))  
  17.     {  
  18.         var output = new MemoryStream();  
  19.         var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);  
  20.         var writer = PdfWriter.GetInstance(document, output);  
  21.         writer.CloseStream = false;  
  22.         document.Open();  
  23.         var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();  
  24.         xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);  
  25.         document.Close();  
  26.         output.Position = 0;  
  27.         return new FileStreamResult(output, "application/pdf");  
  28.     }  
  29. }  
RUN APPLICATION(CTTL + F5).
Create Pdf in mvc
Click on Create PDF. and get PDF.

pdf in mvc
 
 
 
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now