How to print or export the HTML and native node into image format using React Diagram?
Currently, exporting React Diagram into image format with native and HTML nodes is not supported. The export process involves rendering the diagram on a canvas and subsequently converting that canvas into an image. However, accurately rendering all possible HTML equivalents within a canvas presents challenges in terms of feasibility.
To overcome this limitation, we make use of the Syncfusion Essential PDF library. This library incorporates the Syncfusion Essential HTML converter, which employs the advanced Blink rendering engine. This converter seamlessly transforms HTML content into images. It offers easy integration into various applications across .NET platforms such as Windows Forms, WPF, ASP.NET, ASP.NET MVC, and ASP.NET Core. It enables the conversion of URLs, HTML strings, SVG, and MHTML to both PDF and image formats.
Prerequisites and Setting up for conversion
Minimum product version for .NET Core: 18.1.0.36
• Supports conversion from .NET Core 2.0.
• Latest version of Essential HTML converter can be downloaded from the following link.
https://www.syncfusion.com/downloads/latest-version
• To convert an HTML to Image using Blink rendering engine, add the following assemblies or NuGet packages as a reference to the project.
Assemblies
Platform | Assemblies |
---|---|
.NET Core | Syncfusion.HtmlToPdfConverter.Net.Windows , Newtonsoft.Json package (v10.0.1 or above) |
Client side
At first, we need to retrieve the HTML content of the diagram and send it to the server-side. To obtain the diagram content as an HTML string, the following client-side API method has been introduced.
getDiagramContent
Method Name | Argument | Return Type | Description |
---|---|---|---|
getDiagramContent | styleSheetReferences- It is an optional argument. By specifying this, you will get the diagram content along with those stylesheet references. Please note that you have to define absolute path for local CSS file. If it is not specified, you will get the diagram content along with all stylesheets loaded in the document. | string | This method is used to get the diagram DOM element as a string along with all dependent stylesheets. |
Refer to the following code example.
let diagramInstance = document.getElementById("diagram").ej2_instances[0];
// get the diagram content
let htmlData = diagramInstance.getDiagramContent();
You can use the above method to obtain the HTML content and send it to the server through fetch post. On the server side, we used convertImage method to convert the diagram content into an image.
Server side
Now, let’s proceed to create an ASP.NET Core application. For guidance on creating a Core application, please refer to the following link:
https://ej2.syncfusion.com/aspnetcore/documentation/diagram/getting-started
The utility project should be included in the sample to facilitate the conversion of HTML to image format. In the ASP.NET Core application, within the Models folder, create a new file named ‘ExportUtility.cs.’
In the utility project, define a class named ‘ExportUtility,’ and inside that class, create a method for converting HTML content to an image. The ‘ConvertImage’ method in the ‘ExportUtility’ file, as illustrated in the code example below, is employed to convert HTML content into an image format using the Blink engine.
Refer to the following code example.
public class exportUtility
{
// define key value
public string Options { get; set; }
public string ConvertImage(string Options)
{
HtmlToPdfConverter converter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
System.Drawing.Image doc = converter.ConvertToImage(Options, "")[0];
MemoryStream stream = new MemoryStream();
doc.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return "data:image/png;base64," + Convert.ToBase64String(stream.ToArray());
}
}
Ensure that you have referenced ‘Syncfusion.HtmlConverter’ in the ‘ExportUtility’ file, as shown below.
using Syncfusion.HtmlConverter;
Now, let’s create a class with a method adorned with the HttpPost attribute. This method is designed to fetch HTML data sent from the client-side. Upon receiving the data, it will invoke the ConvertImage method from the ‘ExportUtility.cs’ file. Subsequently, the converted image will be sent back to the client-side as a response.
Refer to the server-side code example as follows:
public class DiagramOptions
{
public string Options { get; set; }
}
// Controller action
[HttpPost]
public ActionResult GenerateDocument([FromBody] DiagramOptions diagramOptions)
{
string options = diagramOptions.Options;
exportUtility diagram = new exportUtility();
string jsonContent = diagram.ConvertImage(options);
return Json(new { Result = jsonContent });
}
Make sure to refer the exportUtility class in server side like below.
using static SyncfusionWebApp.Models.exportUtility;
exportImage
After obtaining the image converted from the server-side, you have the option to save the image in a different format with specific exporting options using the ‘exportImage’ API method. The ‘exportImage’ method provides all the options similar to the ‘exportDiagram’ API method, excluding the ‘mode’ argument, as it is not applicable for the ‘exportImage’ method.
The next step involves using the base64Image returned from the server-side as the first argument of the ‘exportImage’ method. Additionally, you can define the export settings in the second argument of this method. For a comprehensive understanding of export settings, please refer to the following link:
Export Settings Documentation.
In the client-side code example below, you’ll find a demonstration of how to initiate a request to the server-side by passing HTML data. It’s crucial to include the URL where the core application is hosted and specify the content-type expected to be returned from the server-side using fetch operation. Upon a successful request, the converted data in JSON format will be received from the server-side. Then, by extracting the base64 string from this JSON response, you can utilize the ‘exportImage’ method to export the image.
Refer the code example below.
document.getElementById('export').onclick = () => {
let htmlData = diagramInstance.getDiagramContent();
const url = 'https://localhost:44301/home/generatedocument';
const headers = new Headers({
'Content-Type': 'application/json',
});
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify({ Options: htmlData }),
};
fetch(url, options)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
console.log('success', data);
// Assuming diagram is accessible here
diagramInstance.exportImage(data.result, {
fileName: 'diagram',
mode: 'Download',
region: 'Content',
stretch: 'Meet',
pageHeight: 1000,
pageWidth: 800,
bounds: new Rect(0, 0, 800, 800),
});
})
.catch((error) => {
console.error('Error:', error);
// Handle errors here
});
};
printImage
Similarly, you can use the “printImage” method to print the image with certain option and it has all the options as like the print method.
Refer to the final client-side code example for printing as follows
diagramInstance.printImage(result.result, {
fileName: 'diagram',
mode: 'Data',
region: 'Content',
stretch: 'Meet',
pageHeight: 1000,
pageWidth: 800,
bounds: new ej.diagrams.Rect(0, 0, 800, 800)
});
To export or print an image, follow these steps:
- Begin by running the provided server-side sample.
- Subsequently, run the client-side sample.
- Within the client-side sample, locate and click the export button.
- Wait for the process to complete; you’ll observe the exported image downloaded as a result.
The complete ASP.NET Sample can be downloaded here:
Server-side sample
Conclusion
I hope you enjoyed learning about how to print or export the HTML and native node into image format using React Diagram.
You can refer to our React Diagram feature tour page to know about its other groundbreaking feature representations and documentations. You can also explore our React Diagram example to understand how to present and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other components.
If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!