In this article I will explain with an example, how to export data from database to PDF file in ASP.Net MVC Razor.
The data from the database is fetched using Entity Framework and dynamic HTML string is generated using StringBuilder class.
Finally, the generated HTML string will be exported to PDF file using iTextSharp XMLWorkerHelper library in ASP.Net MVC Razor.
 
 
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.
ASP.Net MVC: Export data from Database to PDF File
 
2. Now you will need to look for iTextSharp XMLWorker package and once found, you need to click the Install Button.
ASP.Net MVC: Export data from Database to PDF File
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
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.
 
ASP.Net MVC: Export data from Database to PDF File
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
 
 
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 records from the Customers Table are fetched using Entity Framework and returned to the View.
 
Action method for handling the PDF File Export and Download operation
This Action method is executed when the Export button is clicked.
Note: The following Action method performs File Download and hence the return type is set to FileResult. For more details on FileResult, please refer my article FileResult return type in ASP.Net MVC.
 
Inside this Action Method, the Top 10 Customer records are fetched from the Customers Table using Entity Framework and then using the StringBuilder class, a string consisting of an HTML Table is generated.
Then, the HTML string 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);
    }
 
    [HttpPost]
    public FileResult Export()
    {
        NorthwindEntities entities = new NorthwindEntities();
        List<object> customers = (from customer in entities.Customers.ToList().Take(10)
                                  select new[] {
                                      customer.CustomerID,
                                      customer.ContactName,
                                      customer.City,
                                      customer.Country
                                 }).ToList<object>();
 
        //Building an HTML string.
        StringBuilder sb = new StringBuilder();
 
        //Table start.
        sb.Append("<table border='1' cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-family: Arial;'>");
 
        //Building the Header row.
        sb.Append("<tr>");
        sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>CustomerID</th>");
        sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>ContactName</th>");
        sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>City</th>");
        sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>Country</th>");
        sb.Append("</tr>");
 
        //Building the Data rows.
        for (int i = 0; i < customers.Count; i++)
        {
            string[] customer = (string[])customers[i];
            sb.Append("<tr>");
            for (int j = 0; j < customer.Length; j++)
            {
                //Append data.
                sb.Append("<td style='border: 1px solid #ccc'>");
                sb.Append(customer[j]);
                sb.Append("</td>");
            }
            sb.Append("</tr>");
        }
 
        //Table end.
        sb.Append("</table>");
 
        using (MemoryStream stream = new MemoryStream())
        {
            StringReader sr = new StringReader(sb.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            return File(stream.ToArray(), "application/pdf", "Grid.pdf");
        }
    }
}
 
 
View
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.
Displaying the records
For displaying the records, an HTML Table is used.
A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
 
Exporting database data to PDF File
Below the HTML Table, there is an HTML Submit button enclosed inside a Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Export.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
When the Export button is clicked, the Form is submitted.
@model IEnumerable<Export_Data_Database_PDF_MVC.Customer>
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h4>Customers</h4>
    <hr />
    <div id="Grid">
        <table cellpadding="5" cellspacing="0" style="border: 1px solid #ccc;">
            <tr>
                <th style="background-color: #B8DBFD;border: 1px solid #ccc">CustomerID</th>
                <th style="background-color: #B8DBFD;border: 1px solid #ccc">ContactName</th>
                <th style="background-color: #B8DBFD;border: 1px solid #ccc">City</th>
                <th style="background-color: #B8DBFD;border: 1px solid #ccc">Country</th>
            </tr>
            @foreach (Customer customer in Model)
            {
                <tr>
                    <td style="border: 1px solid #ccc">@customer.CustomerID</td>
                    <td style="border: 1px solid #ccc">@customer.ContactName</td>
                    <td style="border: 1px solid #ccc">@customer.City</td>
                    <td style="border: 1px solid #ccc">@customer.Country</td>
                </tr>
            }
        </table>
    </div>
    <br /><br />
    @using (Html.BeginForm("Export", "Home", FormMethod.Post))
    {
        <input type="submit" id="btnSubmit" value="Export" />
    }
</body>
</html>
 
 
Screenshots
HTML Table
ASP.Net MVC: Export data from Database to PDF File
 
Exported PDF File
ASP.Net MVC: Export data from Database to PDF File
 
 
Downloads