How to: Reduce the File Size When Saving a Document Containing Pictures

  • 2 minutes to read

RTF specification allows RTF writers to save embedded pictures two times - in the native format and as a metafile, so if the application is unable to load the original object, it can skip it, and display the graphics metafile instead. Included metafiles may result in "bloated" RTF files.

By default, the pictures are saved only in original format. To enable dual saving of a picture (thus increasing the file size), you can handle the BeforeExport event and set the DuplicateObjectAsMetafile property to true. The following code snippet illustrates this technique.

View Example

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