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.
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:
First, let’s create a Blazor server-side application and configure the Syncfusion Blazor services.
Follow these steps to configure the Blazor Rich Text Editor in your application:
<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>"; }
<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 } }; }
dotnet add package Syncfusion.DocIO.Net.Core --version 19.2.0.56 |
dotnet add package Syncfusion.EJ.Export --version 19.2.0.56 |
Follow these steps to import the RTF files into the Blazor Rich Text Editor control:
<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.
[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; }
Follow these steps to export the Rich Text Editor content to an RTF file:
<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"); } }
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.
[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; }
You can check out the complete project from Import and export RTF document in Blazor Rich Text Editor demo.
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 forums, Direct-Trac, or feedback portal. We are always happy to assist you!