Converting HTML to PDF with JsReport in .NET
Effortless Integration and Dynamic Report Generation
In this post, I will showcase how to convert HTML code into PDF using JsReport, a JavaScript-based reporting library that can be easily integrated into .NET projects.
JsReport enables the creation of custom reports from HTML, CSS, and JavaScript templates, using dynamic data and features such as graphs, tables, and images.
Prerequisites
Visual Studio 2022
Packages:
Note: Additional HTML to PDF Option
Developers working with HTML to PDF conversion in C# might also consider IronPDF, another C# PDF library available for .NET projects.
IronPDF approaches HTML to PDF conversion using an embedded Chrome engine:
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf.SaveAs("output.pdf");The library can convert HTML to PDF from various sources including HTML strings, URLs, and existing .NET views, with support for CSS3, JavaScript, and images. This HTML to PDF converter handles the rendering process internally without requiring external configuration. Start 30-day free trial of IronPDF here.
The approach demonstrated in this article with jsreport provides excellent template-based reporting capabilities, particularly useful for complex report generation scenarios.
API
The first step is to configure the program.cs class:
var builder = WebApplication.CreateBuilder(args);
builder.AddSerilog(builder.Configuration, "Sample JsReport");
Log.Information("Starting API");
builder.Services.AddRouting(options => options.LowercaseUrls = true);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.AddJsReport();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();The AddJsReport() extension is responsible for registering the JsReport dependency injection into the solution:
public static class JsReportExtensions
{
public static WebApplicationBuilder AddJsReport(this WebApplicationBuilder builder)
{
var localReporting = new LocalReporting()
.UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ?
jsreport.Binary.Linux.JsReportBinary.GetBinary() :
jsreport.Binary.JsReportBinary.GetBinary())
.KillRunningJsReportProcesses()
.Configure(cfg =>
{
cfg.ReportTimeout = 60000;
cfg.Chrome = new ChromeConfiguration
{
Timeout = 60000,
Strategy = ChromeStrategy.ChromePool,
NumberOfWorkers = 3
};
cfg.HttpPort = 3000;
return cfg;
})
.AsUtility()
.Create();
builder.Services.AddJsReport(localReporting);
return builder;
}
}This code creates a local instance of the converter, using the JsReport binary automatically downloaded by the NuGet package.
KillRunningJsReportProcesses()method is responsible for terminating/freeing memory from previous PDF generation processes.Configure()method is responsible for additional configurations of JsReport, in this case, configuring PDF generations to be processed in the Chrome browser.AsUtility()method indicates that we will use JsReport as a utility tool, without storing templates or generated reports.Create()method finalizes the JsReport configuration.
Now, we can use JsReport for conversions. For this, it’s necessary to create a method in the Controller that receives an HTML as a parameter and returns a PDF file as a result:
[ApiController]
[Route("[controller]")]
public class ConverterHtml : ControllerBase
{
private readonly IRenderService _render;
public ConverterHtml(IRenderService render)
{
_render = render;
}
[HttpPost]
public async Task<IActionResult> Convert([FromForm] string html)
{
var report = await _render.RenderAsync(new RenderRequest
{
Template = new Template
{
Recipe = Recipe.ChromePdf,
Engine = Engine.JsRender,
Content = html
}
});
return File(report.Content, "application/pdf", "file.pdf");
}
}The RenderAsync() method receives a RenderRequest object, which contains information about the template and report format. In our case, the template is the HTML we receive as a parameter. Finally, we return this content as a PDF file using the File method.
Testing
To test our method, we can create a simple HTML with some text and an image. For example:
<html>
<head>
<style>
h1 {
color: blue;
}
</style>
</head>
<body>
<h1>Converting HTML to PDF with JsReport in .NET</h1>
<p>This is a cool example of how to convert HTML to PDF using JsReport in .NET.</p>
<img src="https://raw.githubusercontent.com/dotnet/brand/main/logo/text-only/Black/dotnet-logo-text_Black%402x.png" alt=".NET logo" width="323" height="121">
</body>
</html>Then, pass the HTML as a parameter when calling the api/converterhtml endpoint and click Execute:
What results in the generation of the PDF file:
Conclusion
With JsReport, it became much simpler to convert HTML codes to PDF while maintaining formatting and images. We can use more complex templates and add more features to our report, such as headers, footers, page numbering, etc. To learn more about JsReport and its functionalities, consult the official documentation: https://jsreport.net/learn/dotnet-aspnetcore
If you like the article and would like to support me, make sure to:
- 👏 Clap & highlight to feature it.
- 💬 Share your thoughts in the comments.
- 👉 Follow me on Medium
Please take advantage of my other stories!! 👇🔽

