How To export base64 Image with diagram size using blink rendering in JavaScript Diagram with MVC?
Currently, exporting JavaScript 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 MVC5
• Latest version of Essential HTML converter can be downloaded from the following link.
https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Net.Windows
• 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 MVC | 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. |
If you are referencing CSS/SCSS from other files for your HTML nodes, you need to include the styleSheetReferences for those files. Otherwise, the exported diagram will not contain those customizations. To include external CSS for HTML nodes, pass your CSS reference files as arguments to the diagram.getDiagramContent(styleSheetReferences) method.
By specifying the stylesheet references, the exported diagram content will include the linked CSS. Make sure to use absolute paths to local CSS files or public URLs. If no references are specified, the export will only include the stylesheets currently loaded in the diagram DOM element.
Refer to the following code example.
let diagram = document.getElementById("diagram").ej2_instances[0];
// define the CSS file(local url/live url) of external css as strings
let styles: string[] = [
'http://localhost:3000/assets/styles/custom-style.css',
'<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">'];
let htmlData: string = diagram.getDiagramContent(styles) as string;
Note: You can directly provide external CSS files that are accessed from public websites. Meanwhile, if you are referencing local CSS files, ensure they are accessible from the hosted link by properly by maintaining your styles in separate folder.
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 MVC 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 = diagram.getDiagramContent();
let htmlData = diagram.getDiagramContent();
const url = 'https://localhost:44301/home/generatedocument';
const headers = new Headers({
'Content-Type': 'application/json',
});
const diagramDiv = document.getElementById('diagram_diagramLayer');
const contentWidth = diagramDiv.getBoundingClientRect().width;
const contentHeight = diagramDiv.getBoundingClientRect().height;
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify({ Options: htmlData, Width: contentWidth, Height: contentHeight }),
};
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);
var exportOptions = {};
exportOptions.mode = 'Download';
diagram.exportImage(data.result, exportOptions);
})
.catch((error) => {
console.error('Error:', error);
// Handle errors here
});
Removing blank space in Base64 string
In this resulted base64, By default, when using the HtmlToPdfConverter to convert HTML data to an image, the generated image typically has dimensions of 1920 x 600. This results in a base64 image output containing unnecessary blank space. To address this issue, a workaround involves adjusting the viewport size. To ensure the image fits the content without excess blank space,use the BlinkConverterSettings class is used to set a custom viewport size during the export process. This optimizes the image’s dimensions and eliminates the blank areas.
To dynamically set the ViewPortSize for the Blink Converter without hardcoding it, you can calculate the content size of the diagram and use those dimensions. First, you can get the width and height of the diagram content by accessing the getBoundingClientRect() method on the diagram layer, you can retrieve the actual dimensions. Then, these values (width and height) can be sent to the backend, where they are used to configure the ViewPortSize in the BlinkConverterSettings in your ASP.NET controller. This approach ensures that the viewport size matches the content of the diagram precisely, preventing unnecessary blank space while rendering the image.
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 MVC application. For guidance on creating a MVC application, please refer to the following link:
https://ej2.syncfusion.com/aspnetmvc/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 MVC 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 double Width { get; set; }
public double Height { get; set; }
public string ConvertImage(string Options, double Width, double Height)
{
// blink rendering is used to convert images
HtmlToPdfConverter converter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
//Set Blink viewport size
blinkConverterSettings.ViewPortSize = new Syncfusion.Drawing.Size((int)Math.Round(Width), (int)Math.Round(Height));
//Assign Blink converter settings to HTML converter
converter.ConverterSettings = blinkConverterSettings;
Syncfusion.Drawing.Image doc = converter.ConvertToImage(Options,"");
MemoryStream stream = new MemoryStream();
byte[] imageByte = doc.ImageData;
//Save the image
File.WriteAllBytes("Output.jpg", imageByte);
//base 64 string is returned
return "data:image/png;base64," + Convert.ToBase64String(imageByte);
//return Convert.ToBase64String(imageByte);
}
}
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 and Size of diagram content 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; }
public double Width { get; set; }
public double Height { get; set; }
}
// Controller action
[HttpPost]
public ActionResult GenerateDocument(DiagramOptions diagramOptions)
{
string options = diagramOptions.Options;
exportUtility diagram = new exportUtility();
string jsonContent = diagram.ConvertImage(options, diagramOptions.Width, diagramOptions.Height);
return Json(new { Result = jsonContent });
}
Make sure to refer the exportUtility class in server side like below.
using static SyncfusionWebApp.Models.exportUtility;
- 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 export the HTML and native node into image format and handle base64 Image with diagram size using JavaScript Diagram.
You can refer to our JavaScript Diagram feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Diagram example to understand how to create 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 controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!