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

How to replace place holder values of HTML at runtime and generate PDF using iTextSharp?

我有 HTML 如下:

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

可以看出,{申请人姓名}{申请人年龄}是占位符。

objective 是在运行时替换那些占位符值并使用 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")
                );
        }

最终输出将是:

在 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")
    );
}