npm i jspdf
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 { HelloComponent } from './hello.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent, HelloComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } |
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 30 31 32 33 34 35 36 37 38 39 40 |
import { Component, ViewChild, ElementRef } from '@angular/core'; import {jsPDF} from 'jspdf'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular Html To Pdf '; userName: string; @ViewChild('pdfTable', {static: false}) pdfTable: ElementRef; public downloadAsPDF() { const doc = new jsPDF(); var x = document.getElementById("myTd"); x.innerHTML = this.userName; const specialElementHandlers = { '#editor': function (element, renderer) { return true; } }; const pdfTable = this.pdfTable.nativeElement; doc.fromHTML(pdfTable.innerHTML, 15, 15, { width: 190, 'elementHandlers': specialElementHandlers }); console.log(doc.output('dataurl')); console.log(this.userName); } } |
app.component.html
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<div id="pdfTable" #pdfTable> <h1>{{name}}</h1> <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td id="myTd"><input [(ngModel)]="userName" type="text" [value]="userName"></td> <td>Maria Anders</td> <td>Germany</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> <td>Mexico</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> <td>Austria</td> </tr> <tr> <td>Island Trading</td> <td>Helen Bennett</td> <td>UK</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Yoshi Tannamuri</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Giovanni Rovelli</td> <td>Italy</td> </tr> </table> </div> <div> <button (click)="downloadAsPDF()">Export To PDF</button></div> |
FULL SOURCE CODE