How to open a word doc from local maschine, edit and save(download) it?

Hi Syncfusion,


this is how I load a word doc using button click.

In cshtml:

<div class="container-fluid" style="margin-top:80px;margin-bottom:40px;">

    <div class="row">

        <div class="col-md-12">

            <div style="margin-top:10px;" class="btn-group" role="group">


                <button type="button" id="IMOCL" data-toggle="tooltip"

                        data-placement="bottom" title="IMO Crew List" class="btn btn-info">

                    IMO Crew List

                </button>

                <button type="button" id="IMOSSD" data-toggle="tooltip"

                        data-placement="bottom" title="IMO Ships Store Declaration" class="btn btn-info">

                    IMO Ship's Store Declaration

                </button>

                <button type="button" id="FScreen" data-toggle="tooltip"

                        data-placement="bottom" title="IMO General Declaration" class="btn btn-info">

                    IMO General Declaration

                </button>

                <button type="button" id="FScreen" data-toggle="tooltip"

                        data-placement="bottom" title="IMO ship’s stores declaration" class="btn btn-info">

                    IMO ship’s stores declaration

                </button>

                <button type="button" id="FScreen" data-toggle="tooltip"

                        data-placement="bottom" title="IMO crew’s effects declaration" class="btn btn-info">

                    IMO crew’s effects declaration

                </button>

                <button type="button" id="FScreen" data-toggle="tooltip"

                        data-placement="bottom" title="IMO passenger list" class="btn btn-info">

                    IMO passenger list

                </button>


            </div>

        </div>


    </div>

</div>


 @using Syncfusion.EJ2

<button id="export" class="btn btn-info">Save</button>


<div class="row">


    <div class="col-md-12">


        <ejs-documenteditorcontainer id="container" documentChange="onDocumentChange"

                                     enableToolbar="true" height="590px"></ejs-documenteditorcontainer>


    </div>


</div>

<script>



</script>

<script src="~/lib/jquery/dist/jquery.min.js"></script>

<script>

    var documenteditor;

    var container;


    document.addEventListener('DOMContentLoaded', function () {

        Load();

    });


    function Load() {

        var buttons = document.querySelectorAll('.btn');

        var caption;

        buttons.forEach(function (button) {

            button.addEventListener('click', function () {

                // Retrieve the text of the clicked button

                caption = button.innerText;

                var fileN;


                if (caption === "IMO Crew List")

                    fileN = "IMOCrewList.doc";

                if (caption==="IMO Ship's Store Declaration")

                    fileN = "IMOShipsStoreDeclaration.doc";

                var documenteditorElement = document.getElementById("container");

                container = documenteditorElement.ej2_instances[0];

                documenteditor = container.documentEditor;

                container.serviceUrl = 'api/documenteditor/';

                var http = new XMLHttpRequest();

                var baseurl = "/api/DocumentEditor/LoadDefault?fileN=" + encodeURIComponent(fileN);


                http.open("POST", baseurl, true);

                http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

                http.onreadystatechange = () => {

                    if (http.readyState === 4) {

                        if (http.status === 200 || http.status === 304) {

                            //open the SFDT text in Document Editor

                            container.documentEditor.open(http.responseText);

                        }

                    }

                };

                http.send();

            });

        });

    }



    document.getElementById('export').addEventListener('click', function () {

            debugger;

            documenteditor.save('YourIMOList', 'Docx');

        });



    function saveDocument() {

        documenteditor = container.documentEditor;

        documenteditor.saveAsBlob("Docx").then(function (blob) {

            var fileReader = new FileReader();

            fileReader.onload = function () {

                var base64Text = ";base64,";

                var documentData = {

                    fileName: 'YourIMOList.docx',

                    documentData: fileReader.result.substring(fileReader.result.indexOf(base64Text) + base64Text.length)

                };

                var httpRequest = new XMLHttpRequest();

                httpRequest.open('POST', '/api/DocumentEditor/Save', true);

                httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

                httpRequest.onreadystatechange = function () {

                    if (httpRequest.readyState === 4) {

                        if (httpRequest.status === 200) {

                            // Document saved successfully

                            // You can perform any additional actions here if needed

                            console.log('Document saved successfully');

                        } else {

                            // Error handling

                            console.error('Failed to save document:', httpRequest.statusText);

                        }

                    }

                };

                httpRequest.send(JSON.stringify(documentData));

            };

            fileReader.readAsDataURL(blob);

        }).catch(function (error) {

            // Error handling for saving blob

            console.error('Error saving document as blob:', error);

        });

    }

    function ServerSave(){

         var httpRequest = new XMLHttpRequest();

        httpRequest.open('Post', '/api/DocumentEditor/ServerSave', true);

        httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

      let sfdt = {

        content: container.documentEditor.serialize(),

        fileName: 'demo.docx',

      };

      httpRequest.send(JSON.stringify(sfdt));


    }


    function onDocumentChange() {

        container = document.getElementById("container").ej2_instances[0];

        //To detect the device

        var isMobileDevice = /Android|Windows Phone|webOS/i.test(navigator.userAgent);


        if (isMobileDevice) {

            container.restrictEditing = true;

            setTimeout(() => {

                container.documentEditor.fitPage("FitPageWidth");

            }, 50);

        }

        else {

            container.restrictEditing = false;

        }

    }



</script>

in api controller:

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Cors;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Syncfusion.DocIO;

using System;

using System.IO;

using EJ2DocumentEditor = Syncfusion.EJ2.DocumentEditor;

using Microsoft.Extensions.Hosting;

using Microsoft.Extensions.Hosting.Internal;



namespace GreatCircleNavigation.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class DocumentEditorController : ControllerBase

    {


        private IWebHostEnvironment hostEnvironment;


        public DocumentEditorController(IWebHostEnvironment environment)

        {

            this.hostEnvironment = environment;

        }

        //Import file from client side.

        [Route("Import")]

        public string Import(IFormCollection data)

        {

            if (data.Files.Count == 0)

                return null;

            Stream stream = new MemoryStream();

            IFormFile file = data.Files[0];

            int index = file.FileName.LastIndexOf('.');

            string type = index > -1 && index < file.FileName.Length - 1 ?

                file.FileName.Substring(index) : ".docx";

            file.CopyTo(stream);

            stream.Position = 0;


            EJ2DocumentEditor.WordDocument document = EJ2DocumentEditor.WordDocument.Load(stream, GetFormatType(type.ToLower()));

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);

            document.Dispose();

            return json;

        }

        //Import documents from web server.

        [Route("ImportFile")]

        public string ImportFile([FromBody] CustomParams param)

        {

            string path = this.hostEnvironment.WebRootPath + "\\IMO\\" + param.fileName;

            try

            {

                Stream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.ReadWrite);

                Syncfusion.EJ2.DocumentEditor.WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream, GetFormatType(path));

                string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);

                document.Dispose();

                stream.Dispose();

                return json;

            }

            catch

            {

                return "Failure";

            }

        }

        public class CustomParams

        {

            public string fileName

            {

                get;

                set;

            }

        }



        [Route("LoadDefault")]

        public string LoadDefault(string fileN)

        {

            string webRootPath = hostEnvironment.WebRootPath;

            string filePath = Path.Combine(webRootPath, "IMO", fileN);


            if (System.IO.File.Exists(filePath))

            {

                using (Stream stream = System.IO.File.OpenRead(filePath))

                {

                    stream.Position = 0;


                    Syncfusion.EJ2.DocumentEditor.WordDocument document = Syncfusion.EJ2.DocumentEditor.WordDocument.Load(stream, EJ2DocumentEditor.FormatType.Docx);

                    string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);

                    document.Dispose();

                    return json;

                }

            }

            else

            {

                // Handle case where file is not found

                // Return appropriate error message or status code

                return "File not found";

            }

        }


        //Save document in web server.

        [Route("Save")]

        public string Save([FromBody] CustomParameter param)

        {


            string path = this.hostEnvironment.WebRootPath + "\\Files\\" + param.fileName;

            Byte[] byteArray = Convert.FromBase64String(param.documentData);

            Stream stream = new MemoryStream(byteArray);

            EJ2DocumentEditor.FormatType type = GetFormatType(path);

            try

            {

                FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);


                if (type != EJ2DocumentEditor.FormatType.Docx)

                {

                    Syncfusion.DocIO.DLS.WordDocument document = new Syncfusion.DocIO.DLS.WordDocument(stream, Syncfusion.DocIO.FormatType.Docx);

                    document.Save(fileStream, GetDocIOFomatType(type));

                    document.Close();

                }

                else

                {

                    stream.Position = 0;

                    stream.CopyTo(fileStream);

                }

                stream.Dispose();

                fileStream.Dispose();

                return "Sucess";

            }

            catch

            {

                Console.WriteLine("err");

                return "Failure";

            }

        }


        [Route("ServerSave")]

        public void ServerSave([FromBody] SaveParameter data)

        {

            string name = data.FileName;

            string format = RetrieveFileType(name);

            if (string.IsNullOrEmpty(name))

            {

                name = "Document1.doc";

            }

            Syncfusion.DocIO.DLS.WordDocument document = EJ2DocumentEditor.WordDocument.Save(data.Content);

            FileStream fileStream = new FileStream(name, FileMode.OpenOrCreate, FileAccess.ReadWrite);

            document.Save(fileStream, FormatType.Docx);

            document.Close();

            fileStream.Close();

        }

        public class SaveParameter

        {

            public string Content { get; set; }

            public string FileName { get; set; }

        }


        private string RetrieveFileType(string name)

        {

            int index = name.LastIndexOf('.');

            string format = index > -1 && index < name.Length - 1 ?

                name.Substring(index) : ".doc";

            return format;

        }


        public class CustomParameter

        {

            public string fileName

            {

                get;

                set;

            }

            public string documentData

            {

                get;

                set;

            }

        }


        internal static EJ2DocumentEditor.FormatType GetFormatType(string fileName)

        {

            int index = fileName.LastIndexOf('.');

            string format = index > -1 && index < fileName.Length - 1 ? fileName.Substring(index + 1) : "";


            if (string.IsNullOrEmpty(format))

                throw new NotSupportedException("EJ2 Document editor does not support this file format.");

            switch (format.ToLower())

            {

                case "dotx":

                case "docx":

                case "docm":

                case "dotm":

                    return EJ2DocumentEditor.FormatType.Docx;

                case "dot":

                case "doc":

                    return EJ2DocumentEditor.FormatType.Doc;

                case "rtf":

                    return EJ2DocumentEditor.FormatType.Rtf;

                case "txt":

                    return EJ2DocumentEditor.FormatType.Txt;

                case "xml":

                    return EJ2DocumentEditor.FormatType.WordML;

                default:

                    throw new NotSupportedException("EJ2 Document editor does not support this file format.");

            }

        }


        internal static Syncfusion.DocIO.FormatType GetDocIOFomatType(EJ2DocumentEditor.FormatType type)

        {

            switch (type)

            {

                case EJ2DocumentEditor.FormatType.Docx:

                    return FormatType.Docx;

                case EJ2DocumentEditor.FormatType.Doc:

                    return FormatType.Doc;

                case EJ2DocumentEditor.FormatType.Rtf:

                    return FormatType.Rtf;

                case EJ2DocumentEditor.FormatType.Txt:

                    return FormatType.Txt;

                case EJ2DocumentEditor.FormatType.WordML:

                    return FormatType.WordML;

                default:

                    throw new NotSupportedException("DocIO does not support this file format.");

            }

        }


        public string WebPath()

        {

            return hostEnvironment.WebRootPath + "//IMO//";

        }


    }

}


It all works fine. But when I try to open a word doc using the button "open" in toolbar I receive an error like "File could not be loaded"

Thanks in advance for your support.

BRGDS

Ernst





2 Replies 1 reply marked as answer

DS Dhanush Sekar Syncfusion Team April 4, 2024 05:01 PM UTC

Hi Ernst,


We have checked the provided code snippet and found that you have missed to set service URL property for document editor container.

Please refer the below code

<ejs-documenteditorcontainer id="container" documentChange="onDocumentChange"


                                     enableToolbar="true" height="590px" serviceUrl="/api/DocumentEditor/"></ejs-documenteditorcontainer>



Regards,

Dhanush Sekar



ES Ernst Schomburg replied to Dhanush Sekar April 4, 2024 05:21 PM UTC

Hi,


Great!! That solved it!


Thank you very much!


BRGDS

Ernst


Marked as answer
Loader.
Up arrow icon