Viewing Word Documents in a Webbrowser Control.

dynamic_sysop

Well-known member
Joined
Oct 1, 2002
Messages
1,039
Location
Ashby, Leicestershire.
if youve ever tried to open a Word Document in a Webbrowser or InternetExplorer , you will be aware that its not an automatic process. you will be presented with a " Download File " dialog box.
Well in i step ;) , heres my unique method of opening a Word Document in a Webbrowser...
Code:
    /// NOTE : You need word installed to run this code...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim DocViewer As New Threading.Thread(AddressOf ViewDocInWebbrowser)
        DocViewer.Start()
    End Sub

    Private Sub ViewDocInWebbrowser()
        Dim od As New OpenFileDialog()
        With od
            .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal)
            .Filter = "Word Documents|*.DOC"
            If .ShowDialog = DialogResult.OK Then
                Dim typeWord As Type = Type.GetTypeFromProgID("Word.Application")
                Dim WordApp As Object = Activator.CreateInstance(typeWord)

                Dim htmlFormat As Integer = 8
                Dim Docpath As Object() = {.FileName} /// path to a valid .Doc file.
                Dim HtmPath As Object() = {Application.StartupPath & "\WordDoc.HTML", htmlFormat} /// temp path to hold the html version of the .Doc file.

                Dim WordDocs As Object = typeWord.InvokeMember("Documents", Reflection.BindingFlags.GetProperty, Nothing, WordApp, Nothing)
                Dim doc As Object = WordDocs.GetType.InvokeMember("Open", Reflection.BindingFlags.InvokeMethod, Nothing, WordDocs, Docpath)
                doc.GetType.InvokeMember("SaveAs", Reflection.BindingFlags.InvokeMethod, Nothing, doc, HtmPath)

                WordApp.quit() /// close the instance of Word down.

                browser.Navigate(HtmPath(0)) /// load the Word Document in to the webbrowser.
            End If
        End With
    End Sub

    Private Sub browser_DocumentComplete(ByVal sender As Object, ByVal e As AxSHDocVw.DWebBrowserEvents2_DocumentCompleteEvent) Handles browser.DocumentComplete
        /// clean up temporary files...
        If IO.File.Exists(Application.StartupPath & "\WordDoc.HTML") Then
            IO.File.Delete(Application.StartupPath & "\WordDoc.HTML") /// remove the temp file.
        End If
        If IO.Directory.Exists(Application.StartupPath & "\WordDoc_files") Then
            Dim files As String() = IO.Directory.GetFiles(Application.StartupPath & "\WordDoc_files")
            Dim file As String
            For Each file In files
                IO.File.Delete(file)
            Next
            IO.Directory.Delete(Application.StartupPath & "\WordDoc_files") /// remove the temp folder.
        End If
    End Sub
included is a zipped project source.
 

Attachments

Back
Top