Tuesday, July 4, 2017

Asp.net MVC : Export data to PDF file

In this article I am going to explain how to export data to PDF file in asp.net MVC. 
 Description:I have created table Employees and insert some dummy data into it. I want to export the data to PDF files. I am using itextsharp DLL to generate PDF file.
 Implementation: 
Model

  public partial class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> Phone { get; set; }
        public Nullable<int> Salary { get; set; }
        public string Department { get; set; }
        public string EmailId { get; set; }
    }
 Add Controller
Add controller to project.  Add iTextsharp namespaces. Create method to export the data to PDF.
Complete code of controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.Web.Helpers;
using System.IO;

namespace MVC_Project.Controllers
{
    public class ExportController : Controller
    {
        //
        // GET: /Export/
        DemoEntities1 db = new DemoEntities1();
        public ActionResult Index()
        {
            var emp = db.Employees.ToList();
            return View(emp);           
        }

        public ActionResult CreatePdf()
        {
            List<Employee> emp = new List<Employee>();
            emp = db.Employees.ToList();
            WebGrid grid = new WebGrid(source: emp, canPage: false, canSort: false);
            string gridHtml = grid.GetHtml(
                   columns: grid.Columns(
                            grid.Column("Id", "Id"),
                            grid.Column("Name", "Name"),
                            grid.Column("Phone", "Phone"),
                            grid.Column("Salary", "Salary"),
                            grid.Column("Department", "Department"),
                             grid.Column("EmailId", "Email")
                           )
                    ).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 File(output, "application/pdf","EmployeePDF.pdf");
            }
        }
    }
}


Add View
Add view for Index action. On button click call the CreatePDF method.
Complete code of view:

@{
    ViewBag.Title = "MVC : Export to PDF";
}

<style type="text/css">
    .webgrid {
        font-size: 1.2em;
        width: 80%;
        display: table;
        border-collapse: collapse;
    }

    .header {
        background-color: #3F95C5;
        color: #fff;
        padding-bottom: 4px;
        padding-top: 5px;
        text-align: center;
    }

        .header a {
            text-decoration: none;
            color: #fff;
        }

    td {
        text-align: center;
    }

    table img {
        width: 150px;
    }

    .row-style {
        background-color: #E6E6E6;
    }

        .row-style:hover {
            background-color: #C0C0C0;
        }

    .alternating-row {
        background-color: #DEEDF5;
    }

        .alternating-row:hover {
            background-color: #6EA0C3;
        }
    .btn {
        border: none;
        background: transparent;
    }

    .content {
        min-height: 550px;
    }
</style>
<h2>Export to PDF</h2>
<div class="content">
    <a href="@Url.Action("CreatePdf", "Export")">
        <img src="@Url.Content("~/images/pdf-button.png")" />
    </a>

    @{var grid = new WebGrid(Model, canPage: true, rowsPerPage: 50, ajaxUpdateContainerId: "gridContent");

    <div id="gridContent">
        @grid.GetHtml(
        tableStyle: "webgrid",
        headerStyle: "header",
        footerStyle: "footer",
        rowStyle: "row-style",
        alternatingRowStyle: "alternating-row",
    mode: WebGridPagerModes.All,
    columns: grid.Columns
    (
        grid.Column("Name", "Name"),
        grid.Column("Phone", "Phone"),
        grid.Column("Salary", "Salary"),
         grid.Column("Department", "Department"),
                //if else condition to check email id
             grid.Column("Email", format: (item) =>
             {
                 if (item.emailid == null)
                     return Html.Raw("Email not available");
                 else
                     return (item.EmailId);
             })
               )
                 )
    </div>
    }
</div>


No comments:

Post a Comment