【问题标题】:How to replace place holder values of HTML at runtime and generate PDF using iTextSharp?如何在运行时替换 HTML 的占位符值并使用 iTextSharp 生成 PDF?
【发布时间】:2021-03-03 02:06:51
【问题描述】:

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

最终输出将是:

【问题讨论】:

    标签: c# html pdf itext


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-29
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 2014-01-01
      相关资源
      最近更新 更多