Home ยป Angular 11 How to convert HTML to image?

Angular 11 How to convert HTML to image?

Angular 11 HTML to the image, This article is going to tell the users to how to convert HTML into an image using the html-to-image NPM package. user can convert any Dom elements into an image, Dom elements like div, span, table, etc..

By using html-to-image package user can convert HTML to image, user can convert HTML to JPEG, PNG, SVG, BLOB(Binary Large Object), This example give you simple and easy way to convert Angular 11 HTML 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 terminal and execute the following command to create a new Angular 11 app.

ng new my-new-app

Step 2 – Install html-to-image Package

In this step, We will install html-to-image package for convert html to image so open the terminal and execute the following command in terminal.

npm install --save html-to-image

The –save option will tell the NPM to include this package in the dependencies section of your package.json

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)="generateImage()">Create Image</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

In this step, We will import module to our component, For demo purpose, i am importing the module to the app.component.ts file but you can import in any components you want so visit the src/app directory and open the app.componets.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 = 'my-new-app';

  generateImage(){
    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('oops, something went wrong!', error);
      });
  }
}

Step 5 – Run Angular app

Execute the following command on terminal run angular app

ng serve

After compiled successfully, click on the create image button for the generate the image.

Related Post

Leave a Comment

Your email address will not be published.

1 × 2 =