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:
- 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>
- 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 } };
- 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:
- 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(); } } } }
- 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; } }
- 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>
- 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.
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
- Introducing the New Blazor Image Editor Component
- What’s New in Blazor Charts: 2023 Volume 2
- What’s New in Blazor Diagram: 2023 Volume 2
- What’s New in Blazor: 2023 Volume 2
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.