DEV Community

jelizaveta
jelizaveta

Posted on

Generating PDF from HTML Template Using C#

Generating PDF reports and documents has become a common requirement. Many developers want to take advantage of the flexibility offered by HTML templates to dynamically create PDFs, making data integration easy. This article will explore how to generate PDF files from HTML templates using C# and the Spire.PDF for .NET library. We will demonstrate this process through a practical example, specifically creating and populating an invoice template.

Preparation

Before getting started, ensure you have installed the Spire.PDF for .NET library and imported the additional QT plugin. You can download the QT plugin here (for Windows 64 bit). Make sure the plugin path is set correctly so that it can be used successfully when generating PDFs.

Code Implementation

Here’s a sample code that generates a PDF from an HTML template:

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;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation

  • Reading the HTML Template

The code first checks whether the HTML template file exists. If the file is not found, the program outputs an error message and terminates.

  • Defining Data Structure

A dictionary is used to store the data for the invoice, including the invoice number, date, biller information, and item details.

  • Replacing Placeholders

The PopulateInvoice method is responsible for replacing placeholders in the HTML template with actual data. This allows us to embed dynamic content into a static template.

  • HTML to PDF Conversion

After setting up the necessary configurations, the code calls the HtmlConverter.Convert method to convert the populated HTML into a PDF file. You can customize the page size, margins, and whether to enable JavaScript.

Conclusion

By using C# and Spire.PDF for .NET along with HTML templates, developers can easily generate personalized PDF files. This approach not only enhances productivity but also provides flexibility for maintaining and updating templates. Whether for invoices, reports, or other types of documents, this method offers significant advantages. I hope this article helps you implement PDF generation in your projects!

Top comments (0)