Generate Dynamic PDF Reports from an HTML Template Using C#
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (178).NET Core  (29).NET MAUI  (214)Angular  (110)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (223)BoldSign  (15)DocIO  (24)Essential JS 2  (109)Essential Studio  (200)File Formats  (68)Flutter  (133)JavaScript  (225)Microsoft  (120)PDF  (81)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (936)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (52)Windows Forms  (61)WinUI  (71)WPF  (162)Xamarin  (161)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (9)Business intelligence  (55)Button  (4)C#  (156)Chart  (138)Chart of the week  (53)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (67)Development  (650)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (6)Essential Tools  (14)Excel  (43)Extensions  (22)File Manager  (7)Gantt  (19)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (512)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (4)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (12)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (393)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (607)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Generate Dynamic PDF Reports from an HTML Template Using C#

Generate Dynamic PDF Reports from an HTML Template Using C#

Generating PDF documents from the scratch is always a difficult process and has the following disadvantages:

  • It is time-consuming.
  • It is challenging to design a complex PDF.
  • It is prone to errors.

It is always advisable to generate PDF documents from well-designed HTML templates. In this blog post, we will see how to generate PDF reports from HTML templates using Syncfusion’s HTML-to-PDF converter in C#.

The HTML-to-PDF converter supports all modern features such as HTML5, CSS3, SVG, and web fonts. So, you can easily style your PDF reports by updating the CSS file with your images and fonts in C#.

To demonstrate this, we are going to generate a PDF invoice from an HTML template using C# with the following steps:

  1. Create an HTML template.
  2. Access the data and bind it with an HTML template.
  3. Convert the HTML string to PDF.

Syncfusion .NET HTML-to-PDF converter:

  • Convert any HTML file to PDF.
  • Preserve graphics, text, forms, and more.
  • Encrypt the PDF with a password.

Create an HTML template

An HTML template contains placeholders with {{mustache}} syntax. It is used to bind the actual data to the HTML template. For this example, we’ll use the Scriban scripting language to create the placeholders. It’s a lightweight scripting language and engine for .NET.

Note: To learn more about the Scriban scripting language, refer to the documentation.

The following code example shows the data model for the invoice.

public class Invoice
  public string InvoiceNumber { get; set; }
  public string IssueDate { get; set; }
  public string DueDate { get; set; }

  public UserDetails CompanyDetails { get; set; }
  public UserDetails CustomerDetails { get; set; }

  public List<Item> Items { get; set; }

  public decimal SubTotal
      return Items.Sum(x => x.Price * x.Quantity);

  public float Tax
       return (float)SubTotal * (25f / 100f);

  public float GrandTotal
      return (float)SubTotal + Tax;

Based on this model, we design the template as follows. By default, the properties and methods of .NET objects are automatically exposed with lowercase and _ names. This means that a property like Invoice.CompanyDetails.Name will be exposed as This is the default convention.

<html lang="en">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css" media="all" />
    <header class="clearfix">
      <div id="logo">
        <img src="logo.png">
      <div id="company">
        <h2 class="name">{{}}</h2>
      <div id="details" class="clearfix">
        <div id="client">
          <div class="to">INVOICE TO:</div>
          <h2 class="name">{{}}</h2>
          <div class="address">{{invoice.customer_details.address}}</div>
          <div class="email">{{}}</div>
        <div id="invoice">
          <div class="date">Date of Invoice: {{invoice.issue_date}}</div>
          <div class="date">Due Date: {{invoice.due_date}}</div>
      <table border="0" cellspacing="0" cellpadding="0">
            <th class="no">#</th>
            <th class="desc">DESCRIPTION</th>
            <th class="unit">UNIT PRICE</th>
            <th class="qty">QUANTITY</th>
            <th class="total">TOTAL</th>
        <tbody id="invoiceItems">
		  {{- index = 1 -}}
		  {{ for item in invoice.items }}
            <td class="no">{{index}}</td>
            <td class="desc"><h3>{{}}</h3>{{item.description}}</td>
            <td class="unit">${{item.price}}</td>
            <td class="qty">{{item.quantity}}</td>
            <td class="total">${{item.total_price}}</td>
		  {{index = index + 1}}
            <td colspan="2"></td>
            <td colspan="2">SUBTOTAL</td>
            <td colspan="2"></td>
            <td colspan="2">TAX 25%</td>
            <td colspan="2"></td>
            <td colspan="2">GRAND TOTAL</td>
      <div id="thanks">Thank you!</div>
      <div id="notices">
        <div class="notice">A finance charge of 1.5% will be made on unpaid balances after 30 days.</div>

You can get this HTML template with CSS and fonts from this GitHub repository.

The following screenshot shows the output of the HTML template with styled CSS.

Invoice HTML template
Invoice HTML template

Everything you need to know about the comprehensive features of Syncfusion’s robust HTML-to-PDF converter.

Access the data and bind it with the HTML template

To simplify this article, we have used a custom JSON file to store and retrieve the data. The following code snippet is used to create the invoice model.

Invoice invoice= JsonConvert.DeserializeObject<Invoice>(File.ReadAllText("../../../InvoiceData.json"));

Now, we use Scriban to bind the data from the model to the HTML template, as explained in the following code example.

//Load html HTML template.
var invoiceTemplate = File.ReadAllText("../../../Template/index.html");
var template = Template.Parse(invoiceTemplate);
var templateData = new { invoice };
//Fill template with real invoice data.
var pageContent = template.Render(templateData);

Check out our demo of converting URLs to PDFs with custom features.

Convert HTML string to PDF

The last step is to generate the invoice PDF from the bound HTML created in the previous section.

We use the HtmlToPdfConverter to convert the HTML string to a PDF document. Refer to the following code example.

//Initialize HTML to PDF converter with Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

//Convert HTML string to PDF. 
PdfDocument document = htmlConverter.Convert(pageContent , Path.GetFullPath("Template"));

FileStream fs = new FileStream("Output.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document.


After the conversion, you will get a PDF document like in the following screenshot.

Invoice PDF document
Invoice PDF document

GitHub samples

For better understanding, we have committed the source for this project in the PDF generation from HTML template GitHub repository.

Join thousands of developers who rely on Syncfusion for their PDF needs. Experience the difference today!


In this blog post, we have learned how to generate PDF reports from an HTML template using Syncfusion’s C# HTML-to-PDF converter.

Take a moment to look at the documentation, where you will find other options and features, all with accompanying code samples.

Please let us know in the comments below if you have any questions about these features. You can also contact us through our support forum, support portal or feedback portal. We are happy to assist you!

Related blogs

If you liked this article, we think you would also like the following articles about PDF Library:


Share this post:

Comments (4)

//Load html HTML template.
var invoiceTemplate = File.ReadAllText(“../../../Template/index.html”);
var template = Template.Parse(invoiceTemplate);
var templateData = new { invoice };
//Fill template with real invoice data.
var pageContent = template.Render(templateData);

In this code, For Template.Parse() which package do you have used because I am getting error like, The name ‘Template’ does not exist in current template

can you tell me ASAP?

Hi Vikas,

You have to use the following Nuget package to use the Template.Parse() code.

Also, you can refer to the full working sample from the below GitHub link.

Hello Praveenkumar,

I need your help. After applying your code to mine, i get a missing reference error here;

Invoice invoice = JsonConvert.DeserializeObject(File.ReadAllText(“~/Report_template/InvoiceData.json”));

All the “Invoice” are red underlined with this error message;
The type or namespace name ‘Invoice’ could not be found (are you missing a using directive or an assembly reference?)

I am using the following references;
using System.IO;
using PdfGeneration.Model;
using Scriban;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;

Although, PdfGeneration.Model; is also red underlined with the following error;

The type or namespace name ‘PdfGeneration’ could not be found (are you missing a using directive or an assembly reference?)

I’m not sure whether i need to download more references. When i hover on the invoice error and go to “show potential fixes”, VS is telling me to install from nuget.

Can you please help me out?

I am getting a runtime error in this line

var templateData = new { invoice };

The error is => Scriban.Syntax.ScriptRuntimeException: (13,56) : error : Cannot get the member for a null object.

I need assistance on how to handle this please.

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed
Syncfusion Ad