Tech Support Websites

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 1 September 2010

HOW TO dynamically generate a Word document with custom header & footer

Posted on 09:40 by Unknown
Way back in 2004, a project I was working on required a web page to be exported as a Word document (.DOC). Without relying on any components, I utilized the Office XML & HTML technique to implement this feature. I posted my sample on CodeProject to seek feedback. Over the years, I've received some generous comments & feature requests. Many wanted to know how to add a header & footer to the dynamically generated Word document.

With the help of the Microsoft Office HTML and XML Reference, I devised a hack to add a lacklustre header and/or footer. Some folks wanted to customize the contents of the header & footer but when they tried with my hack that offered limited functionality, the header/footer text showed up in the document body to their annoyance. This July, an ingenious developer posted a hack that can overcome this problem, in the Comments section of my CodeProject article. His practical workaround was to pack the duplicating header/footer text inside a table & push it off the page's dimensions with CSS.



For those interested, I adapted his VB.NET snippet into a complete sample in C#. Instead of using a ASP.NET webform as I did in the original code sample in the article, I have used a Generic Handler (.ASHX) to dynamically generate a Word document as it is more suitable for this purpose.

<%@ WebHandler Language="C#" Class="Handler" %>


using System;
using System.Web;
using System.Text;

public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
StringBuilder sbTop = new System.Text.StringBuilder();
sbTop.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'>
<head><title></title>

<!--[if gte mso 9]>
<xml>
<w:WordDocument>
<w:View>Print</w:View>
<w:Zoom>90</w:Zoom>
<w:DoNotOptimizeForBrowser/>
</w:WordDocument>
</xml>
<![endif]-->


<style>
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;
}
<style>

<!-- /* Style Definitions */

@page Section1
{
size:8.5in 11.0in;
margin:1.0in 1.25in 1.0in 1.25in ;
mso-header-margin:.5in;
mso-header:h1;
mso-footer: f1;
mso-footer-margin:.5in;
}


div.Section1
{
page:Section1;
}

table#hrdftrtbl
{
margin:0in 0in 0in 9in;
}
-->
</style></head>

<body lang=EN-US style='tab-interval:.5in'>
<div class=Section1>
<h1>Time and tide wait for none</h1>
The quick brown fox jumps over the lazy dog
...
...


<table id='hrdftrtbl' border='1' cellspacing='0' cellpadding='0'>
<tr><td>
<div style='mso-element:header' id=h1 >
<p class=MsoHeader style='text-align:center'>Confidential</p>
</div>
</td>
<td>
<div style='mso-element:footer' id=f1>
<p class=MsoFooter>Draft
<span style=mso-tab-count:2'></span><span style='mso-field-code:"" PAGE ""'></span>
of <span style='mso-field-code:"" NUMPAGES ""'></span></p></div>
/td></tr>
</table>
</body></html>
");

string strBody = sbTop.ToString();
context.Response.AppendHeader("Content-Type", "application/msword");
context.Response.AppendHeader("Content-disposition", "attachment; filename=HeaderFooter.doc");
context.Response.Write(strBody);
}


public bool IsReusable
{
get
{
return false;
}
}
}

To clearly understand the code you would have to download the Microsoft Office HTML and XML Reference which is in .CHM format (as there is no online version of it) & look up the exact meanings of custom CSS properties.

Related links:

HOW TO implement "Download as Word/Excel" functionality through a web page
HOW TO send an email with a Word or Excel file attachment built on the fly
HOW TO generate a Word document dynamically with user submitted text formatted with Free Text Box
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in ASP.NET, CSS, HOWTO, HTML | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Windows 8 keyboard shortcuts
    Win + X   - context menu to access common features like Control Panel, Task Manager, File Explorer, Programs & Features, Run, Search etc...
  • What is the difference between Browser Mode & Document Mode in IE
    If you're a web developer and your job actively involves building web pages that work the same in all browsers including the last three ...
  • My 30-day personal project - watch 100 hours of Pluralsight videos
    Inspired by Matt Cutts' 30-day challenges , I plan to watch 100 hours of Pluralsight online videos to get up-to-date with current ...
  • Archive tweets & favorites with Google Reader
    There are numerous ways to archive tweets but rather than use yet another tool, I prefer using Google Reader to preserve the tweets I mark ...
  • TWIL - Week #3
    This Week I Learned: New Azure VM Image Templates include SQL Server, BizTalk Server, and SharePoint Server (2013?) images . This can be han...
  • Dashboard-like info with Browser tabs, Windows 7 Taskbar tabs
    Browser tabs & Windows 7 Taskbar tabs are turning self-aware.  This is how my browser looked the other day: I had the summary of all tha...
  • The State Of HTML5 Video
    Key points from the  The State Of HTML5 Video  report by LongTailVideo (last updated on April 19, 2012): 75% of the desktop & mobile bro...
  • Azure in Pictures - overview of Windows Azure Features, Services and Common Uses
    Download the Windows Azure Poster in PDF format (1.1MB)
  • Indian comparison shopping sites
    Did you know, India has 120 million Internet users & the Indian e-commerce market is worth $7 billion ?  Travel accounts for over 80 per...
  • Things to consider before settling on a JavaScript Library or jQuery plugin for your project
    In the article, Which JavaScript Library Should I Pick? , Pamela Fox has listed some practical points to consider before you settle on a Jav...

Categories

  • AJAX
  • Android
  • APIs
  • App
  • ASP
  • ASP.NET
  • ASP.NET-MVC
  • Azure
  • Azure SQL Database
  • AzureInPictures
  • Bing
  • Book Review
  • Bookmarklet
  • Browsers
  • C#
  • chart
  • Chrome
  • Cloud
  • CSS
  • CSS3
  • DidYouKnow
  • E-Commerce
  • Excel
  • FB
  • Fiddler
  • Firefox
  • Gadgets
  • GeoLocation
  • GMail
  • Google
  • Google Docs
  • Google Reader
  • Health
  • Hotmail
  • HOWTO
  • HTML
  • HTML/CSS
  • HTML5
  • Humor
  • Hyderabad
  • IE
  • IIS
  • India
  • Internet
  • IT
  • Javascript
  • jQuery
  • JSON
  • JSONP
  • Laptop
  • Learning Resources
  • Lists
  • Map
  • Metrics
  • Microsoft
  • miscellaneous
  • Mobile
  • NAPA
  • Office365
  • Opera
  • PDF
  • Performance
  • Personal
  • PHP
  • PM
  • PowerShell
  • Privacy
  • Programming
  • Rant
  • Safari
  • Science
  • Search Engines
  • SearchEngines
  • Security
  • SEO
  • Sharepoint
  • SharePoint2013
  • Silverlight
  • Software Engineering
  • Solutions
  • SQL Azure
  • SQL Server
  • TFS
  • Tip
  • Tips
  • Tools
  • Tools/Utilities
  • Trivia
  • TWIL
  • Twitter
  • UX
  • VM
  • VS.NET
  • VS2010
  • VS2012
  • WCF
  • WebApps
  • Websites
  • WF
  • Windows Phone
  • Windows7
  • Windows8
  • Word
  • WP7
  • WPF

Blog Archive

  • ►  2013 (112)
    • ►  October (16)
    • ►  September (14)
    • ►  August (8)
    • ►  July (8)
    • ►  June (13)
    • ►  May (12)
    • ►  April (12)
    • ►  March (8)
    • ►  February (15)
    • ►  January (6)
  • ►  2012 (127)
    • ►  December (11)
    • ►  November (14)
    • ►  October (13)
    • ►  September (14)
    • ►  August (16)
    • ►  July (16)
    • ►  June (6)
    • ►  May (5)
    • ►  April (11)
    • ►  March (12)
    • ►  February (7)
    • ►  January (2)
  • ►  2011 (98)
    • ►  December (5)
    • ►  November (2)
    • ►  October (5)
    • ►  September (7)
    • ►  August (7)
    • ►  July (15)
    • ►  June (10)
    • ►  May (7)
    • ►  April (8)
    • ►  March (10)
    • ►  February (11)
    • ►  January (11)
  • ▼  2010 (163)
    • ►  December (14)
    • ►  November (19)
    • ►  October (19)
    • ▼  September (15)
      • HOW TO monitor performance and availability status...
      • India ranks fourth in Internet usage
      • Discover patterns with Wordle
      • jQuery on CDN - Usage Stats
      • Your digital camera can land you in trouble
      • Using ASP.NET? You MUST read this
      • Job ad in HTML source code
      • AJAX is like steriods for web apps
      • Think Mobile First
      • See what Google is suggesting - II
      • HOW TO prevent 3rd-party browser extensions from b...
      • 15 years of Internet Explorer
      • Microsoft SharedView - free document & screen shar...
      • HOW TO perform mouse actions with the keyboard
      • HOW TO dynamically generate a Word document with c...
    • ►  August (18)
    • ►  July (17)
    • ►  June (20)
    • ►  May (17)
    • ►  April (19)
    • ►  March (5)
Powered by Blogger.

About Me

Unknown
View my complete profile