In this article I will explain with an example, how to export HTML string to PDF file in ASP.Net Core MVC.
The data from database will be populated in HTML Table using Entity Framework in ASP.Net Core MVC.
Finally, the HTML Table will be exported and downloaded as PDF file using itext7.pdfhtml library in ASP.Net Core MVC.
 
 
Installing itext7.pdfhtml Library
In order to install itext7.pdfhtml library, use the following command in Nuget Package Manager Console window.
Install-Package itext7.pdfhtml -Version 4.0.4
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Namespaces
You need to import the following namespaces.
using System.IO;
using System.Text;
using iText.Html2pdf;
using iText.IO.Source;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
 
 
Model
The Model class consists of the following four properties.
public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}
 
 
Database Context
Once the Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
Note: For beginners in ASP.Net Core and Entity Framework, please refer my article ASP.Net Core: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework with ASP.Net Core.
  
using Microsoft.EntityFrameworkCore;
 
namespace Export_Grid_PDF_MVC_Core
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
           
        }
       
        public DbSet<Customer> Customers { get; set; }
    }
}
 
 
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, the Top 10 records are fetched from the Customers table 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 operation. Hence the return type is set to FileResult. For more details on FileResult, please refer my article FileResult return type in ASP.Net Core MVC.
 
The HTML string sent from the View is extracted from the GridHtml parameter.
Then, the HTML string is read and saved to the MemoryStream class object.
Next, the ByteArrayOutputStream class object is created and passed to the PdfWriter class object and the PdfDocument is initialized using the PdfWriter class object.
Then, the ConvertToPdf method of HtmlConverter class object is used to convert it to PDF document by passing the MemoryStream and PdfDocument object.
Finally, the ByteArrayOutputStream class object is converted to Byte Array and exported and downloaded as PDF file using the File function.
public class HomeController : Controller
{
    private DBCtx Context { get; }
 
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public IActionResult Index()
    {
        return View(this.Context.Customers.Take(10).ToList());
    }
 
    [HttpPost]
    public FileResult Export(string GridHtml)
    {
        using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(GridHtml)))
        {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PdfWriter writer = new PdfWriter(byteArrayOutputStream);
            PdfDocument pdfDocument = new PdfDocument(writer);
            pdfDocument.SetDefaultPageSize(PageSize.A4);
            HtmlConverter.ConvertToPdf(stream, pdfDocument);
            pdfDocument.Close();
            return File(byteArrayOutputStream.ToArray(), "application/pdf", "Grid.pdf");
        }
    }
}
 
 
View
Inside the View, in the very first line the Customer Model is declared as IEnumerable which specifies that it 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 the HTML Table to PDF File
Below the HTML Table, there is an HTML Submit button enclosed inside a Form which has been created with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Export.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Also, there is an HTML Hidden Field element which will be used to send the HTML content of the Table to the Controller’s Action method.
When the Submit button is clicked, first the HTML is extracted and set into the Hidden Field element and finally the Form is submitted.
@model IEnumerable<Export_Grid_PDF_MVC_Core.Models.Customer>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
 
@{
    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; font-family: Arial; font-size: 10pt;">
            <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 (var 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 />
    <form method="post" asp-action="Export" asp-controller="Home">
        <input type="hidden" name="GridHtml" />
        <input type="submit" id="btnSubmit" value="Export" />
    </form>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnSubmit").click(function () {
                $("input[name='GridHtml']").val($("#Grid").html());
            });
        });
    </script>
</body>
</html>
 
 
Screenshots
HTML Table
ASP.Net Core MVC: Export HTML string to PDF File
 
Exported PDF File
ASP.Net Core MVC: Export HTML string to PDF File
 
 
Downloads