Using DocxFormatProvider

DocxFormatProvider makes it easy to import and export RadRichTextBox to/from DOCX format, preserving the entire document structure and formatting.

All you have to do in order to use DocxFormatProvider is to add references to the assemblies listed below:

  • Telerik.Windows.Documents.FormatProviders.OpenXml.dll
  • Telerik.Windows.Zip.dll

Import

In order to import a .docx file, you need to use the Import() method of DocxFormatProvider. The code in Example 1 shows how to use DocxFormatProvider to import a DOCX document from a file.

Example 1: Import document from a file

Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider provider = new Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider(); 
using (FileStream inputStream = new FileStream("Sample.docx",FileMode.Open)) 
{ 
    this.radRichTextBox.Document = provider.Import(inputStream); 
} 
And here is how you can import a document from byte array containing the docx document:

Example 2: Import document from a byte array

Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider provider = new Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider(); 
RadDocument document = provider.Import(input); 

Export

In order to export a document to DOCX, you need to use the Export() method of DocxFormatProvider. Example 2 shows how to use DocxFormatProvider to export RadDocument to a file.

Example 3: Export document to a file

Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider provider = new Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider(); 
using (FileStream output =  new FileStream("Sample.docx",FileMode.OpenOrCreate)) 
{ 
    RadDocument document = this.radRichTextBox.Document; 
    provider.Export(document, output); 
} 
You can also export the document to a byte array and preserve it in a database.

Example 4: Export a document to a byte array

Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider provider = new Telerik.Windows.Documents.FormatProviders.OpenXml.Docx.DocxFormatProvider(); 
RadDocument document = CreateRadDocument(); 
byte[] output = provider.Export(document); 
The resulting documents can be opened in any application that supports DOCX documents.

However, the format providers cannot be used in XAML and you have to implement a logic that will call their Import() and Export() methods. This is something that you might not want to be concerned with when using RadRichTextBox in a data bound scenarios. For such cases, the DataProvider classes are used. They wrap the FormatProviders' functionality and allow its usage in XAML.

See Also

In this article