Export RichTextEditor content to PDF with images

Hello,

I have a dialog with RichTextEditor in it. I have to create a PDF document programatically from the editor's formatted content, which sometimes contains images as well.

In addition I would like to know if I can print (by clicking on the printer button) the editor's content with inserted images? I tried this function, but in print, only the file name appeared in place of the image. Another formatted text was printed well.

Is there any way to achive the mentioned functionalities?

Thanks in advance!

Regards,
Istvan Szöke

1 Reply

IS Indrajith Srinivasan Syncfusion Team May 14, 2020 02:42 PM UTC

Hi Szöke,

Greetings from Syncfusion support,

Query 1: “I have a dialog with RichTextEditor in it. I have to create a PDF document programatically from the editor's formatted content, which sometimes contains images as well.“
 

We have validated your reported query. Yes, we can convert Rich Text Editor content to PDF format with images and content, by following the below documentation steps.

Documentation: https://help.syncfusion.com/file-formats/pdf/create-pdf-document-in-blazor

 
Steps to configure in your project  
  
  • Download and install our Essential HTML converter, it can be downloaded from
  • Click more downloads option from the required product version. Refer to the following screenshot.
 
  • The HTML converter is available under the Add-On section. Refer to the following screenshot.
 
 
  
  
  • Install the Syncfusion.HtmlToPdfConverter.QtWebKit.Net.Core from the NuGet package
 
  
  • Create a new cs file named ExportService under Data folder and include the following namespaces in the file.
  
  
using System;  
using System.IO;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Syncfusion.Pdf;  
using Syncfusion.HtmlConverter;  
  
  
  • Add the following method in the ExportService class
  
  
        public MemoryStream ExportAsPdf(string content)  
        {  
            try  
            {  
                //Initialize the HTML to PDF converter  
                HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();  
  
                WebKitConverterSettings settings = new WebKitConverterSettings();  
  
                // Used to load resources before convert  
                string baseUrl = @"C:/Users/xxxxxx/RTEPdf/wwwroot/images";  
  
                //Set WebKit path  
                settings.WebKitPath = @"C:/Program Files (x86)/Syncfusion/HTMLConverter/17.3.0.26/QtBinariesDotNetCore";  
  
                //Set additional delay; units in milliseconds;  
                settings.AdditionalDelay = 3000;  
  
                //Assign WebKit settings to HTML converter  
                htmlConverter.ConverterSettings = settings;  
  
                //Convert HTML string to PDF  
                PdfDocument document = htmlConverter.Convert(content, baseUrl);  
  
                //Save the document into stream.  
  
                MemoryStream stream = new MemoryStream();  
  
                document.Save(stream);  
  
                stream.Position = 0;  
  
                //Close the document.  
  
                document.Close(true);  
  
                return stream;  
            }  
            catch  
            {  
                return new MemoryStream();  
            }  
  
        }  
  
  
  • Change HTMLConverter install location based on your computer location in above code snippet
  
  
  //Set WebKit path  
  settings.WebKitPath = @"C:/Program Files (x86)/Syncfusion/HTMLConverter/17.3.0.26/QtBinariesDotNetCore";  
  
  
  
  
  • Register your service in the ConfigureServices method available in the Startup.cs class as follows.
  
  
        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddRazorPages();  
            services.AddServerSideBlazor();  
            services.AddSingleton<WeatherForecastService>();  
            services.AddSingleton<ExportService>();  
        }  
  
  
  • Inject ExportService in-to Index.razor using the following code.
  
  
@inject ExportService exportService  
  
  
  • Create a button in the Index.razor using the following code.
  
  
<button class="btn btn-primary" @onclick="@Export">Export as PDF</button>  
  
  
  • Add the Export method in Index.razor page to call the export service.
  
  
    private async Task Export()  
    {  
        using (MemoryStream excelStream = exportService.ExportAsPdf(this.rteValue))  
        {  
            await SampleInterop.SaveAs<object>(jsRuntime, "Sample.pdf", excelStream.ToArray());  
        }  
    }  
  
  
  • Create a class file with SampleInterop name and add the following replace the below code to invoke the JavaScript action to download the file in the browser.
  
  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.JSInterop;  
using Newtonsoft.Json;  
  
namespace RTEPdf  
 
    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; }  
    }  
 
  
  
  
  • Add the following JavaScript function in the _Host.cshtml available under the Pages folder.
  
  
    <script type="text/javascript">  
        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.rel='nofollow' href = "data:application/octet-stream;base64," + bytesBase64;  
                document.body.appendChild(link); // Needed for Firefox  
                link.click();  
                document.body.removeChild(link);  
            }  
        }  
    </script>  
  
  
  • Create a new cs file named SampleDataController under Data folder and add following method to handle save image action
  
  
using System;  
using System.IO;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using System.Net.Http.Headers;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.AspNetCore.Http;  
using Microsoft.AspNetCore.Mvc;  
using Syncfusion.Pdf;  
using Syncfusion.HtmlConverter;  
  
namespace RTEHPdf.Data  
 
    [Route("api/[controller]")]  
    [ApiController]  
    public class SampleDataController : ControllerBase  
    {  
        private IWebHostEnvironment hostingEnv;  
  
        public SampleDataController(IWebHostEnvironment env)  
        {  
            this.hostingEnv = env;  
        }  
  
        [HttpPost]  
        [Route("Save")]  
        public void Save(IList<IFormFile> UploadFiles)  
        {  
            try  
            {  
                foreach (var file in UploadFiles)  
                {  
                    if (UploadFiles != null)  
                    {  
                        string path = hostingEnv.ContentRootPath + "\\wwwroot\\Images";  
                        string filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');  
                        if (!System.IO.Directory.Exists(path))  
                        {  
                            System.IO.Directory.CreateDirectory(path);  
                        }  
  
                        //To save the image in the sever side   
                        filename = path + $@"\{filename}";  
  
                        if (!System.IO.File.Exists(filename))  
                        {  
                            using (FileStream fs = System.IO.File.Create(filename))  
                            {  
                                file.CopyTo(fs);  
                                fs.Flush();  
                            }  
                        }  
                    }  
                }  
            }  
            catch { }  
        }  
    }  
 
  
  
  • Add following MapControllers configuration in startup.cs
  
  
            app.UseEndpoints(endpoints =>  
            {  
                endpoints.MapControllers();  
                endpoints.MapBlazorHub();  
                endpoints.MapFallbackToPage("/_Host");  
            });  
  
  
  • Now run the application and click Export as PDF button inside the SfDialog, it will generate and export PDF.
  
We have prepared sample for your reference, get it from below link  
 
 
Query 2: “I tried this function, but in print, only the file name appeared in place of the image. Another formatted text was printed well.“

The reported issue is not reproduced from our end, since the image is shown with the print action. can you please check the above sample for this reported scenario and revert back to us if you face the same issue?
 
 
Regards,  
Indrajith 


Loader.
Up arrow icon