In this article I will explain with an example, how to export WebGrid to PDF file in ASP.Net Core Razor Pages.
The WebGrid will be populated from database using Entity Framework and then the WebGrid will be sent as HTML string to the Controller which will be exported to PDF file in ASP.Net Core Razor Pages.
MVC6 Grid for ASP.Net Core
This article makes use of MVC6 Grid library for implementing WebGrid, as it is not available by default in .Net Core.
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.
using Microsoft.EntityFrameworkCore;
namespace Export_WebGrid_PDF_Razor_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Customer> Customers { get; set; }
}
}
Razor PageModel (Code-Behind)
The PageModel consists of following two Handler methods.
Handler method for handling GET operation
Inside this Handler method, the Top 10 records are fetched from the Customers table using Entity Framework and assigned to the public property Customers.
Handler method for handling the PDF file Export and Download operation
This Handler method is executed when the Export Button is clicked.
Note: The following Handler method performs File Download operation. Hence the return type is set to FileResult.
Inside the Handler method, the HTML string sent from the Razor Page is extracted from the GridHtml parameter.
Then, the HTML string is read and converted to a Byte Array using the GetBytes method of Encoding class 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 IndexModel : PageModel
{
private DBCtx Context { get; }
public IndexModel(DBCtx _context)
{
this.Context = _context;
}
public List<Customer> Customers { get; set; }
public void OnGet()
{
this.Customers = this.Context.Customers.Take(10).ToList();
}
public FileResult OnPostExport(string GridHtml)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.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");
}
}
}
Razor Page (HTML)
Inside the Razor Page, ASP.Net TagHelpers, NonFactors.Mvc.Grid namespace and mvc-grid.css file is inherited.
Displaying the Records
For displaying the records, MVC6 Grid is used.
The public property of Generic List object of the Customer Model class is accessed through PageModel inside the Razor Page and passed to the Grid function of the MVC6 Grid HTML Helper class.
In order to export MVC6 WebGrid with formatting, in-line CSS styles are applied to the MVC6 WebGrid and its Header and Data rows using jQuery.
Exporting WebGrid to PDF file
Below the MVC6 WebGrid, there is an HTML Form within which a Submit Button has been placed.
The Export Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostExport but here it will be specified as Export when calling from the Razor HTML Page.
Also, there is an HTML Hidden Field element which will be used to send the MVC6 WebGrid content to the PageModel.
When the Export Button is clicked, first the HTML of the MVC6 WebGrid is extracted and set into the Hidden Field element and finally, the Form is submitted.
@page
@model Export_WebGrid_PDF_Razor_Core.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using NonFactors.Mvc.Grid;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/css/mvc-grid/mvc-grid.css" rel="stylesheet" />
</head>
<body>
<h4>Customers</h4>
<hr />
<div id="Grid">
@(Html.Grid(Model.Customers).Build(columns =>
{
columns.Add(model => model.CustomerID).Titled("CustomerID");
columns.Add(model => model.ContactName).Titled("ContactName");
columns.Add(model => model.City).Titled("City");
columns.Add(model => model.Country).Titled("Country");
})
)
</div>
<br /><br />
<form method="post">
<input type="hidden" name="GridHtml" />
<input type="submit" id="btnSubmit" value="Export" asp-page-handler="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 () {
//Add CSS to the Table for formatting.
$("#Grid table").attr("cellpadding", "5");
$("#Grid table").css({ "border-collapse": "collapse", "border": "1px solid #ccc" });
$("#Grid th").css({ "background-color": "#B8DBFD", "border": "1px solid #ccc" });
$("#Grid td").css({ "width": "150px", "border": "1px solid #ccc" });
//Assign Click event to Button.
$("#btnSubmit").click(function () {
$("input[name='GridHtml']").val($("#Grid").html());
});
});
</script>
</body>
</html>
Screenshots
WebGrid
Exported PDF file
Downloads