DEV Community

Cover image for How to Generate a PDF from a Template in C#
Mehr Muhammad Hamza
Mehr Muhammad Hamza

Posted on

How to Generate a PDF from a Template in C#

Generating PDF documents dynamically is a common task in modern applications, especially for invoices, reports, contracts, and certificates. In this article, we’ll explore how to generate PDF files from templates in C# using the IronPDF library. We’ll walk through template creation, data injection, styling, and output generation in a structured, real-world-friendly way.

Instead of manually constructing PDF layouts in code, we’ll rely on ready-made templates that can be reused across documents. This makes the workflow cleaner, the output more professional, and the system scalable for future enhancements.

In this tutorial, we’ll walk through how to generate PDF reports and create PDF documents from an HTML template using C# and IronPDF—a robust PDF library built specifically for .NET. This approach not only ensures beautiful formatting but also helps you scale with dynamic data sources.

Let’s get started!

Why Use PDF Templates?

Templates allow you to design your document layout independently from your code logic. By using HTML content, you can define styles, structure, and placeholders once and then bind them to a data model. This improves reusability and consistency across documents.

This approach is particularly helpful when you need to:

  • Generate PDF reports based on user data.
  • Insert images or logos dynamically.
  • Control layout with CSS (e.g., margins, font size, page breaks).
  • Work with web content or export web pages directly to PDF format.

This is especially helpful in document-heavy domains like finance, HR, legal, and education.

PDF templates are usually written in HTML/CSS, offering flexibility, design control, and separation of concerns between developers and designers.

Tools and Libraries

For this tutorial, we’re using IronPDF, a C# PDF generation library that supports:

  • Rendering HTML and Razor views into PDFs.
  • Injecting dynamic data into templates.
  • Loading from strings, files, or URLs.
  • Applying CSS and JavaScript styling.

Setting Up the Environment

To begin, open your project in Visual Studio. You can install IronPDF using the NuGet Package Manager UI or the Package Manager Console:

Install-Package IronPdf
Enter fullscreen mode Exit fullscreen mode

IronPDF supports .NET Framework, .NET Core, and .NET 5/6/7+. It works cross-platform (Windows, Linux, macOS), making it suitable for web apps, desktop apps, or services.

Install Package IronPDF

Step 1: Creating an HTML Template File

Rather than embedding HTML directly in C# code, we recommend creating a separate .html file that serves as your template. This keeps your codebase cleaner and separates concerns.

📄 invoice-template.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: Arial, sans-serif; padding: 40px; }
        h1 { color: #333; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { padding: 12px; border: 1px solid #ccc; }
    </style>
</head>
<body>
    <h1>Invoice #{{InvoiceNumber}}</h1>
    <p><strong>Date:</strong> {{Date}}</p>
    <p><strong>Customer:</strong> {{CustomerName}}</p>

    <table>
        <thead>
            <tr><th>Item</th><th>Quantity</th><th>Price</th></tr>
        </thead>
        <tbody>
            {{Items}}
        </tbody>
    </table>

    <p><strong>Total:</strong> {{Total}}</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Explanation:

This is a simple HTML file styled with CSS. It includes bound HTML placeholder tags such as {{InvoiceNumber}}, {{CustomerName}}, and {{Items}}. These will be replaced later in the code with actual data, using string replacement techniques. You can bind your data model directly to this.

Template

Template

Step 2: Loading and Populating the Template in C#

Now, we’ll load the HTML template from the file system, replace placeholders with actual data, and build a complete HTML document ready to render as a PDF.

📄 Code to Load Template and Replace Placeholders

using System.Text;


// Step 1: Load HTML template from file
string templatePath = "invoice-template.html";
string htmlTemplate = File.ReadAllText(templatePath);

// Step 2: Define data
string invoiceNumber = "INV-1001";
string date = DateTime.Now.ToShortDateString();
string customer = "John Doe";
var items = new List<(string Name, int Qty, decimal Price)>
{
    ("Laptop", 1, 999.99m),
    ("Mouse", 2, 25.50m)
};

// Step 3: Generate HTML rows for items
StringBuilder itemRows = new StringBuilder();
decimal total = 0;

foreach (var item in items)
{
    total += item.Qty * item.Price;
    itemRows.AppendLine(
        $"<tr><td>{item.Name}</td><td>{item.Qty}</td><td>${item.Price:F2}</td></tr>");
}

// Step 4: Replace placeholders with actual data
string populatedHtml = htmlTemplate
    .Replace("{{InvoiceNumber}}", invoiceNumber)
    .Replace("{{Date}}", date)
    .Replace("{{CustomerName}}", customer)
    .Replace("{{Items}}", itemRows.ToString())
    .Replace("{{Total}}", $"${total:F2}");
Enter fullscreen mode Exit fullscreen mode

Explanation

  • HTML Loading: The File.ReadAllText() method loads the template from a file, making it editable without recompiling.
  • Dynamic Content: Data such as invoice number, customer name, and line items are stored in variables and collections.
  • StringBuilder: Efficiently creates table rows for each item.
  • String Replacement: Simple Replace() calls inject the values into the placeholders.

This method keeps your code maintainable and avoids cluttering C# with raw HTML.

Step 3: Convert HTML to PDF

Now that we have a fully populated HTML document, the final step is to render it into a PDF file.

📄 Render and Save PDF

using IronPdf;   

var renderer = new ChromePdfRenderer();
   PdfDocument pdf = renderer.RenderHtmlAsPdf(populatedHtml);

   // Save the PDF to file
   pdf.SaveAs("Invoice.pdf");
Enter fullscreen mode Exit fullscreen mode

Explanation

  • ChromePdfRenderer() creates a new renderer instance.
  • RenderHtmlAsPdf() takes the HTML string and converts it into a PdfDocument.
  • SaveAs() writes the file to disk.

Output:

The output will reflect the layout of the HTML with all injected data — complete with table formatting, fonts, and any logos or images.

PDF from Template

Optional: Add Headers and Footers

For more professional output, you may want to add headers or footers that appear on every page.

📄 Header Example

The below code can easily be adapted or extended to meet additional requirements like headers, footers, styled tables, or even multiple page sections. Whether you're looking to generate a PDF for a client-facing summary or a system-generated new document, IronPDF allows you to scale with confidence, offering flexibility across templates, logic, and layout with minimal effort.

var renderer = new ChromePdfRenderer();


renderer.RenderingOptions.TextHeader.CenterText = "ACME Corporation Invoice";
renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
PdfDocument pdf = renderer.RenderHtmlAsPdf(populatedHtml);

// Save the PDF to file
pdf.SaveAs("Invoice.pdf");
Enter fullscreen mode Exit fullscreen mode

Explanation
This snippet adds a centered header with a dividing line to every page of the PDF. Similar options are available for footers, page numbering, and more.

Output:

Header and Footer in PDF

The above code illustrates how developers can create PDF files, create PDF documents, and build dynamic PDF reports using IronPDF with a clean HTML template. With input from a JSON file, you can handle various PDF generation tasks efficiently. This approach emphasizes clarity and maintainability by using minimal code, often just a few lines, to bind structured data and render polished PDFs.

Error Handling and Best Practices

When working with HTML-to-PDF conversion, be mindful of common pitfalls:

  • Missing placeholders: Use validations to ensure all {{...}} are replaced.
  • Encoding: Use UTF-8 for template files to handle special characters.
  • Images and fonts: Ensure external resources are accessible or embedded via base64.
  • Exceptions: Always wrap rendering in try-catch blocks.

Advanced Features You Can Explore

IronPDF also offers:

These are useful for more complex workflows like report generation systems or secure document delivery.

Real-World Applications

This pattern of generating PDFs from templates is widely used in:

  • E-commerce – Order confirmations, invoices, and shipping labels.
  • HR systems – Offer letters, payslips, and onboarding documents.
  • Legal automation – Contracts, agreements, and compliance forms.
  • Education – Student certificates, ID cards, and result reports.
  • Healthcare – Test reports, discharge summaries, and prescriptions.

Using templates reduces manual effort and ensures documents always follow brand and legal standards.

Conclusion

Generating PDFs from templates in C# is a practical and scalable approach for creating dynamic, professional documents. By separating content from presentation using HTML templates, you can streamline your workflow, improve maintainability, and produce consistently styled outputs across a range of applications—from invoices and reports to legal documents and beyond.

IronPDF makes this process seamless with its robust HTML-to-PDF rendering engine. Whether you're building a web application, desktop utility, or backend service, IronPDF provides flexibility, performance, and ease of use.

👉 Next Steps:

  • Try IronPDF for Free: You can get started immediately with a free trial that includes full functionality (with a watermark).
  • 💼 Commercial License: For production use, explore IronPDF's commercial licensing options tailored for individuals, teams, and enterprises.
  • 📚 Learn More: Visit the official documentation for detailed guides, API references, and best practices.

Take your document generation to the next level by integrating IronPDF into your C# projects today!

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

Top comments (0)

Scale globally with MongoDB Atlas. Try free.

Scale globally with MongoDB Atlas. Try free.

MongoDB Atlas is the global, multi-cloud database for modern apps trusted by developers and enterprises to build, scale, and run cutting-edge applications, with automated scaling, built-in security, and 125+ cloud regions.

Learn More

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay