Thursday, March 15, 2007

Generating word document dynamically with header, footer and page border using ASP.NET (c#)

Since Microsoft Word has good support for HTML, you can generate word document (customized) from your asp.net application very easily. First define a string type variable, strDocBody, which will contain the body of word document. Now add the page HTML to strDocBody as follow:

strDocBody = "<!-- /* Page HTML or WordML */><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>" +
"<title>Dynamic Generated Document</title>"
;

This will define xmlns properties (standreds) and title of document. Now set the document properties like layout view, zoom etc.

strDocBody = strDocBody + "<!-- /* Page layout(view) Definitions */>" +
"<!--[if gte mso 9]>" +
"<xml>" +
"<w:WordDocument>" +
"<w:View>Print</w:View>" +
"<w:Zoom>100</w:Zoom>" +
"<w:DoNotOptimizeForBrowser/>" +
"</w:WordDocument>" +
"</xml>" +
"<![endif]>";

Here "<w:View>Print</w:View>" represents the Print Layout View and "<w:Zoom>100</w:Zoom>" represents the page zoom. Now add the style section. This section will contain the page style properties like page size, header id, footer id, page border, margins, font family etc.

strDocBody = strDocBody +"<!-- /* Page Style Definitions */>" +
"<style> @page Section1 " +
" {size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt; " +
"margin:0.75in 0.50in 0.75in 0.50in ; " +
"mso-header-margin:.5in; " +
"mso-footer-margin:.5in; mso-paper-source:0;}" +
"div.Section1" +
" {page:Section1;}" + "p.MsoFooter, li.MsoFooter, div.MsoFooter{margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" +
"p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" +
"-->" +
"</style>" +
"</head>";


The size of page is defined as size:8.5in 11.0in; and mso-first-footer:ff1; defines the first page footer if you select the option Different first page from menu File > Page Setup > Layout tab. mso-footer: f1; defines footer for all pages. The same way you can define first page header and header for all pages as mso-header: h1;. Other header and footer properties are defined in MsoFooter, MsoHeaderer classes as shown in sample code. border:solid navy 2.25pt; defines the page border and padding:24.0pt 24.0pt 24.0pt 24.0pt; defines page border position.
Now add the actual body of the document and header and footer.

strDocBody = strDocBody + "<!-- /* Actual document body */>" +
"<body lang=EN-US style='tab-interval:.5in'>" +
"<div class=Section1>" +
"<h1>This is my Heading</h1>" +
"<h2>This is my Sub Heading</h2>" +
"<p style='color:navy;'> This is blue text</p>" +
"<p style='font-weight:bold; color:green;'><u> This is green bold underlined text </u></p>" +
"<p style='color:red'><I>" +
DateTime.Now + "</I></p>" +
//my image
"<img img width=217 height=162 id='myImg' src='C:/WINDOWS/Web/Wallpaper/Autumn.jpg'>" ;




strDocBody = strDocBody + "<!-- /* Header and footer */>" +
"<!--[if supportFields]>" +
"<div style='mso-element:header' id=h1><p class=MsoHeader><span style='mso-tab-count:4'></span><span style='mso-field-code: PAGE '></span> </p></div>" +
"<div style='mso-element:footer' id=f1> " +
"<p class=MsoFooter style='border:none;mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'</p> " +
"Page <span style='mso-field-code: PAGE '><span style='mso-no-proof:yes'>1</span></span> " +
" <span style='mso-tab-count: 14'> <span style='mso-field-code:
NUMPAGES '></span> " +
" </p></div><![endif]-->" +
"</div></body></html>";


Now force this content to be downloaded as your word document using response.

//Force this content to be downloaded as a Word document
Response.AddHeader("Content-Type", "application/msword");
//filename specify the name of word document of your choice
Response.AddHeader("Content-disposition", "attachment; filename=myWordDoc.doc");
Response.Charset = "";
Response.Write(strDocBody);


Add the whole content on page load event or button click event as example code.

Example:

protected void Page_Load(object sender, EventArgs e)
{
string strDocBody;

try { strDocBody = "<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>" + "<title>Dynamic Generated Document</title>";

strDocBody = strDocBody + "<!--[if gte mso 9]>" + "<xml>" + "<w:WordDocument>" + "<w:View>Print</w:View>" + "<w:Zoom>100</w:Zoom>" + "<w:DoNotOptimizeForBrowser/>" + "</w:WordDocument>" + "</xml>" + "<![endif]-->";

strDocBody = strDocBody + "<style> @page" + "{size:8.5in 11.0in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt;" + " margin:0.75in 0.50in 0.75in 0.50in ; " + " mso-header-margin:.5in; " + " mso-footer-margin:.5in; mso-paper-source:0;}" + " div.Section1" + " {page:Section1;}" + "p.MsoFooter, li.MsoFooter, div.MsoFooter{margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" + "p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}" + "-->" + "</style>" + "</head>";

strDocBody = strDocBody + "<body lang=EN-US style='tab-interval:.5in'>" + "<div class=Section1>" + "<h1>This is my Heading</h1>" + "<h2>This is my Sub Heading</h2>" + "<p style='color:navy;'> This is blue text</p>" + "<p style='font-weight:bold; color:green;'><u> This is green bold underlined text </u></p>" + "<p style='color:red'><I>" + DateTime.Now + "</I></p>" + "<img img width=217 height=162 id='myImg' src='C:/WINDOWS/Web/Wallpaper/Autumn.jpg'>" + "<!--[if supportFields]>" + "<div style='mso-element:header' id=h1><p class=MsoHeader><span style='mso-tab-count:4'></span><span style='mso-field-code: PAGE '></span> </p></div>" + "<div style='mso-element:footer' id=f1> " + "<p class=MsoFooter style='border:none;mso-border-bottom-alt:solid windowtext .75pt;padding:0in;mso-padding-alt:0in 0in 1.0pt 0in'><o:p> </o:p></p> " + "Page <span style='mso-field-code: PAGE '><span style='mso-no-proof:yes'>1</span></span> of <span style='mso-field-code: NUMPAGES '></span>" + " <span style='mso-tab-count: 12'> <span style='mso-field-code: DATE '></span> " + " </p></div><![endif]-->" + "</div> </body> </html> ";

//Force this content to be downloaded as a Word document

Response.AddHeader("Content-Type", "application/msword");

Response.AddHeader("Content-disposition", "attachment; filename=mydoc.doc");

Response.Charset = ""; Response.Write(strDocBody);


}

catch (Exception ex)

{

Response.Write(ex.Message);

}

}

There is a trick to download your aspx page as word document without coding so much but as the aspx. If you remove the closing body and html tag from the above program and define first three blocks i.e page HTML, page layout definitions and style definitions on the page load event then your aspx page contents will be downloaded as word document. Other contents along with header and footer will defined as the aspx page. You can find it in the next post.

13 comments:

huislaw said...

hi Arun,
Thanks for the code!

Unknown said...

Hi Arun,
I tried your code but i am getting two page footers at the last page!!!

Could you please help me with this.

Unknown said...

Hi,

For some reason the text that I enter for the footer also gets shown in the document itself.

Also I would like the footer to be shown on the first page only. I tink i have to use mso-first-footer but not sure how.

Could you please help me.

Thanks for you time

Damien

Arun Kumar said...

Please mail your questions to my mailbox at arunkoslia@gmail.com

Unknown said...

That was a nice code ..But I am facing some problem with the header I have changed the header from page numbers to some text , then the header is repeating twice for the first page..can you help me in this issue...
Thnx in advance

Sunil said...

I have tried implementing your code but its displaying header and footer properly but they are once again displaying in detail section.
Can you plz help me in this regard.

Unknown said...
This comment has been removed by the author.
Neelima said...

Hi,

I have the same problem, I have used the same code with some changes,but I'm getting the header and footer once again in the last page...........can some help me in this regard...!!!

Neelima

Neelima said...

I'm using the same code in sharepoint...I have read that the repeatance of header and footer is a limitation, I don't know if there is any solution for this....you can go through the folowing link for reference.......

http://www.pbdr.com/ostips/wordfoot.htm

The above link say that:
There is a draw back to this solution in that the text that you want to appear in the footer needs to appear somewhere in the body of the main document, this was a limitation I much preferred to the multiple files option. I opted to putting the text at the end of the document and its not very intrusive.

$rinivas Varma Mutyam said...

hi Arun,

The code is good.. It is displaying header and footer properly ..But they are once again displaying at the end of the body i.e., just before the footer of last page.

Can you help me to fix this issue ?

Thanks,

svemir said...

To make the header and footer on the first page be different from the others, in addition to what is specified above, you also need to add this somewhere under @page Section1:

mso-title-page:yes;

Alex said...

For this operation I advise to use-how to fix a corrupted word document,it has free status as far as I can see,also application has many facilities,utiltiy can easily perform these operations and fix recover doc from any damaged document in Microsoft Word format,open your damaged file and press Analyze for fix read only documents in Office,allows to avoid Word documents is unreadable fix,will recover only plain text, without any images, graphics and formatting,export the contents into another document in Microsoft Word format.

raj said...

how to apply values to footer (left ,center and right ) in correct position. Issue is footer positioning