Search code examples
c#htmlpdfitext

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


I have HTML as below:

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

As can be figure out that, {Applicant Name} and {Applicant Age} are place holders.

The objective is to replace those place holder values at runtime and generate PDF using iTextSharp.

I'm able to generate the PDF from HTML template but not able to replace the placeholder values at runtime.

Here is what I have tried so far:

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

Final output will be:

enter image description here


Solution

  • Prior to iTextSharp opening and converting the HTML file, you can perform a String.Replace() against the HTML file to change your place holders to your desired values. See example below:

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