In this blog we will see how to convert HTML string to Word, save downloaded word to folder or download in asp.net using c# with example. Converting html to word in this blog does not contain any third party library. All the classes and namespaces available in .Net framework. 

Create HTML page

Step 1. Create one .html page in your project and design it according to your requirements. Or you can download any sample html template from internet and put it to proper folder in project.

Sample.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

</head>

<body>

    <header>

        <h1>My Invoice Sample</h1>

        <div>

            <div><img src="http://localhost:50763/images/logo.jpg" style="width: 200px; height: 70px;" /></div>

            <div>Company Address</div>

            <div>Phone number</div>

            <div><a>company email address</a></div>

        </div>

        <div>

            <div><span>PROJECT : </span>[ProjectTitle]</div>

            <div><span>CLIENT : </span>[ClientName]</div>

            <div><span>ADDRESS : </span>[ClientAddress]</div>

            <div><span>EMAIL : </span> <a>[ClientEmailAddress]</a></div>

            <div><span>DATE : </span>[Date]</div>

        </div>

    </header>

    <div class="content">

        <table>

            <thead>

                <tr>

                    <th>SERVICE</th>

                    <th>DESCRIPTION</th>

                    <th>PRICE</th>

                    <th>QTY</th>

                    <th>TOTAL</th>

                </tr>

            </thead>

            <tbody>

                <tr>

                    <td>Data collection</td>

                    <td>Collected data</td>

                    <td>Rs.500.00</td>

                    <td>1</td>

                    <td>Rs. 500.00</td>

                </tr>

                <tr>

                    <td colspan='4'>SUBTOTAL</td>

                    <td>----</td>

                </tr>

                <tr>

                    <td colspan='4'>GST 18%</td>

                    <td>----</td>

                </tr>

                <tr>

                    <td colspan='4'>GRAND TOTAL</td>

                    <td>Rs. 500.00</td>

                </tr>

            </tbody>

        </table>

    </div>

    <footer>

        Invoice generated automatic through computer. Do not required seal and signature.  

    </footer>

</body>

</html>

In this sample html page I have used some text with square brackets, which will be replace with dynamic values entered by user.

Generate word and Save to folder

Step 1. Create a folder with name words in your project where generated word from code will be save.

Step to create new folder: Right click on project-> Add-> New Folder.

Step 2. Now create ConvertHTMLtoWord.aspx page to write below code. Here I have used two namespaces System.IO and System.Text. Please read my comments to understand code properly.

Step to create new page: Right click on project-> Add-> Add New Item-> Select Web Form-> Add.

ConvertHTMLtoWord.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ConvertHTMLtoWord.aspx.cs" Inherits="ConvertHTMLtoWord" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Convert HTML to Word</title>

    <style type="text/css">

        h2, table {

            display: table;

            margin: 40px auto;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <h2>Generate HTML to Word</h2>

            <table>

                <tr>

                    <td>Project Title

                    </td>

                    <td>

                        <asp:TextBox ID="txtProjectTitle" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Cilent Name

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientName" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Cilent Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Client Email Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientEmailAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Date

                    </td>

                    <td>

                        <asp:TextBox ID="txtDate" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Button Text="Generate Word" ID="btnGenerateWord" runat="server" OnClick="btnGenerateWord_Click" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Label Text="" ID="lblMsg" runat="server" />

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

ConvertHTMLtoWord.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO; /* Add this Namespace */

using System.Text; /* Add this Namespace */

  

public partial class ConvertHTMLtoWord : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

  

    /* Generate button click event */

    protected void btnGenerateWord_Click(object sender, EventArgs e)

    {

        string htmlstring = "", Filename = DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".doc", Filepath = "";

        htmlstring = File.ReadAllText(HttpContext.Current.Server.MapPath("~/template/Sample.html")); /* Read Sample.html from folder in our project */

  

        /* Replace square braket text with dynamic value insert by user. ie. [ProjectTitle] -> value */

        htmlstring = htmlstring.Replace("[ProjectTitle]", txtProjectTitle.Text);

        htmlstring = htmlstring.Replace("[ClientName]", txtClientName.Text);

        htmlstring = htmlstring.Replace("[ClientAddress]", txtClientAddress.Text);

        htmlstring = htmlstring.Replace("[ClientEmailAddress]", txtClientEmailAddress.Text);

        htmlstring = htmlstring.Replace("[Date]", txtDate.Text);

  

        Filepath = "~/words/" + Filename; /* Path to save generated Word */

        fnGenerateWORD(htmlstring, Filepath);

    }

  

    /* Function to generate Word */

    public void fnGenerateWORD(string html, string Filepath)

    {

        try

        {

            StringWriter sw = new StringWriter(new StringBuilder(html));

            HtmlTextWriter hw = new HtmlTextWriter(sw);

            StreamWriter sWriter = new StreamWriter(HttpContext.Current.Server.MapPath(Filepath));

            sWriter.Write(sw.ToString());

            sWriter.Close();

  

            lblMsg.Text = "Word generated successfully. Please check your folder..!!";

        }

        catch (Exception ex)

        {

        }

    }

}

Word would be save to folder in your project. Here I have used "words" folder.

Generate Word and Download

You can create a new page to write code for downloading generated word. Your design page will remain same. Only the code of button click event will change. Code for generate word and download is given below.

ConvertAndDownload.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO; /* Add this Namespace */

using System.Text; /* Add this Namespace */

  

public partial class ConvertAndDownload : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

  

    /* Generate button click event */

    protected void btnGenerateWord_Click(object sender, EventArgs e)

    {

        string htmlstring = "", Filename = DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".doc";

        htmlstring = File.ReadAllText(HttpContext.Current.Server.MapPath("~/template/Sample.html")); /* Read Sample.html from folder in our project */

  

        /* Replace square braket text with dynamic value insert by user. ie. [ProjectTitle] -> value */

        htmlstring = htmlstring.Replace("[ProjectTitle]", txtProjectTitle.Text);

        htmlstring = htmlstring.Replace("[ClientName]", txtClientName.Text);

        htmlstring = htmlstring.Replace("[ClientAddress]", txtClientAddress.Text);

        htmlstring = htmlstring.Replace("[ClientEmailAddress]", txtClientEmailAddress.Text);

        htmlstring = htmlstring.Replace("[Date]", txtDate.Text);

  

        fnGenerateWORD(htmlstring, Filename);

    }

    

    /* Function to generate Word */

    public void fnGenerateWORD(string html, string Filename)

    {

        try

        {

            StringBuilder strBody = new StringBuilder(html);

  

            /* Code to download word */

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.Charset = "";

            HttpContext.Current.Response.ContentType = "application/msword";

            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + Filename);

            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            HttpContext.Current.Response.Write(strBody);

            HttpContext.Current.Response.End();

            HttpContext.Current.Response.Flush();

        }

        catch (Exception ex)

        {

        }

    }

}

Hope this blog will help you. If I missed something or you have doubts comment below. Thank you..!!