Embed Word in a Web Page with an Easy VB Custom Control in VB.NET

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.

Word- Documents-in-VB.NET.jpg

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. The control described in this project will display an MHT file. 

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), and 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 top of the solution is the test web site, it contains only a single web page (default) and it includes an MHT converted Word document file for testing purposes.  The bottom project is the class library with the single control included ("ShowWordMhtVb"). 

The references in the test web site are per the default configuration; the class library references include the default references but also include the following additions:  

  • System.Design
  • System.Drawing.Design
  • System.Web

Solution- Explore-in-VB.NET.jpg

Figure 2:  Solution Explorer with Both Projects Visible.
 

The Web Custom Control Project

Code:  ShowWordMhtVb.vb.

Within project, there is a single custom control provided in the example. The example is entitled, "ShowWordMhtVb.vb". 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:

  1. Imports System  
  2. Imports System.Collections.Generic  
  3. Imports System.ComponentModel  
  4. Imports System.Text  
  5. Imports System.Web  
  6. Imports System.Web.UI  
  7. Imports System.Web.UI.WebControls   
  8. <DefaultProperty("FilePath"), ToolboxData("<{0}:ShowWordMhtVb runat=server></{0}:ShowWordMhtVb>")> _  
  9. Public Class ShowWordMhtVb  
  10.     Inherits 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.
  1. #Region "Declarations"  
  2.     Private mFilePath As String  
  3. #End Region
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.
  1. #Region "Properties"   
  2.    <Category("Word Document")> _  
  3.    <Browsable(True)> _  
  4.    <Bindable(True)> _  
  5.    <Description("Select Word MHT format file.")> _  
  6.    <Editor(GetType(System.Web.UI.Design.UrlEditor),    
  7.    GetType(System.Drawing.Design.UITypeEditor))> _  
  8.    Public Property FilePath() As String  
  9.        Get  
  10.            Return mFilePath  
  11.        End Get  
  12.        Set(ByVal Value As String)  
  13.            If Value = String.Empty Then  
  14.                mFilePath = String.Empty  
  15.            Else  
  16.                Dim tilde As Integer = -1  
  17.                tilde = Value.IndexOf("~")  
  18.                If tilde <> -1 Then  
  19.                    mFilePath = Value.Substring((tilde + 2)).Trim()  
  20.                Else  
  21.                    mFilePath = Value  
  22.                End If  
  23.            End If  
  24.        End Set  
  25.    End Property  
  26. End Region  
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.

  1.  #Region "Rendering"   
  2.     Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)  
  3.         Try  
  4.             Dim sb As New StringBuilder()  
  5.             sb.Append("<iframe src=" + FilePath.ToString() & " ")  
  6.             sb.Append("width=100% height=" + Height.ToString() & " ")  
  7.             sb.Append("</iframe>")  
  8.             writer.RenderBeginTag(HtmlTextWriterTag.Div)  
  9.             writer.Write(sb.ToString())  
  10.             writer.RenderEndTag()  
  11.         Catch  
  12.             writer.RenderBeginTag(HtmlTextWriterTag.Div)  
  13.             writer.Write("Display Word MHT Control")  
  14.             writer.RenderEndTag()  
  15.         End Try  
  16.     End Sub  
  17. #End Region  
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 label and icon used as a banner and the custom control with its file path property set to point 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.


Similar Articles