Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在运行时替换HTML的占位符值并使用iTextSharp生成PDF?_C#_Html_Pdf_Itext - Fatal编程技术网

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

C# 如何在运行时替换HTML的占位符值并使用iTextSharp生成PDF?,c#,html,pdf,itext,C#,Html,Pdf,Itext,我的HTML格式如下: <html> <head> <title></title> </head> <body> <p>Name:{Applicant Name}</p> <p>Age:{Applicant Age}</p> <

我的HTML格式如下:

<html>
    <head>
        <title></title>
    </head>
    <body>
                        
            <p>Name:{Applicant Name}</p>
            <p>Age:{Applicant Age}</p>
    </body>
</html>
最终产出将是:


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