Seamlessly Export Blazor Rich Text Editor Content to PDF
Tags: blazor, webdev, pdf, richtexteditor
Published: 2023-08-08 13:46:17

---
title: Seamlessly Export Blazor Rich Text Editor Content to PDF
published: true
date: 2023-08-08 11:05:11 UTC
tags: blazor, webdev, pdf, richtexteditor
canonical_url: https://www.syncfusion.com/blogs/post/export-blazor-rich-text-editor-to-pdf.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4b5krj46cros3veogjfn.png
---
The Syncfusion [Blazor Rich Text Editor](https://www.syncfusion.com/blazor-components/blazor-wysiwyg-rich-text-editor "Blazor Rich Text Editor") is a feature-rich WYSIWYG HTML and Markdown (MD) editor. It is used to create blogs, forum posts, notes sections, support tickets (incidents), comment sections, messaging applications, and more. The control provides an efficient user interface with mobile support for a better editing experience. It has various tools to edit and format rich content and it returns valid HTML markup or Markdown content. It allows users to insert images, links, tables, and lists with modular architectures.

In this blog, we will see how to export the Blazor Rich Text Editor content to a PDF document.

Let’s get started!

## Prerequisites

Before proceeding, make sure you have the following prerequisites:

- [Visual Studio 2022,](https://visualstudio.microsoft.com/vs/ "Visual Studio")
- [.NET Core 3.0](https://dotnet.microsoft.com/download/dotnet-core/3.0 "Download .NET Core 3.0") or above,
- [Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package](https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Net.Windows/ "Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package").

## Create a Blazor server-side application

First, [create a Blazor server-side app 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 "Getting started with Blazor server-side app in Visual Studio").

## Configure the Syncfusion Blazor Rich Text Editor and custom toolbar

Follow these steps to configure the Blazor Rich Text Editor’s toolbar items:

1.Add the Blazor Rich Text Editor component to the **index.razor** file and set the value of the **SaveInterval** property as 1 to save the editor content immediately in the **Value** property.
```xml
<SfRichTextEditor SaveInterval="1" @bind-Value="@rteValue">
  <!-- Rich Text Editor configuration -->
</SfRichTextEditor>
```

2.Now, configure the toolbar items list for the Rich Text Editor like in the following code example.
```csharp
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.StrikeThrough },
        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 }
    };
```

3.Include the **ExportPDF** item in the toolbar to export the Rich Text Editor content to PDF format.
```xml
<SfRichTextEditor ID="exportRTEintoPDF" @bind-Value="@rteValue" SaveInterval="1">
  <RichTextEditorToolbarSettings Items="@Tools">
     <RichTextEditorCustomToolbarItems>
        <RichTextEditorCustomToolbarItem Name="ExportPDF">
           <Template>
             <SfButton @onclick="ClickHandler" CssClass="e-tbar-btn" IconCss="e-icons e-export-pdf"></SfButton>
           </Template>
        </RichTextEditorCustomToolbarItem>
     </RichTextEditorCustomToolbarItems>
 </RichTextEditorToolbarSettings>
</SfRichTextEditor>
```

Remember to add the **ExportPDF** toolbar item’s Name field to the toolbar items list.

```csharp
private List<ToolbarItemModel> Tools = new List<ToolbarItemModel>()
{
    new ToolbarItemModel() { Name = "ExportPDF", TooltipText = "Export PDF"},
    new ToolbarItemModel() { Command = ToolbarCommand.Separator },
    new ToolbarItemModel() { Command = ToolbarCommand.Bold },
    new ToolbarItemModel() { Command = ToolbarCommand.Italic },
    new ToolbarItemModel() { Command = ToolbarCommand.Underline },
    new ToolbarItemModel() { Command = ToolbarCommand.StrikeThrough },
    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 }
};
```

## Export the Blazor Rich Text Editor content to PDF

Follow these steps to export the Blazor Rich Text Editor content to a PDF document:

1.Write a service that exports the editor content to a document stream using [**Syncfusion.HtmlToPdfConverter.Net.Windows**](https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Net.Windows "Syncfusion.HtmlToPdfConverter.Net.Windows NuGet package") and [**Syncfusion.Blazor.PdfViewer**](https://www.nuget.org/packages/Syncfusion.Blazor.PdfViewer/ "Syncfusion.Blazor.PdfViewer NuGet package") NuGet packages.
```csharp
Using Syncfusion.Pdf;
using Syncfusion.HtmlConverter;

namespace BlazorRichTextEditorToPDF.Data
{
   public class ExportService
   {
      public MemoryStream ExportAsPdf(string content)
      {
        try
        {
            //Initialize HTML-to-PDF converter.
            HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
            BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
            //Set Blink viewport size.
            blinkConverterSettings.ViewPortSize = new Syncfusion.Drawing.Size(1280, 0);
            //Assign Blink converter settings to HTML converter.
            htmlConverter.ConverterSettings = blinkConverterSettings;
            //Convert HTML string to PDF document.
            PdfDocument document = htmlConverter.Convert(content,””);
            //Create memory stream.
            MemoryStream stream = new MemoryStream();
            //Save the document to the memory stream.
            Document.Save(stream);
            return stream;
        }
        catch
        {
           return new MemoryStream();
        }
     }
  }
}
```

2.To communicate from the server-side to the client-side, add the **SampleInterop** class and define the required code, as shown, in a separate file ( **SampleInterop.cs** ) to the project.
```csharp
public static class SampleInterop
{
   public static ValueTask<T> SaveAs<T>(this IJSRuntime JSRuntime, string filename, byte[] data)
   {
      try
      {
         return JSRuntime.InvokeAsync<T>("saveAsFile", filename, Convert.ToBase64String(data));
      }
      catch (Exception e)
      {
         return SampleInterop.LogError<T>(JSRuntime, e, "");
      }
   }

   public static ValueTask<T> LogError<T>(IJSRuntime jsRuntime, Exception e, string message = "")
   {

      ErrorMessage error = new ErrorMessage();
      error.Message = message + e.Message;
      error.Stack = e.StackTrace;
      if (e.InnerException != null)
      {
         error.Message = message + e.InnerException.Message;
         error.Stack = e.InnerException.StackTrace;
      }
      return jsRuntime.InvokeAsync<T>(
                "jsInterop.throwError", error);
   }

}
public class ErrorMessage
{
    [JsonProperty("message")]
    public string Message { get; set; }
    [JsonProperty("stack")]
    public string Stack { get; set; }
}
```

3.Now, add the JavaScript code to the **\_Host.cshtml** file to enable downloading the PDF when the export button is clicked.
```xml
<script>
   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);
      }
  }
</script>
```

4.Finally, when clicking the custom toolbar button **ExportPDF** , it will call the **ClickHandler** method to utilize the service for exporting the Rich Text Editor content to a PDF document, and it will initiate the download process.
```csharp
private async Task ClickHandler()
{
   string framedValue = @"<div class='e-rte-content'><style>" + richTextEditorStyle + "</style>" + rteValue + "</div>";
   ExportService exportService = new ExportService();
   using (MemoryStream excelStream = exportService.ExportAsPdf(framedValue))
   {
      await SampleInterop.SaveAs<object>(jsRuntime, "Sample.pdf", excelStream.ToArray());
   }

}
```

Refer to the following output image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/08/Exporting-Blazor-Rich-Text-Editor-Content-to-PDF.gif" alt="Exporting Blazor Rich Text Editor Content to PDF" style="width:100%">

  <figcaption>Exporting Blazor Rich Text Editor Content to PDF</figcaption>

</figure>

## GitHub reference

For more details, refer to the demo for Exporting Blazor Rich Text Editor to PDF from this [GitHub](https://github.com/SyncfusionExamples/blazor-richtexteditor-export-pdf "Exporting Blazor Rich Text Editor content to PDF GitHub demo") repository.

## Conclusion

Thanks for reading! In this blog, we’ve seen how to export the [Blazor Rich Text Editor](https://www.syncfusion.com/blazor-components/blazor-wysiwyg-rich-text-editor "Blazor Rich Text Editor") content to a PDF document. Try out the steps in this blog and leave your feedback in the comments section!  

You can also contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forums"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Introducing the New Blazor Image Editor Component](https://www.syncfusion.com/blogs/post/new-blazor-image-editor.aspx "Blog: Introducing the New Blazor Image Editor Component")
- [What’s New in Blazor Charts: 2023 Volume 2](https://www.syncfusion.com/blogs/post/whats-new-blazor-charts.aspx "Blog: What’s New in Blazor Charts: 2023 Volume 2")
- [What’s New in Blazor Diagram: 2023 Volume 2](https://www.syncfusion.com/blogs/post/whats-new-blazor-diagram-2023-volume-2.aspx "Blog: What’s New in Blazor Diagram: 2023 Volume 2")
- [What’s New in Blazor: 2023 Volume 2](https://www.syncfusion.com/blogs/post/whats-new-blazor-2023-volume-2.aspx "Blog: What’s New in Blazor: 2023 Volume 2")