Is there an sample for Import from Word using Javascript (not Typescript)

Hi,

I want to implement the RichTextEditor with "Import from word" option, I went through the Demo - https://ej2.syncfusion.com/demos/#/bootstrap5/rich-text-editor/tools.html but its in the Typescript. Do you have  a similar sample using Javascript? 

Thanks

Sri


5 Replies

SN Sri Nistala June 18, 2024 07:35 PM UTC

Also, where can I find there a backend Aspnetcore Api code for Import and Export of word documents?

Thanks



VJ Vinitha Jeyakumar Syncfusion Team June 19, 2024 07:24 AM UTC

Hi Sri Nistala,


Query 1. "I want to implement the RichTextEditor with "Import from word" option, I went through the Demo , but its in the Typescript. Do you have  a similar sample using Javascript? "

Yes, we have demo samples in javascript for import and export from RichTextEditor. Please find the link below,


Query 2. "where can I find there a backend Aspnetcore Api code for Import and Export of word documents?"

We will include the backend controller.cs file into the demo samples and it will be published live in any of our upcoming volume releases. Now you can find the server side code to import and export Word below,

Code snippet:
       
       public IWebHostEnvironment _webHostEnvironment;

        [AcceptVerbs("Post")]
        [EnableCors("AllowAllOrigins")]
        [Route("ImportFromWord")]
        public IActionResult ImportFromWord(IList<IFormFile> UploadFiles)
        {
            string HtmlString = string.Empty;
            if (UploadFiles != null)
            {
                foreach (var file in UploadFiles)
                {
                    string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    filename = _webHostEnvironment.WebRootPath + $@"\{filename}";
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    using (var mStream = new MemoryStream())
                    {
                        new WordDocument(file.OpenReadStream(), FormatType.Rtf).Save(mStream, FormatType.Html);
                        mStream.Position = 0;
                        HtmlString = new StreamReader(mStream).ReadToEnd();
                    };
                    HtmlString = ExtractBodyContent(HtmlString);
                    HtmlString = SanitizeHtml(HtmlString);
                    System.IO.File.Delete(filename);
                }
                return Ok(HtmlString);
            }
            else
            {
                Response.Clear();
                // Return an appropriate status code or message
                return BadRequest("No files were uploaded.");
            }
        }

        private string ExtractBodyContent(string html)
        {
            if (html.Contains("<html") && html.Contains("<body"))
            {
                return html.Remove(0, html.IndexOf("<body>") + 6).Replace("</body></html>", "");
            }
            return html;
        }

      private string SanitizeHtml(string html)
        {
            // Remove or replace non-ASCII or control characters
            // For example, you can use regular expressions to replace them with spaces
            // Regex pattern to match non-ASCII or control characters: [^\x20-\x7E]
            return Regex.Replace(html, @"[^\x20-\x7E]", " ");
        }


        [AcceptVerbs("Post")]
        [EnableCors("AllowAllOrigins")]
        [Route("ExportToDocx")]
        public FileStreamResult ExportToDocx([FromBody] ExportParam args)
        {
            string htmlString = args.html;
            if (htmlString == null && htmlString == "")
            {
                return null;
            }
            using (WordDocument document = new WordDocument())
            {
                document.EnsureMinimal();
                //Hooks the ImageNodeVisited event to open the image from a specific location
                document.HTMLImportSettings.ImageNodeVisited += OpenImage;
                //Validates the Html string
                bool isValidHtml = document.LastSection.Body.IsValidXHTML(htmlString, XHTMLValidationType.None);
                //When the Html string passes validation, it is inserted to the document
                if (isValidHtml)
                {
                    //Appends the Html string to first paragraph in the document
                    document.Sections[0].Body.Paragraphs[0].AppendHTML(htmlString);
                }
                //Unhooks the ImageNodeVisited event after loading HTML
                document.HTMLImportSettings.ImageNodeVisited -= OpenImage;
                //Creates file stream.
                MemoryStream stream = new MemoryStream();
                document.Save(stream, FormatType.Docx);
                stream.Position = 0;
                //Download Word document in the browser
                return File(stream, "application/msword", "Result.docx");
            }
        }

       public class ExportParam
        {
            public string html { get; set; }
        }

Regards,
Vinitha



SN Sri Nistala June 20, 2024 04:13 PM UTC

Thanks Vanitha, in the  ExportToDocx , the definition of the "OpenImage" is missing. Could you share that as well?




SN Sri Nistala June 20, 2024 07:23 PM UTC

Also, I'm facing another problem, if the RTE is inside a Form then on clicking the "import from word" button, its submitting the Form. 

for eg- https://stackblitz.com/edit/mewgf4?file=index.js,index.html


I placed the RTE inside the form and on clicking the import from word it immediately submits the form.



VJ Vinitha Jeyakumar Syncfusion Team June 21, 2024 06:30 AM UTC

Hi Sri Nistala,

Query 1. "in the  ExportToDocx , the definition of the "OpenImage" is missing. Could you share that as well?"

Please find the code snippets for OpenImage function below,

Code snippet:
 private static void OpenImage(object sender, ImageNodeVisitedEventArgs args)
        {
            if (args.Uri.StartsWith("https://"))
            {
                WebClient client = new WebClient();
                //Download the image as a stream.
                byte[] image = client.DownloadData(args.Uri);
                Stream stream = new MemoryStream(image);
                //Set the retrieved image from the input Markdown.
                args.ImageStream = stream;
            }
        }

Query 2. "I'm facing another problem, if the RTE is inside a Form then on clicking the "import from word" button, its submitting the Form. "

Your reported issue can be resolved by adding "type" as button to the button elements in the toolbar template. Please check the code and modified sample below,

Code snippet:
 
toolbarSettings: {
    items: [
      {
        tooltipText: 'Import from Word',
        template: `<button class="e-tbar-btn e-control e-btn e-lib e-icon-btn" type="button" tabindex="-1" id="custom_tbarbtn_1" style="width:100%">
                      <span class="e-icons e-rte-import-doc e-btn-icon"></span></button>`,
        click: importContentFromWord,
      },
      {
        tooltipText: 'Export to Word',
        template: `<button class="e-tbar-btn e-control e-btn e-lib e-icon-btn" tabindex="-1" type="button" id="custom_tbarbtn_2" style="width:100%">
                      <span class="e-icons e-rte-export-doc e-btn-icon"></span></button>`,
        click: exportContentToWord,
      },
      {
        tooltipText: 'Export to PDF',
        template: `<button class="e-tbar-btn e-control e-btn e-lib e-icon-btn" tabindex="-1"   type="button" id="custom_tbarbtn_3" style="width:100%">
                      <span class="e-icons e-rte-export-pdf e-btn-icon"></span></button>`,
        click: exportContentToPDF,
      },
     
    ],
  },


Regards,
Vinitha

Loader.
Up arrow icon