DEV Community

Cover image for Seamlessly Export Blazor Rich Text Editor Content to PDF
Jollen Moyani for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Seamlessly Export Blazor Rich Text Editor Content to PDF

The Syncfusion 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:

Create a Blazor server-side application

First, create a Blazor server-side app and configure the Syncfusion Blazor services.

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.

<SfRichTextEditor SaveInterval="1" @bind-Value="@rteValue">
  <!-- Rich Text Editor configuration -->
</SfRichTextEditor>
Enter fullscreen mode Exit fullscreen mode

2.Now, configure the toolbar items list for the Rich Text Editor like in the following code example.

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 }
    };
Enter fullscreen mode Exit fullscreen mode

3.Include the ExportPDF item in the toolbar to export the Rich Text Editor content to PDF format.

<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>
Enter fullscreen mode Exit fullscreen mode

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

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 }
};
Enter fullscreen mode Exit fullscreen mode

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 and Syncfusion.Blazor.PdfViewer NuGet packages.

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();
        }
     }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

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; }
}
Enter fullscreen mode Exit fullscreen mode

3.Now, add the JavaScript code to the _Host.cshtml file to enable downloading the PDF when the export button is clicked.

<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>
Enter fullscreen mode Exit fullscreen mode

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.

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());
   }

}
Enter fullscreen mode Exit fullscreen mode

Refer to the following output image.

Exporting Blazor Rich Text Editor Content to PDF

Exporting Blazor Rich Text Editor Content to PDF

GitHub reference

For more details, refer to the demo for Exporting Blazor Rich Text Editor to PDF from this GitHub repository.

Conclusion

Thanks for reading! In this blog, we’ve seen how to export the 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, support portal, or feedback portal. We are always happy to assist you!

Related blogs

Top comments (0)