Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (152).NET Core  (26)Angular  (49)ASP.NET  (48)ASP.NET Core  (64)ASP.NET MVC  (86)Azure  (29)Blazor  (107)DocIO  (20)Essential JS 2  (72)Essential Studio  (164)File Formats  (20)Flutter  (115)JavaScript  (150)Microsoft  (102)PDF  (59)React  (33)Succinctly series  (124)Syncfusion  (490)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (26)Webinar  (27)Windows Forms  (55)WinUI  (27)WPF  (123)Xamarin  (132)XlsIO  (24)Other CategoriesBarcode  (4)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (108)Chart  (53)Cloud  (10)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (5)DataGrid  (50)Development  (263)Doc  (7)DockingManager  (1)eBook  (94)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (20)Extensions  (15)File Manager  (4)Gantt  (9)Gauge  (7)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (233)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (25)Performance  (7)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (6)Road Map  (9)Scheduler  (29)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (19)Solution Services  (2)Spreadsheet  (10)SQL  (7)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (65)UI  (139)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (19)Visual Studio Code  (13)Web  (227)What's new  (146)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Easily Import and Export RTF Files in Blazor with Accuracy

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.
    Importing RTF Document into Blazor Rich Text Editor

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.Exporting the Blazor Rich Text Editor content to RTF document

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

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top