Skip to main content

How to: Save a Document in the RichEditControl

  • 5 minutes to read

To save a document in the RichEditControl, use the RichEditControl.SaveDocument or Document.SaveDocument method. The RichEditControlOptionsBase.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 or not 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: How to save a document in the RichEditControl

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;
            }
        }
    }
}

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.

View Example

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);
}
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();
    }
}

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