Angular 11 How to convert HTML to image?

Angular 11 How to convert HTML to image

Angular 11 How to convert HTML to image, This article will tell the developer how to change over HTML into an image utilizing the html-to-image NPM bundle. developer can change over any Dom components into a image, Dom components like div, length, table, and so forth

By utilizing html-to-image bundle client can change HTML over to an image, a developer can change HTML over to JPEG, PNG, SVG, BLOB(Binary Large Object), This model gives you a straightforward and simple approach to change Angular 11 HTML over to Image.

Angular 11 How to convert HTML to Image Example

  • Step 1 – Create a new Angular 11 app
  • Step 2 – Install html-to-image Package
  • Step 3 – Add HTML into a view file
  • Step 4 – Add code in Component .ts file
  • Step 5 – Run Angular app

Step 1 – Create a new Angular 11 app

First of all, open your command prompt and execute the following command to create a new Angular 11 app.

ng new htmltoImage

Step 2 – Install html-to-image Package

In this step, We will install html-to-image using node package module, open the terminal and execute the following command in the terminal.

npm install --save html-to-image

Step 3 – Add HTML into a view file

In this step, We will add HTML code in a view file so visit the src/app/app.component.html file and add your HTML code

 

<div id="image-section">
  <h1>Hello world!</h1>
</div>
 
<button type="button" (click)="generateImg()">GenerateImage</button>

In the above code, I have added the id attribute because this package will access the DOM Elements and generate an image.

Step 4 – Add code in Component .ts file

import { Component } from '@angular/core';
import * as htmlToImage from 'html-to-image';
 
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'htmltoImage';
 
  generateImg(){
    var node:any = document.getElementById('image-section');
    htmlToImage.toPng(node)
      .then(function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
      })
      .catch(function (error) {
        console.error('Error, something is missing!', error);
      });
  }
}
Step 5 –

Step 5 – Run Angular app

ng serve