c# - 如何在运行时替换 HTML 的占位符值并使用 iTextSharp 生成 PDF?

标签 c# html pdf itext

我的 HTML 如下:

<html>
    <head>
        <title></title>
    </head>
    <body>
                        
            <p>Name:{Applicant Name}</p>
            <p>Age:{Applicant Age}</p>
    </body>
</html>

可以看出,{Applicant Name}{Applicant Age} 是占位符。

目标是在运行时替换这些占位符值并使用 iTextSharp 生成 PDF。

我能够从 HTML 模板生成 PDF,但无法在运行时替换占位符值。

这是我迄今为止尝试过的:

public void HTML2PDFTest()
        {
            var name = "some name";
            var age = 27;
           
            HtmlConverter.ConvertToPdf
                (
                        new FileInfo(@"D:\test.html")
                        ,new FileInfo(@"D:\test.pdf")
                );
        }

最终输出将是:

enter image description here

最佳答案

在 iTextSharp 打开并转换 HTML 文件之前,您可以对 HTML 文件执行 String.Replace() 以将占位符更改为所需的值。请参阅下面的示例:

public void HTML2PDFTest()
{
    var name = "some name";
    var age = 27;

    string htmlFileContent = "";
    using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.html"))
        htmlFileContent = file.ReadToEnd();

    htmlFileContent = htmlFileContent.Replace("{Applicant Name}", name).Replace("{Applicant Age}", age.ToString());

    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\test.html"))
        file.Write(htmlFileContent);
    
    HtmlConverter.ConvertToPdf
    (
        new FileInfo(@"D:\test.html"),
        new FileInfo(@"D:\test.pdf")
    );
}

关于c# - 如何在运行时替换 HTML 的占位符值并使用 iTextSharp 生成 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64916236/

相关文章:

c# - 选择工作簿 Excel 已使用按钮单击方法打开

c# - .NET 6 中的 using 语句/指令在哪里

使用 selenium : ui-dialog trouble with switching 进行 Python 3 网页抓取

php - 带有 PHP 和 Laravel 的数字签名 PDF 文件

node.js - 试图在使用 Puppeteer 生成的 PDF 上隐藏第一个页脚/页眉

c# - HttpClient 解码编码的 Url?

c# - 无法在MVVM中覆盖

html - 编辑 Shopify 的结帐

javascript - 如果未选择任何内容,PHP setcookie 不显示

php - PHP、HTML 和 CSS 的页面布局问题