Back to Devexpress

How to: Load a Document

officefileapi-116813-word-processing-document-api-examples-files-how-to-load-a-document.md

latest8.8 KB
Original Source

How to: Load a Document

  • Sep 19, 2023
  • 3 minutes to read

The RichEditDocumentServer.LoadDocument method allows you to load a document from a file, stream, byte array, or string. Handle related events to determine the moment when the document can be modified.

The format of the loaded document is detected automatically by the built-in IFormatDetectorService service implementation. The following formats are detected:

  • DOC, DOCM, DOTX, DOT, DOTM, DOCX, RTF, HTM, HTML, MHT, XML, FlatOpc, EPUB;
  • ODT - non-encrypted files only.

Use the LoadDocument method overloads with explicit format definition to improve performance.

Load a Document from a File

View Example

csharp
wordProcessor.LoadDocument("Documents\\Grimm.docx", DocumentFormat.Docx);
vb
wordProcessor.LoadDocument("Documents\Grimm.docx", DocumentFormat.Docx)

Load a Document from a Stream

csharp
using DevExpress.XtraRichEdit;
using System.Diagnostics;
using System.Reflection;

using (var wordProcessor = new RichEditDocumentServer())
{
    using (Stream stream = GetResourceStream("MyApplication.Document1.rtf"))
    {
        stream.Seek(0, SeekOrigin.Begin);
        wordProcessor.LoadDocument(stream, DocumentFormat.Rtf);
        stream.Close();
    }
}

static Stream GetResourceStream(string resourceName)
{
    return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
}
vb
Imports DevExpress.XtraRichEdit
Imports System.Diagnostics
Imports System.Reflection

Using wordProcessor = New RichEditDocumentServer()
    Using stream As Stream = GetResourceStream("MyApplication.Document1.rtf")
        stream.Seek(0, SeekOrigin.Begin)
        wordProcessor.LoadDocument(stream, DocumentFormat.Rtf)
        stream.Close()
    End Using
End Using

Shared Function GetResourceStream(ByVal resourceName As String) As Stream
    Return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)
End Function

Load a Document from a String

The following properties load strings in various formats:

The code sample below loads an RTF string:

csharp
using (var wordProcessor = new RichEditDocumentServer()) {
    string rtfString = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1049
{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}
{\f1\fswiss\fcharset0 Arial;}}
{\colortbl ;\red0\green0\blue255;}
\viewkind4\uc1\pard\cf1\lang1033\b\f0\fs32 Test.\cf0\b0\f1\fs20\par}";
    Document document = wordProcessor.Document;
    document.RtfText = rtfString;
}
vb
Using wordProcessor As New RichEditDocumentServer()
    Dim rtfString As String = "{\rtf1\ansi\ansicpg1252\deff0\deflang1049" & ControlChars.CrLf & _
    "{\fonttbl{\f0\fswiss\fprq2\fcharset0 Arial;}" & ControlChars.CrLf & _
    "{\f1\fswiss\fcharset0 Arial;}}" & ControlChars.CrLf & _
    "{\colortbl ;\red0\green0\blue255;}" & ControlChars.CrLf & _
    "\viewkind4\uc1\pard\cf1\lang1033\b\f0\fs32 Test.\cf0\b0\f1\fs20\par}"
    Dim document As Document = wordProcessor.Document
    document.RtfText = rtfString
End Using

Asynchronous Load

Use the RichEditDocumentServerExtensions.LoadDocumentAsync method to asynchronously load a document from a file, stream, or byte array.

To run asynchronous operations, you need to use the RichEditDocumentServerExtensions class from the DevExpress.Docs.v25.2.dll assembly. Remember to add this assembly to your project. If you use this assembly in production code, a license for the DevExpress Office File API or DevExpress Universal Subscription is required. For pricing information, refer to the following page: DevExpress Subscription Plans.

Important

Take into account the following when you call this method:

  • The events fired by this method call may occur in a different thread than the target operation.

  • The operation is not thread safe (the document should not be accessed simultaneously by different threads). Wait until the operation is completed before you continue to work with the document (for example, use the await operator).

The code sample below merges two asynchronously loaded documents and asynchronously exports the result:

csharp
private async void MergeDocuments()
{
  using (RichEditDocumentServer wordProcessor = new RichEditDocumentServer())
  using (RichEditDocumentServer wordProcessor2 = new RichEditDocumentServer())
  {
      await Task.WhenAll(new Task[]
      {
          wordProcessor.LoadDocumentAsync("Document1.docx"),
          wordProcessor2.LoadDocumentAsync("Document2.docx")
      });
      wordProcessor.AppendDocumentContent(wordProcessor2.Document.Range);
      await wordProcessor.SaveDocumentAsync("merged.docx", DocumentFormat.Docx);
  }
}
vb
Private Async Sub MergeDocuments()
    Using wordProcessor As RichEditDocumentServer = New RichEditDocumentServer()

        Using wordProcessor2 As RichEditDocumentServer = New RichEditDocumentServer()
            Await Task.WhenAll(New Task() {wordProcessor.LoadDocumentAsync("Document1.docx"), wordProcessor2.LoadDocumentAsync("Document2.docx")})
            wordProcessor.AppendDocumentContent(wordProcessor2.Document.Range)
            Await wordProcessor.SaveDocumentAsync("merged.docx", DocumentFormat.Docx)
        End Using
    End Using
End Sub

The table below lists events related to the document load:

EventDescription
RichEditDocumentServer.BeforeImportOccurs before a document is loaded (imported from an external source).
RichEditDocumentServer.InitializeDocumentOccurs before a document is loaded. Handle this event to set initial document settings.
RichEditDocumentServer.DocumentLoadedOccurs after a document is loaded.
DocumentLayout.DocumentFormattedFires after the document layout is calculated.
RichEditDocumentServer.InvalidFormatExceptionFires when the supplied data could not be recognized as data in the assumed format for import.
RichEditDocumentServer.UnhandledExceptionThis event is raised when an exception unhandled by the RichEditDocumentServer occurs.