WPF中的WebBrowser.DocumentText属性

时间:2016-11-17 15:03:31

标签: wpf vb.net pdf ms-word webbrowser-control

我有一个浏览器控件,将使用Text&情节等 我在浏览器控件中看起来很好。

现在我想将浏览器内容导出到word文件中它可以导出为PDF / HTMl / Doc等

这适用于Windows窗体。我使用WebBrowser1.DocumentText属性并将其写入文件等。这是命令:

(System.IO.File.WriteAllText(tempFileName, WebBrowser1.DocumentText)

不幸的是,WebFrowser.DocumentText属性在WPF中不再可用。我该如何解决这个问题?

以下是表单的代码:

Imports System.Drawing
Imports Microsoft.Office.Interop.Word
Imports System.Windows.Forms
Imports System.IO


 Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        ' save the document as html, mhtm (embedded), document or pdf
        If dlgSaveDoc.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            ' create a temp file of the web browser document
            Dim tempFileName As String
            tempFileName = System.IO.Path.GetTempPath() & "\" & Now.ToString().Replace(":", "") & "_RepGen" & ".html"
            System.IO.File.WriteAllText(tempFileName, WebBrowser1.DocumentText)

            ' load temp file into word
            Dim oWord As Microsoft.Office.Interop.Word.Application
            Dim oDoc As Microsoft.Office.Interop.Word.Document
            oWord = CreateObject("Word.Application")
            Try
                ' for debug, show word
                oWord.Visible = True

                oDoc = oWord.Documents.Open(tempFileName)
                Try
                    ' depending on the file type (extension), set the save format
                    Dim sf As WdSaveFormat
                    Dim ext As String = Path.GetExtension(dlgSaveDoc.FileName).ToUpper()
                    If ext.StartsWith(".HTM") Then sf = WdSaveFormat.wdFormatHTML
                    If ext.StartsWith(".MHT") Then sf = WdSaveFormat.wdFormatWebArchive
                    If ext.StartsWith(".DOC") Then sf = WdSaveFormat.wdFormatXMLDocument
                    If ext.StartsWith(".PDF") Then sf = WdSaveFormat.wdFormatPDF

                    ' save the file from word
                    oDoc.SaveAs2(dlgSaveDoc.FileName, sf)
                Finally
                    oDoc.Close()
                    oDoc = Nothing
                End Try
                oWord.Quit()
            Finally
                oWord = Nothing
                ' cleanup
                If File.Exists(tempFileName) Then File.Delete(tempFileName)
            End Try
        End If
    End Sub

2 个答案:

答案 0 :(得分:1)

这很好......甚至Plots等也没问题:

我用于WPF:

Dim tempFileName As String = "E:test.doc 
Dim doc As Object = browser.Document
Dim htmlText = doc.documentElement.InnerHtml


System.IO.File.WriteAllText(tempFileName, htmlText)

而不是(对于winforms)

System.IO.File.WriteAllText(tempFileName, WebBrowser1.DocumentText)

答案 1 :(得分:0)

首先添加COM引用Microsoft HTML Object Library:

Screenshot of references

然后,您将能够查看使用mshtml

Private Function GetPageContent(ByVal wb As WebBrowser) As String
    Return DirectCast(wb.Document, mshtml.HTMLDocumentClass).body.innerHTML
End Function