使用 C# 和 Spire.PDF 从 HTML 模板生成 PDF 的实用指南

13 阅读2分钟

生成 PDF 报告和文档已成为一种常见需求。许多开发者希望利用 HTML 模板的灵活性,动态创建 PDF,以便轻松集成数据。本文将探讨如何使用 C# 和 Spire.PDF for .NET 库,从 HTML 模板生成 PDF 文件。我们将通过一个实际示例展示这一过程,具体而言,创建和填充发票模板的步骤。

准备工作

在开始之前,确保您已经安装了 Spire.PDF for .NET 库,并引入了额外的 QT 插件。可以在 这里下载 QT 插件 (Windows 64 bit 可用)。确保将插件路径指向正确的位置,以便在生成 PDF 时能够正常使用。

NuGet 安装 Spire.PDF:

Install-Package Spire.PDF

代码实现

下面是一个示例代码,用于从 HTML 模板生成 PDF:

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<stringstring> invoiceData = new Dictionary<stringstring>()
            {
                { "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(595842),  // 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<stringstring> data)
        {
            string result = template;
            foreach (var entry in data)
            {
                result = result.Replace("{" + entry.Key + "}", entry.Value);
            }
            return result;
        }
    }
}

代码解析

  • 读取 HTML 模板

首先,代码会检查 HTML 模板文件是否存在。如果文件不存在,则程序会输出错误信息并终止。

  • 定义数据结构

使用字典(Dictionary)来存储发票的数据,包括发票号码、日期、发件人信息和项目详情。

  • 替换占位符

PopulateInvoice 方法负责将 HTML 模板中的占位符替换为实际数据。这允许我们将动态内容嵌入到静态模板中。

  • HTML 转换为 PDF

设置必要的配置后,调用 HtmlConverter.Convert 方法将填充后的 HTML 转换为 PDF 文件。您可以自定义页面大小、边距以及是否启用 JavaScript。

总结

通过使用 C# 和 Spire.PDF for .NET,结合 HTML 模板,开发人员可以轻松生成个性化的 PDF 文件。这种方法不仅提高了生产效率,还提供了灵活性,便于维护和更新模板。无论是发票、报告还是其他类型的文档,这种方式都能带来显著的好处。希望这篇文章对您在项目中实现 PDF 生成有所帮助!