当前位置: 代码网 > it编程>网页制作>网页播放器 > 使用C#和Spire.PDF从HTML模板生成PDF的实用指南

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

2026年03月05日 网页播放器 我要评论
生成 pdf 报告和文档已成为一种常见需求。许多开发者希望利用 html 模板的灵活性,动态创建 pdf,以便轻松集成数据。本文将探讨如何使用 c# 和 spire.pdf for .net 库,从

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

准备工作

在开始之前,确保您已经安装了 spire.pdf for .net 库,并引入了额外的 qt 插件。确保将插件路径指向正确的位置,以便在生成 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<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;
        }
    }
}

代码解析

  • 读取 html 模板

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

  • 定义数据结构

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

  • 替换占位符

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

  • html 转换为 pdf

设置必要的配置后,调用 htmlconverter.convert 方法将填充后的 html 转换为 pdf 文件。您可以自定义页面大小、边距以及是否启用 javascript。

总结

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

以上就是使用c#和spire.pdf从html模板生成pdf的实用指南的详细内容,更多关于c# html模板生成pdf的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com