Blue Theme Orange Theme Green Theme Red Theme
 
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Office Interop » An Easy Way to Embed Word in a Web Page

An Easy Way to Embed Word in a Web Page

This article describes an approach to displaying word documents within a web page using a simple custom server control.

Author Rank:
Total page views :  30695
Total downloads :  1383
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
TestWordInWeb.zip
 
Become a Sponsor

Introduction

This article describes an approach to displaying word documents within a web page using a simple custom server control. There are several approaches that may be used to get a word document into a web page, but that the one demonstrated in this example appears to be the easiest and most reliable method of delivery that I have encountered in terms of actually embedding the document. Some alternative approach will download the document to the user's machine and open it in Word or the Word Viewer is it is installed.



Figure 1.  Embedding and Displaying Word Documents

The approach used in this example is based upon conversion of the Word document into an MHT file. This conversion is accomplished by using the Word file Save As option and selecting the MHT file type prior to saving. The MHT file type is a single web page with all content embedded. 

Getting Started.

There are two solutions included with this download, one is web custom control library containing a single custom control used to render out the Word document (in MHT format), the other is a test web site used to display a document through the use of the control.

Figure 2 (below) shows the solution explorer for the project. The project appearing at the bottom of the solution is the test web site, it contains only a single web page (default) and it includes a converted Word document file for testing purposes. The top project is the web custom control library with the single control included ("ShowWordMht"). 

The references in the test web site are per the default configuration; the custom control library references include the default references but also includes System.Design.



Figure 2.  Solution Explorer with Both Projects Visible 

The Web Custom Control Project

Code:  ShowWordMht.cs

Within the web custom control project, there is a single custom control provided in this example. The example is entitled, "ShowWordMht.cs". The code for the project is very simple and should take very little time to implement. The control code starts out with the default imports and class declaration:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace CCWordMht

{

 

    [ToolboxData("<{0}:ShowWordMht runat=server></{0}:ShowWordMht>")]

    public class ShowWordMht : WebControl

    {

After the class declaration, a declarations region was added and a single local member variable was defined and included within that region. The local member variable is used to retain the path to the Word document loaded into the control.

#region "Declarations" 

private string mFilePath;

#endregion

The next bit of code in the class is contained in a new region called "Properties". Within this region is a single property entitled, "FilePath". The property is used to provide public member access to the file path member variable. The attributes associated with this property indicate that the property is visible (Browsable) in the property editor, defines the property editor category under which to show the property in the editor, and provides the text used to describe the property which viewed in the property editor (Description). The editor defined specifies an association between this property and the URL Editor; when the developer using the control edits the property at design time, the URL editor will be displayed to allow the developer to navigate to and select a target file based using this editor. The System.Design reference is needed to support this portion of the design.

#region "Properties"

 

[Category("Source File")]

[Browsable(true)]

[Description("Set path to source file.")]

[Editor(typeof(System.Web.UI.Design.UrlEditor),

typeof(System.Drawing.Design.UITypeEditor))]

public string FilePath

{

    get

    {

        return mFilePath;

    }

    set

    {

        if (value == string.Empty)

        {

            mFilePath = string.Empty;

        }

        else

        {

            int tilde = -1;

            tilde = value.IndexOf('~');

            if (tilde != -1)

            {

                mFilePath = value.Substring((tilde + 2)).Trim();

            }

            else

            {

                mFilePath = value;

            }

        }

    }

}   // end FilePath property 

 

#endregion

Notice that in the set side of the property, the code is written to remove the tilde from in front of the file path if the tilde is present. If the tilde is left intact after setting the property to point to a file using the URL Editor, the tilde would otherwise be included in the HTML rendered to the page and the file would not found. It is necessary to strip this character from the file path in order to use the URL Editor to set this property at design time.

The last bit of code needed to finish the control is contained in a region called "Rendering". This region contains a single method used to override the RenderContents method. Within RenderContents, a string builder is created and then populated with the HTML needed to render the control on a page. In this instance, the simplest way to display the MHT file is through the use of an IFrame. Looking at the string builder, note that the IFrame contains the source property which points to the file path property added earlier in this project. Further, the width and height of the IFrame is set such that the width of the control is fixed at 100% while the height of is set to the actual height of the control. After the string builder is populated, the content is dumped into a div. The entire control is constructed within a try catch block, if the try fails, the catch block will render out "Display Word MHT Control" into a box on the page in lieu of showing the control. When the control is first added to the page, it does not point to a file and so the try will fail, this prevents an error from occurring during that initial placement of the control.

#region "Rendering" 

protected override void RenderContents(HtmlTextWriter writer)

{

    try

    {

        StringBuilder sb = new StringBuilder();

        sb.Append("<iframe src=" + FilePath.ToString() + " ");

        sb.Append("width=100% height=" + Height.ToString() + " ");

        sb.Append("</iframe>"); 

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write(sb.ToString());

        writer.RenderEndTag();

    }

    catch

    {

        // with no properties set, this will render "Display Word MHT

        // Control" in a a box on the page

        writer.RenderBeginTag(HtmlTextWriterTag.Div);

        writer.Write("Display Word MHT Control");

        writer.RenderEndTag();

    }  // end try-catch

}   // end RenderContents
 

#endregion 

The Test Web Project

Code:  Default Page

The default page included in the web project is provided to serve as a test bed for the control. The page contains only a panel used as a banner and the custom control with its file path property also pointing to the MHT file. The MHT file was added to the web site content and is also included in the web project. When this site is viewed, the control will display the Word document in the defined area. 

Summary.

This article demonstrates an approach that may be used to develop a custom control through which Word documents may be embedded into a web page. The purpose of the control is to allow the Word document to be included within a web page as opposed to the alternative of opening the document into a separate page or evoking a download to the document for local viewing in Word or the Word Viewer. Naturally, the code included in the custom control could be added directly into any page and the same effect could be achieved, however, by adding the code once into a custom control, the developer need only drop the control into the form and set the file path and dimensions to display Word documents without repeating the manual addition of the code each time it is needed.

The control may be used with Word doc files, however without the conversion to MHT format, the browser will attempt to download the file locally for viewing. If the intent is to embed rather than download, this approach is valid.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
TestWordInWeb.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
Become a Sponsor
 Comments
View word doc. in silverlight 2.0 by Niya On February 25, 2009
Hi, i am a Newbie :( Need a help... i m using silverlight 2.0, n hv to display a word or excel document inside the silverlight page,, can u help me in this Thanks, Alec_
Reply | Email | Delete | Modify | 
Work for FireFox by Jason On March 5, 2009
Is it possible to get this to work with firefox?
Reply | Email | Delete | Modify | 
Re: Work for FireFox by Scott On March 12, 2009
I don't see why not; once converted to MHT, the word document is pretty much html.
Reply | Email | Delete | Modify | 
sdf by dushi On May 12, 2009
Sf
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.