Generate PDF from HTML Template in C# – Full Tutorial

C-sharp Generate PDF from HTML Template

In many modern .NET applications, generating professional-looking PDF documents is a common requirement — especially for invoices, reports, certificates, and forms. Instead of creating PDFs manually, a smarter approach is to use HTML templates . HTML makes it easy to design layouts using CSS, include company branding, and reuse the same structure across multiple documents.

By dynamically inserting data into HTML and converting it to PDF programmatically, you can automate document generation while maintaining design consistency.

In this tutorial, you’ll learn how to generate a PDF from an HTML template in C# .NET using Spire.PDF for .NET. We’ll guide you step-by-step — from setting up your development environment (including the required HTML-to-PDF plugin), preparing the HTML template, inserting dynamic data, and generating the final PDF file.

On this page:

Why Generate PDFs from HTML Templates in C#?

Using HTML templates for PDF generation offers several advantages:

  • Reusability: Design once, reuse anywhere — perfect for reports, receipts, and forms.
  • Styling flexibility: HTML + CSS allow rich formatting without complex PDF drawing code.
  • Dynamic content: Easily inject runtime data such as customer names, order totals, or timestamps.
  • Consistency: Ensure all generated documents follow the same layout and style guidelines.
  • Ease of maintenance: You can update the HTML template without changing your C# logic.

Set Up Your .NET Environment

Before you begin coding, make sure your project is properly configured to handle HTML-to-PDF conversion.

1. Install Spire.PDF for .NET

Spire.PDF for .NET is a professional library designed for creating, reading, editing, and converting PDF documents in C# and VB.NET applications—without relying on Adobe Acrobat. It provides powerful APIs for handling text, images, annotations, forms, and HTML-to-PDF conversion.

You can install it via NuGet:

Install-Package Spire.PDF

Or download it directly from the official website and reference the DLL in your project.

2. Install the HTML Rendering Plugin

Spire.PDF relies on an external rendering engine (Qt WebEngine or Chrome) to accurately convert HTML content into PDF. This plugin must be installed separately.

Steps:

  1. Download the plugin package for your platform.
  1. Extract the contents to a local folder, such as: C:\plugins-windows-x64\plugins
  2. In your C# code, register the plugin path before performing the conversion.
HtmlConverter.PluginPath = @"C:\plugins-windows-x64\plugins";

Prepare an HTML Template

Create an HTML file with placeholders for your dynamic data. For example, name it invoice_template.html :

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Invoice</title>
  <style>
    body { font-family: Arial; margin: 40px; }
    .header { font-size: 24px; font-weight: bold; margin-bottom: 20px; }
    table { width: 100%; border-collapse: collapse; margin-top: 20px; }
    th, td { border: 1px solid #999; padding: 8px; text-align: left; }
  </style>
</head>
<body>
  <div class="header">Invoice for {CustomerName}</div>
  <p>Date: {InvoiceDate}</p>
  <table>
    <tr><th>Item</th><th>Price</th></tr>
    <tr><td>{Item}</td><td>{Price}</td></tr>
  </table>
</body>
</html>

Tips:

  • Keep CSS inline or embedded within the HTML file.
  • Avoid JavaScript or complex animations.
  • Use placeholders like {CustomerName} and {InvoiceDate} for data replacement.

Insert Dynamic Data into HTML Before Conversion

You can read your HTML file as text, replace placeholders with real values, and then save it as a new temporary file.

using System;
using System.IO;

string template = File.ReadAllText("invoice_template.html");

template = template.Replace("{CustomerName}", "John Doe");
template = template.Replace("{InvoiceDate}", DateTime.Now.ToShortDateString());
template = template.Replace("{Item}", "Wireless Mouse");
template = template.Replace("{Price}", "$25.99");

File.WriteAllText("invoice_ready.html", template);

This approach lets you generate customized PDFs for each user or transaction dynamically.

Convert Updated HTML Template to PDF in C#

Now that your HTML content is ready, you can use the HtmlConverter.Convert() method to directly convert the HTML string into a PDF file.

Below is a full code example to create PDF from HTML template file in C#:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Spire.Additions.Qt;
using Spire.Pdf.Graphics;
using Spire.Pdf.HtmlConverter;

namespace CreatePdfFromHtmlTemplate
{
    class Program
    {
        static void Main(string[] args)
        {
            // Path to the HTML template file
            string htmlFilePath = "invoice_template.html";

            // Step 1: Read the HTML template from file
            if (!File.Exists(htmlFilePath))
            {
                Console.WriteLine("Error: HTML template file not found.");
                return;
            }

            string htmlTemplate = File.ReadAllText(htmlFilePath);

            // Step 2: Define dynamic data for invoice placeholders
            Dictionary<string, string> invoiceData = new Dictionary<string, string>()
            {
                { "INVOICE_NUMBER", "INV-2025-001" },
                { "INVOICE_DATE", DateTime.Now.ToString("yyyy-MM-dd") },
                { "BILLER_NAME", "John Doe" },
                { "BILLER_ADDRESS", "123 Main Street, New York, USA" },
                { "BILLER_EMAIL", "john.doe@example.com" },
                { "ITEM_DESCRIPTION", "Consulting Services" },
                { "ITEM_QUANTITY", "10" },
                { "ITEM_UNIT_PRICE", "$100" },
                { "ITEM_TOTAL", "$1000" },
                { "SUBTOTAL", "$1000" },
                { "TAX_RATE", "5" },
                { "TAX", "$50" },
                { "TOTAL", "$1050" }
            };

            // Step 3: Replace placeholders in the HTML template with real values
            string populatedInvoice = PopulateInvoice(htmlTemplate, invoiceData);

            // Optional: Save the populated HTML for debugging or review
            File.WriteAllText("invoice_ready.html", populatedInvoice);

            // Step 4: Specify the plugin path for the HTML to PDF conversion
            string pluginPath = @"C:\plugins-windows-x64\plugins";
            HtmlConverter.PluginPath = pluginPath;

            // Step 5: Define output PDF file path
            string outputFile = "InvoiceOutput.pdf";

            try
            {
                // Step 6: Convert the HTML string to PDF
                HtmlConverter.Convert(
                    populatedInvoice,
                    outputFile,
                    enableJavaScript: true,
                    timeout: 100000,                // 100 seconds
                    pageSize: new SizeF(595, 842),  // A4 size in points
                    margins: new PdfMargins(20),    // 20-point margins
                    loadHtmlType: LoadHtmlType.SourceCode
                );

                Console.WriteLine($"PDF generated successfully: {outputFile}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during PDF generation: {ex.Message}");
            }
        }

        /// <summary>
        /// Helper method: Replaces placeholders in the HTML with actual data values.
        /// </summary>
        private static string PopulateInvoice(string template, Dictionary<string, string> data)
        {
            string result = template;
            foreach (var entry in data)
            {
                result = result.Replace("{" + entry.Key + "}", entry.Value);
            }
            return result;
        }
    }
}

How it works :

  1. Create an invoice template with placeholder variables in {VARIABLE_NAME} format.
  2. Set up a dictionary with key-value pairs containing actual invoice data that matches the template placeholders.
  3. Replace all placeholders in the HTML template with actual values from the data dictionary.
  4. Use Spire.PDF with the Qt plugin to render the HTML content as a PDF file.

Result:

Create PDF from Template in C#

Best Practices for Generating PDF from HTML in C#

  • Use fixed-width layouts: Avoid fluid or responsive designs to maintain consistent rendering.
  • Embed or inline CSS: Ensure your styles are self-contained.
  • Use standard fonts: Arial, Times New Roman, or other supported fonts convert reliably.
  • Keep images lightweight: Compress large images to improve performance.
  • Test with different page sizes: A4 and Letter are the most common formats.
  • Avoid unsupported tags: Elements relying on JavaScript (like <canvas>) won’t render.

Final Words

Generating PDFs from HTML templates in C# .NET is a powerful way to automate document creation while preserving visual consistency. By combining Spire.PDF for .NET with the HTML rendering plugin , you can easily transform styled HTML layouts into print-ready PDF files that integrate seamlessly with your applications.

Whether you’re building a reporting system, an invoicing tool, or a document automation service, this approach saves time, reduces complexity, and produces professional results with minimal code.

FAQs About C# HTML Template to PDF Conversion

Q1: Can I use Google Chrome for HTML rendering instead of Qt WebEngine?

Absolutely. For advanced HTML, CSS, or modern JavaScript, we recommend using the Google Chrome engine via the ChromeHtmlConverter class for more precise and reliable PDF results.

For a complete guide, see our article: Convert HTML to PDF using ChromeHtmlConverter

Q2: Do I need to install a plugin for every machine running my application?

Yes, each environment must have access to the HTML rendering plugin (Qt or Chrome engine) for successful HTML-to-PDF conversion.

Q3: Does Spire.PDF support external CSS files or online resources?

Yes, but inline or embedded CSS is recommended for better rendering accuracy.

Q4: Can I use this approach in ASP.NET or web APIs?

Absolutely. You can generate PDFs server-side and return them as downloadable files or streams.

Q5: Is JavaScript supported during HTML rendering?

Limited support. Static elements are rendered correctly, but scripts and dynamic DOM manipulations are not executed.

Get a Free License

To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.