Back to Devexpress

How to: Save a Document

wpf-116728-controls-and-libraries-rich-text-editor-examples-files-how-to-save-a-document.md

latest12.3 KB
Original Source

How to: Save a Document

  • May 27, 2025
  • 5 minutes to read

Common Technique

To save a document in the RichEditControl, use the RichEditControl.SaveDocument Document.SaveDocument method. The RichEditControl.DocumentSaveOptions property provides access to information about the current and default file names and formats.

Call the RichEditControl.SaveDocumentAs method to invoke a Save As… dialog.

Note

Take into account the following when you save the document:

The RichEditControl.BeforeExport event is raised before you save a document. You can handle this event to check how the exporter formats a document. For example, the following code snippet determines whether a document contains complex formatting elements (inline pictures). If they are found, the user is prompted to save the metafile representation along with the original picture (by enabling the RtfDocumentExporterCompatibilityOptions.DuplicateObjectAsMetafile property). This technique increases the file size, but makes it possible to open this file with third-party editors which don’t support native picture format.

View Example

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.Export;
using DevExpress.XtraRichEdit.Services;
private void btnSaveToFile_Click(object sender, EventArgs e) {
    richEditControl1.SaveDocument("SavedDocument.rtf", DocumentFormat.Rtf);
    System.IO.FileInfo fi = new System.IO.FileInfo("SavedDocument.rtf");
    string msg = String.Format("The size of the file is {0:#,#} bytes.", fi.Length.ToString("#,#"));
    MessageBox.Show(msg);
}

private void richEditControl1_BeforeExport(object sender, DevExpress.XtraRichEdit.BeforeExportEventArgs e) {
    DocumentExportCapabilities checkDocument = richEditControl1.Document.RequiredExportCapabilities;
    if((e.DocumentFormat == DocumentFormat.Rtf) && checkDocument.InlinePictures ) {
        DialogResult reduceFileSize = MessageBox.Show("This document contains inline pictures.\n" +
        "You can embed the same picture in two different types (original and Windows Metafile) for better compatibility" +
        " although it increases the file size. By default a picture is saved in original format only.\n" +
        "Enable dual picture format in a saved file?",
        "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

        RtfDocumentExporterOptions options = e.Options as RtfDocumentExporterOptions;
        if(options != null) {
            switch (reduceFileSize) {
            case DialogResult.Yes:
                    options.Compatibility.DuplicateObjectAsMetafile = true;
                    break;
            case System.Windows.Forms.DialogResult.No:
                    options.Compatibility.DuplicateObjectAsMetafile = false;
                    break;
            }
        }
    }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.Export
Imports DevExpress.XtraRichEdit.Services
Private Sub btnSaveToFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSaveToFile.Click
    richEditControl1.SaveDocument("SavedDocument.rtf", DocumentFormat.Rtf)
    Dim fi As New System.IO.FileInfo("SavedDocument.rtf")
    Dim msg As String = String.Format("The size of the file is {0:#,#} bytes.", fi.Length.ToString("#,#"))
    MessageBox.Show(msg)
End Sub

Private Sub richEditControl1_BeforeExport(ByVal sender As Object, ByVal e As DevExpress.XtraRichEdit.BeforeExportEventArgs) Handles richEditControl1.BeforeExport
    Dim checkDocument As DocumentExportCapabilities = richEditControl1.Document.RequiredExportCapabilities
    If (e.DocumentFormat = DocumentFormat.Rtf) AndAlso checkDocument.InlinePictures Then
        Dim reduceFileSize As DialogResult = MessageBox.Show("This document contains inline pictures." & Constants.vbLf & "You can embed the same picture in two different types (original and Windows Metafile) for better compatibility" & " although it increases the file size. By default a picture is saved in original format only." & Constants.vbLf & "Enable dual picture format in a saved file?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)

        Dim options As RtfDocumentExporterOptions = TryCast(e.Options, RtfDocumentExporterOptions)
        If options IsNot Nothing Then
            Select Case reduceFileSize
            Case System.Windows.Forms.DialogResult.Yes
                    options.Compatibility.DuplicateObjectAsMetafile = True
            Case System.Windows.Forms.DialogResult.No
                    options.Compatibility.DuplicateObjectAsMetafile = False
            End Select
        End If
    End If
End Sub
csharp
public class CustomRichEditCommandFactoryService : IRichEditCommandFactoryService
{
    readonly IRichEditCommandFactoryService service;
    readonly RichEditControl control;
    public CustomRichEditCommandFactoryService(RichEditControl control, IRichEditCommandFactoryService service)
    {
        DevExpress.Utils.Guard.ArgumentNotNull(control, "control");
        DevExpress.Utils.Guard.ArgumentNotNull(service, "service");
        this.control = control;
        this.service = service;
    }
    public RichEditCommand CreateCommand(RichEditCommandId id)
    {
        if (id == RichEditCommandId.FileSaveAs)
            return new CustomSaveDocumentAsCommand(control);

        return service.CreateCommand(id);
    }
}

public class CustomSaveDocumentAsCommand : SaveDocumentAsCommand
{
    public CustomSaveDocumentAsCommand(IRichEditControl control)
        : base(control) {}

    protected override void ExecuteCore()
    {
        SaveFileDialog dialog = new SaveFileDialog
        {
            Filter = "Rich Text Format Files (*.rtf)|*.rtf|All Files (*.*)|*.*",
            FileName = "SavedDocument.rtf",
            RestoreDirectory = true,
            CheckFileExists = false,
            CheckPathExists = true,
            OverwritePrompt = true,
            DereferenceLinks = true,
            ValidateNames = true,
            AddExtension = false,
            FilterIndex = 1
        };
        dialog.InitialDirectory = "C:\\Temp";
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            ((RichEditControl)this.Control).SaveDocument(dialog.FileName, DocumentFormat.Rtf);
        }
        //base.ExecuteCore();
    }
}
vb
Public Class CustomRichEditCommandFactoryService
    Implements IRichEditCommandFactoryService
    Private ReadOnly service As IRichEditCommandFactoryService
    Private ReadOnly control As RichEditControl
    Public Sub New(ByVal control As RichEditControl, ByVal service As IRichEditCommandFactoryService)
        DevExpress.Utils.Guard.ArgumentNotNull(control, "control")
        DevExpress.Utils.Guard.ArgumentNotNull(service, "service")
        Me.control = control
        Me.service = service
    End Sub
    Public Function CreateCommand(ByVal id As RichEditCommandId) As RichEditCommand Implements IRichEditCommandFactoryService.CreateCommand
        If id = RichEditCommandId.FileSaveAs Then
            Return New CustomSaveDocumentAsCommand(control)
        End If

        Return service.CreateCommand(id)
    End Function
End Class

Public Class CustomSaveDocumentAsCommand
    Inherits SaveDocumentAsCommand
    Public Sub New(ByVal control As IRichEditControl)
        MyBase.New(control)
    End Sub

    Protected Overrides Sub ExecuteCore()
        Dim dialog As SaveFileDialog = New SaveFileDialog With {.Filter = "Rich Text Format Files (*.rtf)|*.rtf|All Files (*.*)|*.*", .FileName = "SavedDocument.rtf", .RestoreDirectory = True, .CheckFileExists = False, .CheckPathExists = True, .OverwritePrompt = True, .DereferenceLinks = True, .ValidateNames = True, .AddExtension = False, .FilterIndex = 1}
        dialog.InitialDirectory = "C:\Temp"
        If dialog.ShowDialog() = DialogResult.OK Then
            CType(Me.Control, RichEditControl).SaveDocument(dialog.FileName, DocumentFormat.Rtf)
        End If
        'base.ExecuteCore();
    End Sub
End Class

Custom SaveAs Command

You can implement a custom command to adjust the SaveAs dialog settings or accomplish specific tasks.

Note

Commands executed via the Bar (Ribbon) user interface can throw unhandled exceptions if a problem occurs. Consider the situation when a document is being saved to a locked or read-only file. To prevent application failure, subscribe to the RichEditControl.UnhandledException event and set the RichEditUnhandledExceptionEventArgs.Handled property to true.

A custom command inherits from the SaveDocumentAsCommand class and overrides the protected ExecuteCore method. To substitute default command with a custom command, create a new command factory - the class that implements the IRichEditCommandFactoryService interface and intercepts a call that creates a SaveDocumentAsCommand command. Register the new command factory via the IRichEditDocumentServer.ReplaceService<T> method and the RichEditControl will execute a custom command whenever you press F12 or click the Save As… button.

csharp
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.Export;
using DevExpress.XtraRichEdit.Services;
        public Form1() 
        {
            InitializeComponent();

            CustomRichEditCommandFactoryService commandFactory =
                new CustomRichEditCommandFactoryService(richEditControl1,
                    richEditControl1.GetService<IRichEditCommandFactoryService>());
            richEditControl1.ReplaceService<IRichEditCommandFactoryService>(commandFactory);
        }
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.Export
Imports DevExpress.XtraRichEdit.Services
        Public Sub New()
            InitializeComponent()

            Dim commandFactory As New CustomRichEditCommandFactoryService(richEditControl1, richEditControl1.GetService(Of IRichEditCommandFactoryService)())
            richEditControl1.ReplaceService(Of IRichEditCommandFactoryService)(commandFactory)
        End Sub

Save in Format with External Content

When saving a document in a format that defines an external content included via links (HTML format), specify a base URI to store these objects (images and style sheets). This involves RichEditControl.BeforeExport event handling and custom IUriProvider interface implementation.

View Example: How to save the document range in different formats