While working in ASP.NET Core Web-application, you may want to convert Razor View or HTML to PDF using C# .NET Core, so in this article, I have mentioned how you can convert ASP.NET Core Razor View into PDF using jsreport open-source and free NuGet package.
Step 1: Create a new project in Visual Studio 2022/2019, I am using VS 2022, so we can create new project by opening VS 2022 and then selecting "Create new project" -> Select "ASP.NET Core (Model-View-Controller) MVC" template -> then select ".NET Core 6" as our .NET Core version and click "Create"
Step 2: Once Visual Studio generates ASP.NET Core MVC template files, we will now need to install NuGet Package jsreport, so navigate to "Tools" -> "NuGet package manager" -> Select "Manage NuGet package for solution" -> select "Browse" tab and search for "jsreport", then we will to install 3 packages
- jsreport.Local
- jsreport.Binary
- jsreport.AspNetCore
Install-Package jsreport.Client
Here is an image
Once you have installed all 3 the above packages, as shown in the image, we can move to the next step.
As jsreport.AspNetCore
includes just helper classes to work with jsreport and it still requires to connect to instance running through jsreport.Local
or to the instance running remotely through jsreport.Client
.
Step 3: Navigate to "Program.cs" in your .NET Core solution to add jsreport in your project
using jsreport.AspNetCore;
using jsreport.Binary;
using jsreport.Local;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddJsReport(new LocalReporting()
.UseBinary(JsReportBinary.GetBinary())
.AsUtility()
.Create());
Step 4: Since we generated ASP.NET Core MVC template using Visual Studio, it has an auto-generated Index.cshtml
view, which I will use to convert to PDF.
So Navigate to "HomeController.cs" and use below C# Code.
using jsreport.AspNetCore;
using jsreport.Types;
using Microsoft.AspNetCore.Mvc;
namespace ASPNetCoreHTMLtoPDF.Controllers
{
public class HomeController : Controller
{
[MiddlewareFilter(typeof(JsReportPipeline))]
public IActionResult Index()
{
HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf);
return View();
}
}
}
The above code enables asp.net filter which captures the view rendering result and uses the specified chrome-pdf recipe to convert the output HTML into pdf.
That's it, we are done, once you will build and run your project, you will see HTML View is converted as PDF and shown in browser as below
Download HTML as PDF in ASP.NET Core
You can directly save pdf file generated from Razor view as shown below
var contentDisposition = "attachment; filename=\"myReport.pdf\"";
HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf)
.OnAfterRender((r) => HttpContext.Response.Headers["Content-Disposition"] = contentDisposition);
Save PDF File
You can also save PDF file externally
[MiddlewareFilter(typeof(JsReportPipeline))]
public IActionResult Index()
{
HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf);
HttpContext.JsReportFeature().OnAfterRender((r) => {
using (var file = System.IO.File.Open("report.pdf", FileMode.Create))
{
r.Content.CopyTo(file);
}
r.Content.Seek(0, SeekOrigin.Begin);
});
return View();
}
OnAfterRender
hook can be used also to store output to file and at the same time return stream as the response.
Adding Headers
Using JsReport, you can also add headers in PDF report.
The pdf headers can be specified in extra partial view and rendered in runtime along with the main pdf content, but first, you need to get the IJsReportMVCService
helper class from the asp.net container.
public IJsReportMVCService JsReportMVCService { get; }
public HomeController(IJsReportMVCService jsReportMVCService)
{
JsReportMVCService = jsReportMVCService;
}
You will also need to add "Header.cshtml" partial view
using jsreport.AspNetCore;
using jsreport.Types;
using Microsoft.AspNetCore.Mvc;
namespace ASPNetCoreHTMLtoPDF.Controllers
{
public class HomeController : Controller
{
public IJsReportMVCService JsReportMVCService { get; }
public HomeController(IJsReportMVCService jsReportMVCService)
{
JsReportMVCService = jsReportMVCService;
}
[MiddlewareFilter(typeof(JsReportPipeline))]
public async Task<IActionResult> IndexAsync()
{
var header = await JsReportMVCService.RenderViewToStringAsync(
HttpContext, RouteData, "Header", new { });
HttpContext.JsReportFeature()
.Recipe(Recipe.ChromePdf)
.Configure((r) => r.Template.Chrome = new Chrome { HeaderTemplate = header });
return View();
}
}
}
That's it.
You may also like to read:
How to connect sql server database in ASP.NET Core MVC
Bulk Insert in ASP.NET Core MVC using Entity Framework Core
Run or Execute Stored Procedure using EF Core
Read OR Generate QR Code in ASP.NET Core
Creating Cascading Dropdown list in ASP.NET Core MVC
jQuery Datatable Server side processing in ASP.NET Core
Bootstrap Pop Up Modal Validation in ASP.NET Core MVC
Difference between AddTransient, AddScoped and AddSingleton in ASP.NET Core
Get JSON result from MVC using jQuery Ajax & show JSON data in HTML
How to comment PowerShell code?
Ways to Fix 'Circular reference detected' error in Entity Framework C#
Upload file to Google Drive using Google Drive API in ASP.NET MVC C#