Import in ASP.NET MVC DOCX Editor

12 Oct 202615 minutes to read

In ASP.NET MVC DOCX Editor (Document Editor), documents are stored in its own format called Syncfusion Document Text (SFDT).

The following example shows how to open SFDT data in DOCX Editor.

@Html.EJS().DocumentEditor("container").Render()

<script>
    var documenteditor;    
    document.addEventListener('DOMContentLoaded', function () {        
        documenteditor = documenteditorElement.ej2_instances[0];
        documenteditor.resize();
        var sfdt = {
            "sections": [
                {
                    "blocks": [
                        {
                            "inlines": [
                                {
                                    "characterFormat": {
                                        "bold": true,
                                        "italic": true
                                    },
                                    "text": "Hello World"
                                }
                            ]
                        }
                    ],
                    "headersFooters": {
                    }
                }
            ]
        };

        documenteditor.open(JSON.stringify(sfdt));
    }); 
</script>
public ActionResult Default()
{
    return View();
}

Import a document from a local machine

The following example shows how to import a document from a local machine.

<input type="file" id="file_upload" accept=".sfdt" style="position:fixed; left:-100em" /> 
@Html.EJS().Button("import").Content("Import").Render()
<div id="documenteditor" style="width:100%;height:100%">
    @Html.EJS().DocumentEditor("container").Render()
</div>

<script>
    var documenteditor;
    document.addEventListener('DOMContentLoaded', function () {
        var documenteditorElement = document.getElementById("container");        
        documenteditor = documenteditorElement.ej2_instances[0];
        documenteditor.resize();
        document.getElementById("import").addEventListener("click", function () {
            document.getElementById('file_upload').click();
        });

        document.getElementById('file_upload').addEventListener("change", function (e) {
            if (e.target.files[0]) {
                var file = e.target.files[0];
                if (file.name.substr(file.name.lastIndexOf('.')) === '.sfdt') {
                    var fileReader = new FileReader();
                    fileReader.onload = function (e) {
                        var contents = e.target.result;
                        documenteditor.open(contents);
                    };
                    fileReader.readAsText(file);
                    documenteditor.documentName = file.name.substr(0, file.name.lastIndexOf('.'));
                }
            }
        });
    }); 
</script>
public ActionResult Default()
{
    return View();
}

Convert Word documents into SFDT

You can convert Word documents into SFDT format using the Syncfusion.EJ2.WordEditor.AspNet.MVC5 by the web API service implementation. This library helps you to convert Word documents (.dotx, .docx, .docm, .dot, .doc), rich text format documents (.rtf), and text documents (.txt) into SFDT format. Refer to the following example.

<input type="file" id="file_upload" style="position:fixed; left:-100em" /> 
@Html.EJS().Button("import").Content("Import").Render()
<div id="documenteditor" style="width:100%;height:100%">
    @Html.EJS().DocumentEditor("container").Render()
</div>

<script>
    var documenteditor;
    document.addEventListener('DOMContentLoaded', function () {
        var documenteditorElement = document.getElementById("container");        
        documenteditor = documenteditorElement.ej2_instances[0];
        documenteditor.resize();
        document.getElementById('file_upload').setAttribute('accept', '.dotx,.docx,.docm,.dot,.doc,.rtf,.txt,.xml,.sfdt');

        document.getElementById('file_upload').addEventListener("change", function (e) {
            if (e.target.files[0]) {
                var file = e.target.files[0];
                if (file.name.substr(file.name.lastIndexOf('.')) !== '.sfdt') {
                    loadFile(file);
                }
            }
        });

        function loadFile(file) {
            var ajax = new XMLHttpRequest();
            ajax.open('POST', 'https://localhost:4000/api/documenteditor/Import', true);
            ajax.onreadystatechange = function () {
                if (ajax.readyState === 4) {
                    if (ajax.status === 200 || ajax.status === 304) {
                        // open SFDT text in document editor
                        documenteditor.open(ajax.responseText);
                    }
                }
            }
            var formData = new FormData();
            formData.append('files', file);
            ajax.send(formData);
        }
    }); 
</script>
public ActionResult Default()
{
    return View();
}

Here’s how to handle the server-side action for converting a Word document into SFDT.

[HttpPost]
public HttpResponseMessage Import()
{
    if (HttpContext.Current.Request.Files.Count == 0)
    return null;

    HttpPostedFile file = HttpContext.Current.Request.Files[0];
    int index = file.FileName.LastIndexOf('.');
    string type = index > -1 && index < file.FileName.Length - 1 ?
    file.FileName.Substring(index) : ".docx";
    Stream stream = file.InputStream;
    stream.Position = 0;

    EJ2WordDocument document = EJ2WordDocument.Load(stream, GetFormatType(type.ToLower()));
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
    document.Dispose();
    stream.Close();
    return new HttpResponseMessage() { Content = new StringContent(json) };
}

internal static FormatType GetFormatType(string format)
{
    if (string.IsNullOrEmpty(format))
        throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
    switch (format.ToLower()) {
        case ".dotx":
        case ".docx":
        case ".docm":
        case ".dotm":
            return FormatType.Docx;
        case ".dot":
        case ".doc":
            return FormatType.Doc;
        case ".rtf":
            return FormatType.Rtf;
        case ".txt":
            return FormatType.Txt;
        case ".xml":
            return FormatType.WordML;
        default:
            throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
    }
}

Opening a document in asynchronous mode

ASP.NET MVC DOCX Editor (Document Editor) supports asynchronous document loading, which can be enabled using the enable property available in the openAsyncSettings API.

Properties

  • enable: Enables or disables asynchronous document loading.
  • initialPageLoadCount: Number of pages to load initially when the document is opened.
  • incrementalPageLoadCount: Number of pages to load incrementally after initial pages load, during the asynchronous document-loading operation.

The following example shows how to open the document asynchronously in DOCX Editor.

<div>
@Html.EJS().DocumentEditorContainer("container").Created("onCreated").EnableToolbar(true).Render()
</div>
<script>
    var documenteditor;
    var container;
    function onCreated() {
        var documenteditorElement = document.getElementById("container");
        container = documenteditorElement.ej2_instances[0];
        container.documentEditorSettings.openAsyncSettings.enable = true;
        container.documentEditorSettings.openAsyncSettings.initialPageLoadCount = 5;
        container.documentEditorSettings.openAsyncSettings.incrementalPageLoadCount = 3;
    }
</script>

When asynchronous loading is enabled, the document initially opens in read-only mode, allowing users to view the first set of pages while the remaining pages load in the background. During this time, the document can be viewed but cannot be edited or saved. Once loading is complete, editing and saving become available.

See Also