Articles in this section
Category / Section

How to open a Word document available in the file explorer control using JS DocumentEditor?

3 mins read

You can open a Word document in the JavaScript Document Editor control while clicking the Word document from the FileExplorer control using its beforeOpen event.

HTML

<html>
<head>
<!-- Essential JS 1 default theme -->
    <link href=" http://cdn.syncfusion.com/16.1.0.24/js/web/flat-azure/ej.web.all.compatibility.min.css " rel="stylesheet" type="text/css" />
    <!-- Essential JS 2 material theme -->
    <link href="https://cdn.syncfusion.com/ej2/styles/compatibility/material.css" rel="stylesheet" type="text/css" />
 
    <!-- Essential JS 1 scripts -->
    <script src="https://cdn.syncfusion.com/js/assets/external/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script src="https://cdn.syncfusion.com/js/assets/external/jquery.easing.1.3.min.js" type="text/javascript"></script>
    <script src="https://cdn.syncfusion.com/js/assets/external/jsrender.min.js"></script>
    <script src="https://cdn.syncfusion.com/16.4.0.42/js/web/ej.web.all.min.js" type="text/javascript"></script>
 
    <!-- Essential JS 2 script -->
    <script src=" https://cdn.syncfusion.com/ej2/dist/ej2.min.js" type="text/javascript"></script>
    <script>
        //Extend ej namespace with Syncfusion
        $.extend(ej, Syncfusion)
    </script>
</head>
<body>
<div id="target">
    <div id="filePicker_target">
        <div id="fileExplorer"></div>
    </div>
    <div id=dialog>
        <div id="container"></div>
    </div>
</div>
</body>
</html>

 

JS

$("#fileExplorer").ejFileExplorer({
    "isResponsive": true,
    "layout": "tile",
    "width": "100%",
    "fileTypes": "*.png, *.gif, *.jpg, *.jpeg, *.docx",
    "path": "~/FileExplorerContent/",
    "ajaxAction": "/Home/FileActionDefault",
    "minWidth": "150px",
    "beforeOpen": "onBeforeOpen"
});
 
var dialog = new ejs.popups.Dialog({
    "height": "100%",
    "isModal": true,
    "showCloseIcon": true,
    "visible": false,
    "zIndex": 0.0,
    "beforeOpen": onDialogBeforeOpen,
    "close": onDialogClose,
    "open": resizeEditor
});
dialog.appendTo("#dialog");
 
var container = new ejs.documenteditor.DocumentEditorContainer({
    "enableLocalPaste": false,
    "enableToolbar": true,
    "restrictEditing": false,
    "showPropertiesPane": false
});
container.appendTo("#container");
 
var filePicker = document.getElementById("filePicker_target");
 
function onBeforeOpen(args) {
 
    if (args.itemType == "File" && (/\.(doc|docx|rtf|txt|html)$/i).test(args.model.selectedItems[0])) {
        dialog.show();
        var filePath = args.model.selectedFolder + args.model.selectedItems[0];
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('POST', "/api/DocumentEditor/Import?filePath=" + filePath, true);
        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200 || httpRequest.status === 304) {
                    container.documentEditor.open(httpRequest.responseText);
                } else {
                    console.error(httpRequest.response);
                }
            }
        }
            ;
        httpRequest.send();
    }
}
 
function resizeEditor() {
    var container = document.getElementById("container").ej2_instances[0];
    container.documentEditor.resize();
}
function onDialogBeforeOpen() {
    filePicker.style.display = 'none';
    setTimeout(function () {
        resizeEditor();
    });
}
function onDialogClose() {
    filePicker.style.display = 'block';
}
 

 

WEB API

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using EJ2WordDocument = Syncfusion.EJ2.DocumentEditor.WordDocument;
 
// To process the import request.
        [HttpPost]
        [Route("Import")]
        public HttpResponseMessage Import(string filePath)
        {
            filePath = System.Web.HttpContext.Current.Server.MapPath(filePath);
            //If the path from local drive.
            Stream fileStream = System.IO.File.Open(filePath, FileMode.Open, System.IO.FileAccess.Read);
            fileStream.Position = 0;
 
            int index = filePath.LastIndexOf('.');
            string type = index > -1 && index < filePath.Length - 1 ?
                filePath.Substring(index) : ".docx";
 
 
            EJ2WordDocument document = EJ2WordDocument.Load(fileStream, GetFormatType(type.ToLower()));
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
            document.Dispose();
            fileStream.Close();
            return new HttpResponseMessage() { Content = new StringContent(json) };
 
        }
        internal static Syncfusion.EJ2.DocumentEditor.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 Syncfusion.EJ2.DocumentEditor.FormatType.Docx;
                case ".dot":
                case ".doc":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Doc;
                case ".rtf":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Rtf;
                case ".txt":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.Txt;
                case ".xml":
                    return Syncfusion.EJ2.DocumentEditor.FormatType.WordML;
                default:
                    throw new NotSupportedException("EJ2 DocumentEditor does not support this file format.");
            }
        }

 

File Manager.

 

Opened Word Document.

 

Sample:https://www.syncfusion.com/downloads/support/directtrac/general/ze/DocumentEditorWithFilePicker-698218240 

In the previously given sample, the FileExplorer control is provided with the Word documents. By using the Document Editor control, you can open a Word document by selecting it.

Conclusion

I hope you enjoyed learning about the quick getting started with the JavaScript Word Processor. You can explore the runnable sample of getting started with JavaScript Grid from this GitHub location.

You can refer to our JavaScript Word Processor's feature tour page to know about its other groundbreaking feature representations. You can also explore our JavaScript Word Processor to understand how to present and manipulate data.

For current customers, you can check out our JavaScript components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other JavaScript components.

If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

 


Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied