Welcome folks today in this blog post we will be capturing screenshot of html
elements in browser and download it as png
image in angular. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleapp
cd sampleapp
npm i ngx-capture
And after that you will be seeing the below directory
structure of the angular app as shown below
And now we need to go to app.module.ts
file and copy paste the following code
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { NgModule } from "@angular/core"; import { BrowserModule } from "@angular/platform-browser"; import { FormsModule } from "@angular/forms"; import { AppComponent } from "./app.component"; import { NgxCaptureModule } from 'ngx-capture'; @NgModule({ imports: [BrowserModule, FormsModule, NgxCaptureModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} |
As you can see we are importing the ngx-capture
module at the top and then we are adding it inside the imports
array.
And now we need to go to app.component.html
file and copy paste the following code
`
app.component.html
1 2 3 4 5 6 7 8 |
<div #screen> <h1>John Williamson Latham</h1> <p> Start editing to see some magic happen :) </p> </div> <h2>My Capture:</h2> <img src="{{img}}" /> |
As you can see we have the html5
template in which we have the heading
and the paragraph
and then we have the img
rendering the html
template as shown below
app.component.css
1 2 3 4 5 6 |
p { font-family: Lato; } img { border: 1px gray solid; } |
And now we need to go to app.component.ts
file and copy paste the following code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import { Component, ViewChild, OnInit } from "@angular/core"; import { NgxCaptureService } from "ngx-capture"; import { tap } from "rxjs/operators"; @Component({ selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { name = "Angular"; img = ""; @ViewChild("screen", { static: true }) screen: any; constructor(private captureService: NgxCaptureService) {} ngOnInit() { this.captureService .getImage(this.screen.nativeElement, true) .pipe( tap(img => { this.img = img; console.log(img); }) ) .subscribe(); } } |
As you can see we are importing the ngx-capture
service and then we are taking the screenshot
of the html template
and saving it as png image file.