Thursday, April 12, 2007

How to dynamically generate MS Word Document using ASP

Listen to this articleListen to this article

ASP or "Active Server Pages" has the ability to dynamically generate MS Words File. For those, who are familiar with ASP (the legacy technology of ASP.NET), this article will help you on how to do it. It's simple and very easy. Don't need to use any extra component.

As you can see below, the first thing we need to do is to set the correct content type of your documents which is "application/msword".
Next, is to give the ms word file name, for example technoguide.doc .

Then, write whatever your want as a document body.

To create body, style and format your MS Word file, you are freely to use HTML codes and CSS styles in your document.


<%
Response.ContentType = "application/msword"
Response.AddHeader "Content-Disposition", "attachment;filename=technoguide.doc"
response.Write("mytechnoguide.blogspot.com : <a href=""http://mytechnoguide.blogspot.com"">My Techno Guide</a><br>" & vbnewline)
response.Write("<h1>Generate Online MS Word using ASP</h1>")
response.Write ("<div style=""padding:4px; font:11px arial"">We can format our MS word using CSS Style and HTML Codes.</span>")
%>



Instead of using simple HTML and CSS style, to further enhance your MS Word format, used mso style definitions. Below is the example on how to use do it:


<%
Response.ContentType = "application/msword"
Response.AddHeader "Content-Disposition", "attachment;filename=technoguide.doc"
Response.write("<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'>" & _
"<head><>My Technoguide MS Word Documents Title</title>")

'The setting specifies document's view after it is downloaded as Print
'instead of the default Web Layout
Response.write("<!--[if gte mso 9]>" & _
"<xml>" & _
"<w:WordDocument>" & _
"<w:View>Print</w:View>" & _
"<w:Zoom>90</w:Zoom>" & _
"<w:DoNotOptimizeForBrowser/>" & _
"</w:WordDocument>" & _
"</xml>" & _
"<![endif]-->")

' Write mso style definitions class in style tag, style class can be divided by
' sections, in this example, i used Section1
' Then call your style class (Section1) in div tag

Response.write("<style>" & _
"<!-- /* Style Definitions */" & _
"@page Section1" & _
" {size:8.5in 11.0in; " & _
" margin:1.0in 1.25in 1.0in 1.25in ; " & _
" mso-header-margin:.5in; " & _
" mso-footer-margin:.5in; mso-paper-source:0;}" & _
" div.Section1" & _
" {page:Section1;}" & _
"-->" & _
"</style></head>")

Response.write("<body lang=EN-US style='tab-interval:.5in'>" & _
"<div class=Section1>" & _
"<h1>Tips and Tricks from mytechnoguide</h1>" & _
"<p style='color:red'><I>" & _
I love my Technoguide & "</I></p>" & _
"</div></body></html>")

%>