posted on Tuesday, December 29, 2009 6:36 PM by Obi

How to export Telerik's RAD Editor to MS Word

I am currently working with Telerik’s RAD Editor server control for ASP.Net.
Needless to say, the control provides a plethora of features for styling, formatting and such.

For all intents and purposes it’s a WYSIWIG tool and you can do practically anything what you can with MS Word. All said and done, however, it does not provide any out-of-the-box functionality to convert the editor's content to MS Word.

What you can do though is to save the editor content as an .html file, read the entire content into a string and open it in MS Word. If you want to edit the .html content, you can even go as far as doing a simple string replacement.

Here’s the code that does just that…
Private folderPath As String = "C:/Report/"
Private template As String = "MyMemo.DOT"

Protected Sub SaveRADContentAsHTML()
Try
' CREATE WORD DOCUMENT
Dim WordApp = CreateObject("word.application")
Dim WordDoc = WordApp.Documents.Open(Server.MapPath(folderPath & template))
WordApp.Application.Visible = False
Dim wordDocPath As String = Server.MapPath(folderPath)
If Not File.Exists(Server.MapPath(folderPath & " MyMemo.html")) Then
WordDoc.SaveAs(wordDocPath & "MyMemo.html")
End If

WordDoc.Close()
WordApp.Quit()

WordDoc = Nothing
WordApp = Nothing
Catch ex As Exception
Throw ex
End Try
End Sub

Private Sub btnReplaceWord_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReplaceWord.Click
Dim wordDocPath As String = Server.MapPath(folderPath)
Dim inputText As String = String.Empty
Dim sTemp As String = String.Empty
Try
inputText = ReadFile(wordDocPath & "MyMemo.html")
sTemp = inputText.Replace("Purpose~1", radEditor1.Content) 'Please note the string "Purpose~1" is used as a marker for string replacement
Using sw As New StreamWriter(Server.MapPath(folderPath & "Test1.html"))
sw.Write(sTemp)
End Using

Catch ex As Exception
Throw ex
End Try
End Sub

Protected Function ReadFile(ByVal myFilePath As String) As String
Try
If Not File.Exists(myFilePath) Then
Return String.Empty
End If

Using sr As New StreamReader(myFilePath)
Return sr.ReadToEnd()
End Using

Catch ex As Exception
Throw ex
End Try
End Function

Comments