Seamlessly Export Blazor Rich Text Editor Content to PDF
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (182).NET Core  (28).NET MAUI  (233)Angular  (117)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (42)Black Friday Deal  (1)Blazor  (244)BoldSign  (15)DocIO  (24)Essential JS 2  (110)Essential Studio  (201)File Formats  (74)Flutter  (140)JavaScript  (227)Microsoft  (122)PDF  (86)Python  (1)React  (107)Streamlit  (1)Succinctly series  (131)Syncfusion  (993)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (165)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (11)Business intelligence  (55)Button  (4)C#  (164)Chart  (154)Chart of the week  (62)Cloud  (16)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (74)Development  (694)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (31)File Manager  (8)Gantt  (23)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (530)Mobile MVC  (9)OLAP server  (2)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (48)Performance  (13)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (8)Reporting / Back Office  (9)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (5)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (32)Solution Services  (4)Spreadsheet  (11)SQL  (15)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (426)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (648)What's new  (354)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Seamlessly Export Blazor Rich Text Editor Content to PDF

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>
  1. 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 }
        };
  1. 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>

    Rember 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 }
    };

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

    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 forumssupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Comments (2)

Hi, thanks for blog. I am using GitHub repo.
I have internal error on place
//Convert HTML string to PDF document.
PdfDocument document = htmlConverter.Convert(content, “”);

Syncfusion.Pdf.PdfException
HResult=0x80131500
Message=Failed to convert webpage
Source=Syncfusion.HtmlConverter.Portable
StackTrace:
at Syncfusion.HtmlConverter.BlinkConverter.Convert(String url)
at Syncfusion.HtmlConverter.BlinkConverter.Convert(String htmlString, String baseurl)
at Syncfusion.HtmlConverter.HtmlToPdfConverter.Convert(String html, String baseurl)
at BlazorRichTextEditorToPDF.Data.ExportService.ExportAsPdf(String content) in W:\Metric repos\blazor-richtexteditor-export-pdf-master\blazor-richtexteditor-export-pdf-master\Data\ExportService.cs:line 25

This exception was originally thrown at this call stack:
[External Code]

Inner Exception 1:
PdfException: Failed to convert webpage

Any suggestions?
Best regards Igor

Hi Igora,

We have checked the GitHub sample (https://github.com/SyncfusionExamples/blazor-richtexteditor-export-pdf) for Exporting Blazor Rich Text Editor to PDF using Blink rendering engine, but it is working properly on our end. Our Html Blink converter internally make use of chromium executable in headless mode for converting HTML to PDF document. We suspect that the reported issue may occurs due to particular HTML content itself. And please make sure your application does not blocks or restrict the internal chrome browser to perform conversion? Do you have any application or software that prevents this background browser activities on your end? If you have any restriction, please let us know.

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/blazor-richtexteditor-export-pdf1573393650

Please refer the below troubleshooting link for more details,

https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/troubleshooting#failed-to-convert-webpage-exception

If still you are facing the same issue, we request you to share the more details such as HTML content/URL, simplified sample, product version, package list, environmental details (OS, Bit version, culture settings) to check the issue on our end. So, that it will be helpful for us to analyze and assist you further on this.

Regards
Thangavel

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed