Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » Embed Word in a Web Page with an Easy VB Custom Control

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


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

Author Rank:
Total page views :  37414
Total downloads :  1169
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
EmbedWordVB.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. 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

 


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:

Imports System

Imports System.Collections.Generic

Imports System.ComponentModel

Imports System.Text

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls 

 

<DefaultProperty("FilePath"), ToolboxData("<{0}:ShowWordMhtVb runat=server></{0}:ShowWordMhtVb>")> _

Public Class ShowWordMhtVb

    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. 

#Region "Declarations"

 

    Private mFilePath As String

 

#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.

#Region "Properties" 

 

    <Category("Word Document")> _

    <Browsable(True)> _

    <Bindable(True)> _

    <Description("Select Word MHT format file.")> _

    <Editor(GetType(System.Web.UI.Design.UrlEditor),  

    GetType(System.Drawing.Design.UITypeEditor))> _

    Public Property FilePath() As String

        Get

 

            Return mFilePath

 

        End Get

 

        Set(ByVal Value As String)

 

            If Value = String.Empty Then

                mFilePath = String.Empty

            Else

 

                Dim tilde As Integer = -1

                tilde = Value.IndexOf("~")

 

                If tilde <> -1 Then

                    mFilePath = Value.Substring((tilde + 2)).Trim()

                Else

                    mFilePath = Value

                End If

 

            End If

 

        End Set

 

    End Property 

 

#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. 

#Region "Rendering" 

 

    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)

 

        Try

 

            Dim sb As 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

 

            writer.RenderBeginTag(HtmlTextWriterTag.Div)

            writer.Write("Display Word MHT Control")

            writer.RenderEndTag()

 

        End Try

 

    End Sub 

 

#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.


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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
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.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
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
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
ASP.Net 4 Hosting is here
Become a Sponsor
 Comments
handle embedded documents by Ankur On July 24, 2007
I am writting a tool in which i want to convert a word to html cleaning the extra codes. I am not getting a clue how to handle embedded documents in the word. can i access the embedded documents properties using VB.NET code
Reply | Email | Delete | Modify | 
This code not working with my Master Page by Vin On August 11, 2007
Great code, but 1 problem. When I put it in a Content Placeholder in my content page, the footer from my Master Page never gets displayed. Any ideas why?
Reply | Email | Delete | Modify | 
Re: This code not working with my Master Page by Vickie On September 5, 2007
Did you figure this out. I am having the same issue and do not why.
Reply | Email | Delete | Modify | 
Waste of My Time by Amy On March 18, 2009
Downloaded, reviewed, I'm new to this 1. Can't open the project locally - Not Trusted - moved to my vb projects folder no help - no pathing just straight file 2. Parser Error Message: Could not load file or assembly 'WordShow' or one of its dependencies. The system cannot find the file specified. This wasted about 2 hours of my time - if you can't put the full instructions up - don't bother putting partial stuff
Reply | Email | Delete | Modify | 
Re: Waste of My Time by Scott On March 18, 2009
I just downloaded it, opened the website and viewed the default page in the browser.  It works fine; rather than getting frustrated you could have just asked for some help with it.  If you'd like to get it running email me with a description of what you did and I will help you sort it out.
Reply | Email | Delete | Modify | 
Can it be used for DOCX? by Steve On March 17, 2010
Hi Scott,
Wondering how to get this to use a docx file from a url location?
I need something to show a word document hosted from within another site.
Any ideas?
Reply | Email | Delete | Modify | 
aSDF by watches On July 11, 2010
And The louis vuitton handbags attach much importance on the material for metal part, such as zipper would not be easy for the paint to drop down. Also, Each Monogram Shearling has its own hiding number from original factory. And the purse’s tool life is very good. Additionally, it has particular paint vehicle. It is reported that that layer deep dying Monogram Sude Embossed possesses sole patent. Even the public relationship personnel can not elaborate this kind of paint vehicle. Only the general factory has Monogram Suede material and techniques.
Reply | Email | Delete | Modify | 
lv by watches On July 11, 2010
The Ambre lv collection by itself is one of the most copied products on the market nowadays. If you like beautiful Louis vuitton bags , then you already know that owning a louis vuitton bag is considered to be the essence of wealth and sophistication. louis vuitton by itself will show you how popular and desired the collection is.
Reply | Email | Delete | Modify | 
viagra by watches On July 11, 2010
The word Viagra is synonymous to strong penile erection in the sexually enlightened world community. Business giants have already sensed the pulse of ED market and challenged Viagra online with equally efficient erectile dysfunction treatments. Not that the small fishes in the market are sitting idle...the market is flooded with many generic versions of branded ED pills along with those called Herbal Generic Cialis .
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.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.