Writing HTML Content to the Screen in Word Document Format In a Server

There are many commercial products available to allow you to create a true Word document on the fly in a server. Since Office automation is not really an option (Microsoft doesn't recommend it; see Considerations for server-side Automation of Office) you were generally stuck with those components (most of them just a pretty wrapper for old COM objects). Well, that is, until now.

If you still need to write something very specific to Word, then you should still use one of the better components out there, but if your goal is a simple DOC representation of some HTML then you might find this way to be somewhat simpler.

Changing the mime-type to fool the browser is the first thing you should do. This is easy enough and can be done with the following code (but make sure to clear the buffer before):

Response.Clear();
Response.ContentType = "application/msword";

But that's not enough if you are outputting a part of an HTML document (mostly something that you generated yourself by means of a StringBuilder object or an XSLT translation). Word would simply take that HTML and display it in the contents of the document, tags and everything. Not the effect we are going for!

So the next step is to make the Word recognize that it's dealing with HTML. Since we already changed the content type we can do that with the following code:

Response.Write (@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");

Now we can output whatever we need by simply using Response.Write. However that might not be enough, because if the user's settings are set to "ask before open" and the user does in fact save the document before opening, he/she will in fact save this doc as an .aspx page. Again, NOT the effect we are going for. To fool the browser into thinking that it is delivering a file and not an .aspx page the following code would do the trick:

Response.AddHeader("Content-Disposition","inline; filename="CSCornerTest.doc");

Note: Keep in mind that this code would need to be added right after you change the content type.

Also, if you use any CSS styles then make sure they are inline, because the ones that come from .css files will not be automatically included.

Well, that should do the trick. Happy programming!

P.S. Special thanks go to Keith Marran.