Easily Import and Export RTF Files in Blazor with Accuracy
Tags: blazor, csharp, dotnet, webdev
Published: 2021-10-20 10:37:31

---
title: Easily Import and Export RTF Files in Blazor with Accuracy
published: true
date: 2021-10-20 10:00:18 UTC
tags: blazor, csharp, dotnet, webdev
canonical_url: https://www.syncfusion.com/blogs/post/easily-import-and-export-rtf-files-in-blazor-with-accuracy.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyo77bj9xyoeeni71aqb.png
---

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)](https://en.wikipedia.org/wiki/Rich_Text_Format "Link to Wikipeida page for Rich Text Format") files in them.

The Syncfusion [Blazor Rich Text Editor](https://www.syncfusion.com/blazor-components/blazor-wysiwyg-rich-text-editor "Link to 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:

- [Visual Studio 2019](https://visualstudio.microsoft.com/vs/ "Link to Visual Studio 2019").
- [.NET Core 3.0 ](https://dotnet.microsoft.com/download/dotnet-core/3.0 "Link to .NET Core 3.0")or above.
- [Syncfusion.DocIO.Net.Core](https://www.nuget.org/packages/Syncfusion.DocIO.Net.Core/ "Link to Syncfusion.DocIO.Net.Core NuGet Package")
- [Syncfusion.EJ.Export](https://www.nuget.org/packages/Syncfusion.EJ.Export/ "Link to Syncfusion.EJ.Export NuGet Package")

## Create a Blazor server-side application

First, let’s [create a Blazor server-side application and configure the Syncfusion Blazor services](https://blazor.syncfusion.com/documentation/getting-started/blazor-server-side-visual-studio-2019/#getting-started-with-syncfusion-blazor-components-in-blazor-server-side-app-in-visual-studio-2019 "Link to Getting started with Blazor Server Side App in VS 2019").

## 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.
```js
<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.
```js
<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](https://www.nuget.org/packages/Syncfusion.DocIO.Net.Core/ "Link to 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](https://www.nuget.org/packages/Syncfusion.EJ.Export/ "Link to 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.
```js
<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**
```csharp
[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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/10/Importing-RTF-Document-into-Blazor-Rich-Text-Editor.png)

## 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.
```js
<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.
```csharp
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.
```csharp
[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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/10/Exporting-the-Blazor-Rich-Text-Editor-content-to-RTF-document.png)

## GitHub resource

You can check out the complete project from [Import and export RTF document in Blazor Rich Text Editor demo](https://github.com/SyncfusionExamples/blazor-wysiwyg-rich-text-editor-rtf-import-export "Link to Blazor: Rich Text Editor for import and export the RTF document demo on GitHub").

## 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](https://www.syncfusion.com/blazor-components/blazor-wysiwyg-rich-text-editor "Link to 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](https://blazor.syncfusion.com/demos/rich-text-editor/overview?theme=bootstrap4 "Link to Example of Overview in Blazor Rich Text Editor Component") and [documentation](https://blazor.syncfusion.com/documentation/rich-text-editor/getting-started "Link to Getting Started with Blazor RichTextEditor Component") for more details. If you are new to Syncfusion, try our control’s features by downloading a [free trial](https://www.syncfusion.com/downloads "Link to the free evaluation of the Syncfusion Essential Studio").

You can also contact us through our [support forums](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac/ "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/ "Link to Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [What’s New in 2021 Volume 3: Blazor](https://dev.to/sureshmohan/what-s-new-in-2021-volume-3-blazor-21jh-temp-slug-8656328 "Link to What’s New in 2021 Volume 3: Blazor blog")
- [Easily Visualize Online Maps in a Blazor Application](https://dev.to/syncfusion/easily-visualize-online-maps-in-a-blazor-application-426n "Link to Easily Visualize Online Maps in a Blazor Application blog")
- [Authentication Support in Syncfusion Blazor Template Studio: A Complete Guide](https://dev.to/sureshmohan/authentication-support-in-syncfusion-blazor-template-studio-a-complete-guide-58j-temp-slug-1598912 "Link to Authentication Support in Syncfusion Blazor Template Studio: A Complete Guide blog")
- [Schedule Your Tasks Like A Pro in Blazor Applications](https://dev.to/karthickramasamy08/schedule-your-tasks-like-a-pro-in-blazor-applications-d77-temp-slug-6326719 "Link to Schedule Your Tasks Like A Pro in Blazor Applications blog")