Reason for the article:
Parameters to compare:
I went through a ton of articles and questions on stack overflow, stack exchange, here are some options how to generate HTML documents:
While checking the RazorEngine approach I was not able to run it on .Net Core. It requires lots of dependencies and obsolete libraries.
Knowing that everybody would avoid obsolete technologies and .Net framework libs I think going with this generator is not the right way.
After some research, I was able to run the Razor engine using this library on “netstandard” library, please see the following code below.
Pros:
Cons:
<PreserveCompilationContext>true</PreserveCompilationContext>
HtmlContentBuilder is more suitable for dynamic HTML creation and requires lots of preparation to build actual HTML output. I do not see the benefits of using this library for current goals.
This idea died in my head at the very beginning, since to achieve this we needed to:
Here is the code example with the simplest and atomic approach implemented in .net core console application:
Key points:
After all the previous disappointing findings I started locking in using JS frameworks to do the generation of documents, that is how I found Handlebars.js but written fully in .NET.
So Handlebars.Net is a really easy and fast way to do documents generation because it doesn't use any scripting engine to run a Javascript library; it compiles Handlebars templates directly to IL bytecode. It also mimics the JS library's API as closely as possible.
Since Handlebars.js has a big community and a long story you will be able to find answers to your questions to build a valid HTML.
The link to their Github repo is here.
The simplest and fastest way for simple files generation would be to go with simple templating which will not bring new dependencies into the project.
On the other hand, people who know Razor may be easier to go with a powerful Razor engine via RazorLight, but it may require DevOps effort to make sure dependent libraries are in place in the environments. And I think the easiest and most extendable way would be Handlebars.Net which is straightforward in usage.
In addition
All these findings can be applied not only to generate HTML files, but for XML files and any plain text documents.
Also, this article will be useful for those who are looking for a way to generate PDF documents since data sources for the generation of PDF files may be HTML string. A good topic to explore next would be: "How to convert HTML to PDF."
Lead image courtesy of Nathan da Silva on Unsplash.