Download Html to Word Document

09 May 2023 | Viewed 1602 times

HTML: HyperText Markup Language, is a Web format file.

DOC: Microsoft Word Document, is a file with .doc and it is associated mainly with Microsoft Word application.

C# Code

public void DownloadHtmlToWord()
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

Panel1.RenderControl(htmlWriter);
string strWordContent = StringWriter.ToString();

//prepare word content and add if need to apply any styles

StringBuilder strBody = new StringBuilder();
strBody.Append("<html " +
"xmlns:o='urn:schemas-microsoft-com:office:office'" +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www/w3.org/TR/REC-html40'>");

strBody.Append("<head>");
strBody.Append("<title>Document Title</title>");
strBody.Append("<style>h1{color: blue;} h2{background-color: yellow;}</style>");
strBody.Append("</head>");

strBody.Append("<body>" + strWordContent + "</body>");
strBody.Append("</html>");

string fileName = "My_Word_Dcoument.doc";

//Add headers to Response

Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader("Content-disposition", "attachment: filename=" + fileName);
Response.Write(strBody);
}

PreviousNext