Welcome folks today in this blog post we will be exporting html to png image
using ngx-export-as
library in browser using typescript.
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
Now first of all you 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 { AppComponent } from './app.component'; import { ExportAsModule } from 'ngx-export-as'; @NgModule({ imports: [ BrowserModule, ExportAsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } |
And now you need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 4 |
<p id="myTableElementId"> Start editing to see some magic happen :) hjkhkhk kh k </p> <button (click)="export()">Export to PNG</button> |
In the above html code we have the simple paragraph in which we have some text
and then we have the button to export html
to png image file and download it as an attachment.
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 |
import { Component } from '@angular/core'; import { ExportAsService, ExportAsConfig } from 'ngx-export-as'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { exportAsConfig: ExportAsConfig = { type: 'png', // the type you want to download elementIdOrContent: 'myTableElementId', // the id of html/table element } constructor(private exportAsService: ExportAsService) { } export() { // download the file using old school javascript method this.exportAsService.save(this.exportAsConfig, 'My File Name').subscribe(() => { // save started }); // get the data as base64 or json object for json type - this will be helpful in ionic or SSR this.exportAsService.get(this.exportAsConfig).subscribe(content => { console.log(content); }); } } |
As you can see we are setting the custom
filename and then we are taking the screenshot
of the html and then exporting to png
image file using the ngx-export-as
library.