Convert html to pdf in angular 12;. In this tutorial, i am going to show you easy way on how do you generate pdf from html in angular 12/11/10 apps.
This tutorial will use pdfmake, html-to-pdfmake and jspdf package for generating pdf file from HTML. And will help you step by step on how to generate HTML to pdf angular 11/12 app.
How To Convert HTML Page To PDF In Angular 12 Application
- Step 1 – Create New Angular App
- Step 2 – Install Package
- Step 3 – Add Code on View File
- Step 4 – Add Code On Component ts File
- Step 5 – Start Angular App
Step 1 – Create New Angular App
Execute the following command on terminal to install angular app:
ng new my-new-app
Step 2 – Install Package
Execute the following command on terminal to install Package in our angular application:
npm install --save pdfmake npm install html-to-pdfmake npm install jspdf --save
Step 3 – Add Code on View File
Create table to convert html to pdf. So, visit src/app/app.component.html and update the following code into it:
<div class="container"> <div id="pdfTable" #pdfTable> <h2>Angular HTML To PDF Generator Example - laratutorials.com</h2> <table class="table table-bordered"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Website</th> </tr> </thead> <tbody> <tr> <td>Sam</td> <td>Sam</td> <td>laratutorials.com</td> </tr> <tr> <td>john</td> <td>dam</td> <td>w3school.com</td> </tr> <tr> <td>jonhy</td> <td>hid</td> <td>geeks.com</td> </tr> </tbody> </table> </div> <button class="btn btn-primary" (click)="downloadAsPDF()">Export To PDF</button> </div>
Step 4 – Add Code On Component ts File
Go to src/app directory and open app.component.ts. Then add the following code into component.ts file:
import { Component, ViewChild, ElementRef } from '@angular/core'; import jsPDF from 'jspdf'; import pdfMake from 'pdfmake/build/pdfmake'; import pdfFonts from 'pdfmake/build/vfs_fonts'; pdfMake.vfs = pdfFonts.pdfMake.vfs; import htmlToPdfmake from 'html-to-pdfmake'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'htmltopdf'; @ViewChild('pdfTable') pdfTable: ElementRef; public downloadAsPDF() { const doc = new jsPDF(); const pdfTable = this.pdfTable.nativeElement; var html = htmlToPdfmake(pdfTable.innerHTML); const documentDefinition = { content: html }; pdfMake.createPdf(documentDefinition).open(); } }
Step 5 – Start Angular App
Execute the following commands on terminal to start angular app:
ng serve
Be First to Comment