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.
- 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.
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")
- )
- ).ToString();
- 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;
- document.Open();
- var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
- xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
- document.Close();
- output.Position = 0;
- return new FileStreamResult(output, "application/pdf");
- }
- }
RUN APPLICATION(CTTL + F5).
Click on Create PDF. and get PDF.