Copied RSS Feed

Blazor

Easily Import and Export RTF Files in Blazor with Accuracy

Importing and exporting are indispensable parts of development. While working on a blog, website, feedback portal, or any other editor content, we frequently export and import RTF (rich text format) files in them.

The Syncfusion Blazor Rich Text Editor provides support to easily import and export RTF files. It is a feature-rich WYSIWYG HTML and Markdown editor. We can use it to create blogs, forum posts, notes sections, support tickets, comment sections, messaging applications, and more. The control provides an efficient user interface for a better editing experience with mobile support. It has a variety of tools to edit and format rich content and returns valid HTML markup or Markdown (MD) content. Also, it allows users to insert images, links, tables, and lists with modular architectures.

In this blog, we will cover the procedures to import and export RTF files in the Blazor Rich Text Editor using the Syncfusion.DocIO and Syncfusion.EJ.Export assemblies.

Prerequisites

For this blog, we are going to demonstrate how to import and export RTF files in a Blazor server-side application. So, we need the following prerequisites:

Create a Blazor server-side application

First, let’s create a Blazor server-side application and configure the Syncfusion Blazor services.

Configure the Blazor Rich Text Editor

Follow these steps to configure the Blazor Rich Text Editor in your application:

  1. Add the Blazor Rich Text Editor component in the index.razor file.
    <SfRichTextEditor @bind-Value="rteValue" >
    </SfRichTextEditor>
    @code {
    
    private string rteValue {get; set; } = "<p>The Rich Text Editor component is a WYSIWYG ('what you see is what you get') editor that provides the best user experience to create and update the content. Users can format their content using standard toolbar commands. </p>";
    
    }
  2. Then, configure the most-used toolbar items like Bold and Italic for the SfRichTextEditor as shown in the following code example.
    <SfRichTextEditor @bind-Value="rteValue">
     <RichTextEditorToolbarSettings Items="Tools">
     </RichTextEditorToolbarSettings>
    </SfRichTextEditor>
    
    @code {
            ……
            ……
    private List<ToolbarItemModel> Tools = new List<ToolbarItemModel>()
     {
    
     new ToolbarItemModel() { Command = ToolbarCommand.Bold },
     new ToolbarItemModel() { Command = ToolbarCommand.Italic },
     new ToolbarItemModel() { Command = ToolbarCommand.Underline },
     new ToolbarItemModel() { Command = ToolbarCommand.Separator },
     new ToolbarItemModel() { Command = ToolbarCommand.Formats },
     new ToolbarItemModel() { Command = ToolbarCommand.Alignments },
     new ToolbarItemModel() { Command = ToolbarCommand.OrderedList },
     new ToolbarItemModel() { Command = ToolbarCommand.UnorderedList },
     new ToolbarItemModel() { Command = ToolbarCommand.Separator },
     new ToolbarItemModel() { Command = ToolbarCommand.CreateLink },
     new ToolbarItemModel() { Command = ToolbarCommand.Image },
     new ToolbarItemModel() { Command = ToolbarCommand.Separator },
     new ToolbarItemModel() { Command = ToolbarCommand.SourceCode },
     new ToolbarItemModel() { Command = ToolbarCommand.Undo },
     new ToolbarItemModel() { Command = ToolbarCommand.Redo } };
    }

Add the Syncfusion.DocIO.Net.Core and Syncfusion.EJ.Export libraries

  1. To import the Syncfusion.DocIO namespace, install the Syncfusion.DocIO.Net.Core NuGet package in your application.
    dotnet add package Syncfusion.DocIO.Net.Core --version 19.2.0.56
  2. To import the Syncfusion.EJ.Export namespace, install the Syncfusion.EJ.Export NuGet package in your application.
    dotnet add package Syncfusion.EJ.Export --version 19.2.0.56

Import an RTF document into Blazor Rich Text Editor

Follow these steps to import the RTF files into the Blazor Rich Text Editor control:

  1. Let’s render the uploader component within the Import custom toolbar item which will import the RTF content into the Blazor Rich Text Editor. Refer to the following code.
    <SfRichTextEditor  @bind-Value="rteValue">
     <RichTextEditorToolbarSettings Items="Tools">
      <RichTextEditorCustomToolbarItems>
       <RichTextEditorCustomToolbarItem Name="Import">
        <Template>
         <SfUploader ID="UploadFiles" ShowFileList="false" CssClass="e-import">
          <UploaderAsyncSettings SaveUrl="api/SampleData/Import"></UploaderAsyncSettings>
          <UploaderEvents Success="@onSuccess"></UploaderEvents>
          <UploaderButtons>
           <UploaderButtonsProps Browse=""></UploaderButtonsProps>
          </UploaderButtons>
         </SfUploader>
        </Template>
       </RichTextEditorCustomToolbarItem>
      </RichTextEditorCustomToolbarItems>
     </RichTextEditorToolbarSettings>
    </SfRichTextEditor>
    
    @code{
                ……
                ……
     private List<ToolbarItemModel> Tools = new List<ToolbarItemModel>()
     {
      ……
                  ……
                  ……
     new ToolbarItemModel() { Name = "Import", TooltipText = "Import the RTF document" }
     }
    
            public void onSuccess(SuccessEventArgs args)
     {
      var headers = args.Response.Headers.ToString();
      var header = headers.Split("rtevalue: ");
      header = header[1].Split("\r");
      this.rteValue = header[0];
     }
    }

    We have added the controller for importing the RTF content in the Uploader component.

  2. Now, set the imported RTF content to the Rich Text Editor’s value property in the Uploader success event. Refer to the following code example.
    Controller
    [HttpPost]
    [Route("Import")]
    public string Import(IList<IFormFile> UploadFiles)
    {
         string HtmlString = string.Empty;
         if (UploadFiles != null)
         {
              foreach (var file in UploadFiles)
              {
                   string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                   filename = hostingEnv.WebRootPath + "\\files" + $@"\{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);
                   var str = HtmlString.Replace("\r\n", "");
                   Response.Headers.Add("rteValue", str);
              }
          }
          return HtmlString;
    }
    
    public string ExtractBodyContent(string html)
       {
           if (html.Contains("<html") && html.Contains("<body"))
           {
              return html.Remove(0, html.IndexOf("<body>") + 6).Replace("</body></html>", "");
           }
           return html;
       }
  3. Now, click on the Import button to import the desired RTF document into the Blazor Rich Text Editor content area.

Export the Blazor Rich Text Editor content to an RTF document

Follow these steps to export the Rich Text Editor content to an RTF file:

  1. We are going to render the Button component within the Export custom toolbar item to export the Rich Text Editor content to an RTF document. Refer to the following code example.
    <SfRichTextEditor @bind-Value="rteValue">
     <RichTextEditorToolbarSettings Items="Tools">
      <RichTextEditorCustomToolbarItems>
       ……
                                            ……
    
       <RichTextEditorCustomToolbarItem Name="Export">
        <Template>
         <SfButton OnClick="OnExport" CssClass="e-icons e-export"></SfButton>
        </Template>
       </RichTextEditorCustomToolbarItem>
      </RichTextEditorCustomToolbarItems>
     </RichTextEditorToolbarSettings>
    </SfRichTextEditor>
    
    @code{
            ……
            ……
            ……
    public async Task OnExport()
     {
    
      HttpClientHandler clientHandler = new HttpClientHandler();
      clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
      HttpClient client = new HttpClient(clientHandler);
      var content = new StringContent(rteValue);
      content.Headers.Add("value", rteValue);
      await client.PostAsync(navigationManager.Uri + "api/SampleData/ExportToRtf", content);
      await SampleInterop.SaveAs<object>(jsRuntime, "Sample.rtf");
     }
    }
  2. Then, add the JSinterop script code in the _Host.cshtml file to download the RTF document in the browser.
    function saveAsFile(filename, bytesBase64) {
                if (navigator.msSaveBlob) {
                    //Download document in Edge browser.
                    var data = window.atob(bytesBase64);
                    var bytes = new Uint8Array(data.length);
                    for (var i = 0; i < data.length; i++) {
                        bytes[i] = data.charCodeAt(i);
                    }
                    var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
                    navigator.msSaveBlob(blob, filename);
                }
                else {
                    var link = document.createElement('a');
                    link.download = filename;
                    link.href = "data:application/octet-stream;base64," + bytesBase64;
                    document.body.appendChild(link); // Needed for Firefox.
                    link.click();
                    document.body.removeChild(link);
                }
            }

    Thus, we have successfully added the controller for exporting the RTF content from the Blazor Rich Text Editor.

  3. Now, add the following code to the controller to easily download the exported RTF document.
    [HttpPost]
    [Route("ExportToRtf")]
    public FileStreamResult ExportToRtf(string value)
    {
         string htmlText = Request.Headers["value"][0];
         WordDocument document = GetDocument(htmlText);
         //Saves the Word document to MemoryStream.
         MemoryStream stream = new MemoryStream();
         document.Save(stream, FormatType.Rtf);
         stream.Position = 0;
         FileStream outputStream = new FileStream("Sample.rtf", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
         document.Save(outputStream, FormatType.Rtf);
         document.Close();
         outputStream.Flush();
         outputStream.Dispose();
         //Download Word document in the browser. 
         return File(stream, "application/msword", "Sample.rtf");
    }
    
    
    public WordDocument GetDocument(string htmlText)
    {
         WordDocument document = null;
         MemoryStream stream = new MemoryStream();
         StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.Default);
         htmlText = htmlText.Replace("\"", "'");
         XmlConversion XmlText = new XmlConversion(htmlText);
         XhtmlConversion XhtmlText = new XhtmlConversion(XmlText);
         writer.Write(XhtmlText.ToString());
         writer.Flush();
         stream.Position = 0;
         document = new WordDocument(stream, FormatType.Html, XHTMLValidationType.None);
         return document;
    }
  4. Now, click on the Export button to export the Rich Text Editor content to the sample .rtf file.

GitHub resource

You can check out the complete project from Import and export RTF document in Blazor Rich Text Editor demo.

Conclusion

Thanks for reading! I hope you now have a clear idea of how to import and export RTF files using the Blazor Rich Text Editor by using the Syncfusion.DocIO and Syncfusion.EJ.Export assemblies. Try out the steps provided in this blog post and leave your feedback in the comments section below!

Also, refer to our Blazor Rich Text Editor online demo and documentation for more details. If you are new to Syncfusion, try our control’s features by downloading a free trial.

You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Related blogs

Meet the Author

Thangavel E

As a Product Manager at Syncfusion, Thangavel Ellappan manages the web product development (especially the RichTextEditor component) and helps extend its design and functionality based on real-time usability. He is a tech enthusiast with 6+ years of experience in full-stack web product development and focuses mainly on delivering products with perfection.