Articles in this section
Category / Section

How to Export HTML and Native Node into Image in Angular Using MVC?

8 mins read

At present, exporting the Angular Diagram into an image format with native and HTML nodes is not supported. The export process involves rendering the diagram onto a canvas, which is then converted into an image. However, accurately replicating all possible HTML elements within a canvas poses significant challenges in terms of practicality.

To address this limitation, the Syncfusion Essential® PDF library is utilized. This library includes the Syncfusion Essential® HTML converter, which leverages the advanced Blink rendering engine. The converter efficiently transforms HTML content into images and integrates seamlessly into various .NET platforms, including Windows Forms, WPF, ASP.NET, ASP.NET MVC, and ASP.NET Core. It supports the conversion of URLs, HTML strings, SVG, and MHTML into both PDF and image formats.

Prerequisites and Setting up for conversion

Minimum Product Version for .NET MVC 5

• The latest version of the Essential HTML Converter can be downloaded from the following link: https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Net.Windows

• To convert HTML to an image using the Blink rendering engine, add the following assemblies or NuGet packages as references to your 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 the absolute path for the 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.

Please review the code example provided below.

let diagram = document.getElementById("diagram").ej2_instances[0];
// define the CSS file(local url/live url) of external css as strings
const styles: string[] = [
               'http://localhost:4200/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">'];  //string array
const htmlData: string = this.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 configuring the file and maintaining your styles in a separate folder.

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 string ConvertImage(string Options)
       {
           HtmlToPdfConverter converter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
           Image[] doc = converter.ConvertToImage(Options, "");
           using (MemoryStream ms = new MemoryStream())
           {
               doc[0].Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // or use any format you prefer (e.g., PNG)
               byte[] imageByte = ms.ToArray();
           
               // Return the base64 string
               return "data:image/png;base64," + 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 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
[System.Web.Mvc.HttpPost]
public ActionResult GenerateDocument([FromBody] DiagramOptions diagramOptions)
{
   // Access the Options property from the passed diagramOptions object
   string options = diagramOptions.Options;
   exportUtility diagram = new exportUtility();

   // Pass the options to the ConvertImage method
   string jsonContent = diagram.ConvertImage(options);

   // Return the result as JSON
   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 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 = this.diagram.getDiagramContent();
   const headers = new HttpHeaders({
     'Content-Type': 'application/json'
   });
   const options = {
     headers: headers,
     body: JSON.stringify({ Options: htmlData }),
   };

   const requestData = JSON.stringify({ Options: htmlData });    
this.http.post(url, requestData, options)
     .subscribe(
       (result: any) => {
         console.log('success', result);
         this.diagram.exportImage(result.result, {
           fileName: 'diagram',
           mode: 'Download',
           region: 'Content',
           stretch: 'Meet',
           pageHeight: 300,
           pageWidth: 500,
           bounds: new Rect(0, 0, 500, 300)
         });
       },
       (error: any) => {
         console.log('error', error);
         // Handle errors here
       }
     );};

printImage

Similarly, you can use the “printImage” method to print the image with certain options, and it has all the options similar to the print method.

Refer to the final client-side code example for printing as follows.

   
    this.diagram.printImage(data.result, {
         fileName: 'diagram',
         mode: 'Data',
         region: 'Content',
         stretch: 'Meet',
         pageHeight: 1000,
         pageWidth: 800,
         bounds: new 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:
ASP.NET MVC Sample
client side sample

Conclusion

we hope you enjoyed learning about how to print or export HTML and Native Nodes into an image in Angular using MVC.

You can refer to our Angular Diagram feature tour page to learn about its other groundbreaking feature representations. You can explore our Angular Diagram documentation to understand how to present and manipulate data.

For current customers, you can check out our Angular 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 Angular Diagram and other Angular components.

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

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied