Skip to main content
A newer version of this page is available. .

Import and Export

  • 11 minutes to read

Supported Formats

The RichEditControl supports the following document formats:

  • Plain Text;
  • RTF (Rich Text Format);
  • DOCX (MS Office Word 2007 -… format);
  • DOC (Microsoft Word 97-2003 format);
  • WordML (MS Office Word 2003 XML format);
  • OpenDocument (implemented by the OpenOffice.org office suite);
  • HTML;
  • MHTML (web page archive format);
  • EPUB (Electronic Publication);
  • PDF format (export only)

Load Documents in the User Interface

End-users can open documents using the Open button on the File ribbon tab. Clicking this button invokes the Open dialog allowing end-users to find and select the target document. Refer to the How to: Create a Simple Word Processor with a Ribbon UI for details on how to provide a ribbon UI for the RichEditControl.

XtraRichEdit_ImportExport_LoadDocuments

Tip

Set the RichEditBehaviorOptions.CreateNew or RichEditBehaviorOptions.Open property to DocumentCapability.Disabled to prohibit end-users from creating or loading documents.

Load Documents in Code

Command

Execute the LoadDocumentCommand to invoke the Open dialog and load the selected document.

API

The RichEditControl provides the following methods to import the document and specify its options:

Member Description
RichEditControl.LoadDocument Loads a document from a file or stream. The document format can be specified manually or detected automatically.
RichEditControl.LoadDocumentTemplate Loads a document from the specified file or stream so that it cannot be overwritten automatically.
Document.LoadDocument Loads a document from the specified file or stream. Its content determines the file format or specified manually.
SubDocument.InsertDocumentContent Inserts content from the specified range into the current document at the specified position.
SubDocument.AppendDocumentContent Appends content from the specified range to the end of the current document.

Handle the RichEditControl.BeforeImport event to specify the format-specific import options (accessed by the RichEditControlOptionsBase.Import property), as shown in the code snippet below.

The following example illustrates how the RichEditControl.BeforeImport event can be used to specify the location of external content of the loaded HTML file.

private void richEditControl1_BeforeImport(object sender, BeforeImportEventArgs e) {
    if(e.DocumentFormat == DocumentFormat.Html) {
        e.Options.SourceUri = "file:///" + Application.StartupPath + imgPath;
    }
}
private void richEditControl2_BeforeImport(object sender, BeforeImportEventArgs e) {
    if(e.DocumentFormat == DocumentFormat.PlainText) {
        ((PlainTextDocumentImporterOptions)e.Options).Encoding = cur_Encoding;
    }
}

The table below lists the document formats the RichEditControl supports, and the API used to specify the necessary import options:

Format Import Options
Plain Text RichEditDocumentImportOptions.PlainText
Rich Text Format RichEditDocumentImportOptions.Rtf
DOCX RichEditDocumentImportOptions.OpenXml
DOC RichEditDocumentImportOptions.Doc
WordML RichEditDocumentImportOptions.WordML
MHT RichEditDocumentImportOptions.Mht

Use the RichEditControlOptionsBase.DocumentCapabilities options to access the DocumentCapabilitiesOptions instance and restrict importing certain document elements (bookmarks, comments, fields, etc. ).

Note

Hyperlink fields represent hyperlinks in the RichEditControl, therefore the DocumentCapabilitiesOptions.Fields property affects the hyperlink loading process when importing the documents. Set the RichEditControlCompatibility.LoadHyperlinkAsField property to false before calling the InitializeComponent method to allow loading hyperlinks when loading fields is disabled.

You can use the Document.DefaultCharacterProperties or Document.DefaultParagraphProperties property to set every imported document’s default character or paragraph formatting options.

HTML Documents

Loaded HTML documents are parsed and transformed into the internal document model. Not every HTML tag can be converted into a corresponding document model element. Refer to the HTML Tag Support topic for a full list of supported tags.

When exporting a document to HTML, the document model is parsed and transformed again, resulting in a document that is different from the original HTML document.

You can implement your IUriStreamProvider or IUriStreamService descendants and override the IUriStreamProvider.GetStream method to manage decoding external contents in an HTML file when an HTML document is loaded. When the RichEditControl needs to load data from a specific URI, your method is executed instead of the default one.

This example demonstrates how to implement the IUriStreamProvider interface to create a custom data stream provider for the IUriProviderService service.

public class ImageStreamProvider : IUriStreamProvider {
    static readonly string prefix = "dbimg://";
    DataTable table;
    string columnName;

    public ImageStreamProvider(DataTable sourceTable, string imageColumn) {
        this.table = sourceTable;
        this.columnName = imageColumn;
    }


    public Stream GetStream(string uri) {
        uri = uri.Trim();
        if (!uri.StartsWith(prefix))
            return null;
        string strId = uri.Substring(prefix.Length).Trim();
        int id;
        if (!int.TryParse(strId, out id))
            return null;
        DataRow row = table.Rows.Find(id);
        if (row == null)
            return null;
        byte[] bytes = row[columnName] as byte[];
        if (bytes == null)
            return null;

        // Use this approach to trim the OLE header off the image
        // See also: http://www.devexpress.com/issue=Q233460, 
        // https://social.msdn.microsoft.com/Forums/en-US/c37289c7-3ca5-458e-8eda-286ffa2ff966/retrieving-an-image-from-a-table-in-a-c-picturebox?forum=sqldataaccess
        MemoryStream memoryStream = new MemoryStream();
        int oleHeaderOffset = 78;
        memoryStream.Write(bytes, oleHeaderOffset, bytes.Length - oleHeaderOffset);

        return memoryStream;
    }

Saving Documents in the User Interface

End-users can save changes made in the current document or save it as a new file using Save and Save As buttons on the File ribbon tab. Clicking the Save As button invokes the Save As dialog, which allows end-users to specify the document’s location, name, and format. Refer to the How to: Create a Simple Word Processor with a Ribbon UI topic for details on how to provide a ribbon ui for the RichEditControl.

XtraRichEdit_ImportExport_ExportDocuments

Tip

Set the RichEditBehaviorOptions.Save or RichEditBehaviorOptions.SaveAs property to DocumentCapability.Disabled to prohibit end-users from saving documents.

Save Documents in Code

Command

Execute the SaveDocumentCommand to save changes to the current document. If the document is saved for the first time, it invokes the Save As dialog. Otherwise, this command saves the document with the name and format the DocumentSaveOptions.CurrentFileName and DocumentSaveOptions.CurrentFormat properties specify.

Executing the SaveDocumentAsCommand command always invokes the Save As dialog that saves a document as a file with the given name and format.

API

Use the following methods to save a document manually:

Handle the RichEditControl.BeforeExport event to specify the format-specific export options (accessed by the RichEditControlOptionsBase.Export property), as shown in the code snippet:

private void richEditControl_BeforeExport(object sender, DevExpress.XtraRichEdit.BeforeExportEventArgs e) {
    DevExpress.XtraRichEdit.Export.HtmlDocumentExporterOptions options = e.Options as DevExpress.XtraRichEdit.Export.HtmlDocumentExporterOptions;
    if (options != null) {
        options.CssPropertiesExportType = DevExpress.XtraRichEdit.Export.Html.CssPropertiesExportType.Link;
        options.HtmlNumberingListExportFormat = DevExpress.XtraRichEdit.Export.Html.HtmlNumberingListExportFormat.HtmlFormat;
        options.TargetUri = Path.GetFileNameWithoutExtension(this.fileName);
    }
}

Use the API from the table below to set the corresponding export options:

Format Export Options
Plain Text RichEditDocumentExportOptions.PlainText
Rich Text Format RichEditDocumentExportOptions.Rtf
MS Word 2007 (OpenXML) RichEditDocumentExportOptions.OpenXml
DOC RichEditDocumentExportOptions.Doc
WordML RichEditDocumentExportOptions.WordML
HTML RichEditDocumentExportOptions.Html
MHT RichEditDocumentExportOptions.Mht
PDF PdfExportOptions

Use the RichEditControlOptionsBase.DocumentSaveOptions property to define the saved document’s name and format.

HTML Documents

When exporting a document to HTML format, you can specify a location for storing images as external files or process them before saving. To do this, handle the RichEditControl.BeforeExport event and specify the HtmlDocumentExporterOptions.UriExportType and IExporterOptions.TargetUri. Moreover, you can implement your class with the IUriProvider interface and override the IUriProvider.CreateImageUri and IUriProvider.CreateCssUri methods. Then, it can be used instead of the default URI provider when the SubDocument.GetHtmlText method is called.

    public class CustomUriProvider : DevExpress.Office.Services.IUriProvider {
    string rootDirecory;
    public CustomUriProvider(string rootDirectory) {
        if (String.IsNullOrEmpty(rootDirectory))
            DevExpress.Office.Utils.Exceptions.ThrowArgumentException("rootDirectory", rootDirectory);
        this.rootDirecory = rootDirectory;
    }

    public string CreateCssUri(string rootUri, string styleText, string relativeUri) {
        string cssDir = String.Format("{0}\\{1}", this.rootDirecory, rootUri.Trim('/'));
        if (!Directory.Exists(cssDir))
            Directory.CreateDirectory(cssDir);
        string cssFileName = String.Format("{0}\\style.css", cssDir);
        File.AppendAllText(cssFileName, styleText);
        return GetRelativePath(cssFileName);
    }
        public string CreateImageUri(string rootUri, DevExpress.Office.Utils.OfficeImage image, string relativeUri) {
        string imagesDir = String.Format("{0}\\{1}", this.rootDirecory, rootUri.Trim('/'));
        if (!Directory.Exists(imagesDir))
            Directory.CreateDirectory(imagesDir);
        string imageName = String.Format("{0}\\{1}.png", imagesDir, Guid.NewGuid());
        image.NativeImage.Save(imageName, ImageFormat.Png);
        return GetRelativePath(imageName);
    }
    string GetRelativePath(string path) {
        string substring = path.Substring(this.rootDirecory.Length);
        return substring.Replace("\\", "/").Trim('/');
    }
}

Use the HtmlDocumentExporterOptions.EmbedImages option to store images in base-64 encoding. The HtmlDocumentExporterOptions.TabMarker property allows you to substitute Tab (0x09) characters with any symbol combination in HTML output.

Specify the corresponding paragraph’s Paragraph.OutlineLevel property to mark the text in HTML output with H1 - H6 tags. Paragraphs with outline levels higher than 6 are exported as text enclosed in a P tag.

RTF Documents

When saving a document in an RTF format, inline pictures can be stored twice - in the native format and as a Windows Metafile. If an editing application is unable to process the native picture format, it can display a Windows Metafile. Only pictures in the native format are saved by default to reduce the file size. Use the RtfDocumentExporterCompatibilityOptions.DuplicateObjectAsMetafile property to modify this behavior.

All document styles are saved by default, which could increase the saved document’s size. You can delete unused styles from the Document.CharacterStyles, Document.ParagraphStyles and Document.TableStyles style collections before exporting to reduce the size of data in RTF format. Set the RtfDocumentExporterOptions.ExportTheme property to false to exclude the color theme information from the file.

PDF Documents

The RichEditControl uses the DevExpress Printing Library to process the PDF export. Use the PdfExportOptions class properties to specify advanced export settings, as demonstrated below.

The following code loads the sample document, specifies export options using the PdfExportOptions settings and exports it to PDF. It invokes the default PDF viewer to display the resulting document.

The RichEditControl instance is passed to the BarItem.ItemClick event handler using the BarItem.Tag property.

static void buttonCustomAction_ItemClick_PDF(object sender, ItemClickEventArgs e) {
    RichEditControl richEdit = e.Item.Tag as RichEditControl;
    richEdit.LoadDocument("Documents\\Grimm.docx");
    //Set the required export options:
    DevExpress.XtraPrinting.PdfExportOptions options = new DevExpress.XtraPrinting.PdfExportOptions();
    options.DocumentOptions.Author = "Mark Jones";
    options.Compressed = false;
    options.ImageQuality = DevExpress.XtraPrinting.PdfJpegImageQuality.High;
    //Export the document to the file:
    richEdit.ExportToPdf("resultingDocument.pdf", options);
    //Export the document to the file stream:
    using (FileStream pdfFileStream = new FileStream("resultingDocumentFromStream.pdf", FileMode.Create)) {
        richEdit.ExportToPdf(pdfFileStream, options);
    }

    System.Diagnostics.Process.Start("resultingDocument.pdf");
}

Get or Set Document Content

Use one of the following properties to get or set the document content in a specific format:

Tip

Use the SubDocument‘s Get… methods to retrieve and format a part of the document. Refer to the Positions and Ranges topic for details.

See Also