Ganesh Atkale
Ganesh Atkale

Reputation: 19

Render HTML Code on MS Word File (.docx) - File getting corrupted

Below is the code. What are the changes we need to do.

HttpContext context = HttpContext.Current;
    context.Response.Clear();
    context.Response.AppendHeader("content-disposition", "attachment;filename=" + strFileName + ".docx");
    context.Response.Charset = "";
    context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    var stringWriter = new StringWriter();
    stringWriter.Write(strContent);
    var htmlWriter = new HtmlTextWriter(stringWriter);
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
    HttpContext.Current.Response.Write(oHtmlTextWriter);
    context.Response.Write(stringWriter.ToString());
    context.Response.End();

Upvotes: 0

Views: 5251

Answers (1)

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

You can't simply write out HTML, give it a .docx file name extension and expect Word to correctly open that document. A .docx file needs to be a valid Office Open XML package, which basically is a zip container with various XML files in it (you can easily see that by renaming a .docx document to .zip and then open it using a standard zip tool).

What you can do now to fix the problem and get a valid Word file:

  • Instead of HTML, create a valid docx file using Microsoft's Open XML SDK. There a samples included with the SDK that show you how to create Word documents with it.
  • If you can't change from creating HTML you are also able to embed HTML into a Word document using a so-called altChunk. This is described in another answer here.
  • Depending on the content that you generate, there might also be the possibility to create a template Word document, where you only need to fill placeholder. Such a solution could e.g. be build around Content Controls and Custom XML. Then you only need to replace a single XML file in the docx package to fill your document. A basic tutorial for that is available here.

Upvotes: 1

Related Questions