Hello Dev,
I will explain step-by-step tutorial angular 11 html to pdf. In this article, we will implement an angular 11 to generate PDF from HTML. This post will give you a simple example of html to pdf angular 11. we will help you to give an example of how to convert HTML to pdf in angular 11.
we will use pdf make, html-to-pdf make, and pdf package for generating pdf files from html view in the angular app. Let's see the simple examples of how to generate pdf from html in angular 11.
Step - 1: Create New App
You can easily create your angular app using the below command:
ng new myNewApp
Step - 2 : Install Packages
Now in this step, we need to just install ngmodule/material-carousel and angular/material in our angular application. so let's add as like bellow:
npm install --save pdfmake
npm install html-to-pdfmake
npm install jspdf --save
Step - 3 : Update Ts File
here, we need to update the ts file as below:
src/app/app.component.ts
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 - 4 : Update HTML File
here, we need to update the HTML file as below code:
src/app/app.component.html
<div class="container">
<div id="pdfTable" #pdfTable>
<h2>Angular HTML To PDF Generator Example - ItSolutionStuff.com</h2>
<table class="table table-bordered">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Website</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hardik</td>
<td>Savani</td>
<td>itsolutionstuff.com</td>
</tr>
<tr>
<td>Vimal</td>
<td>Kashiyani</td>
<td>hdtuto.com</td>
</tr>
<tr>
<td>Harshad</td>
<td>Pathak</td>
<td>nicesnippets.com</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-primary" (click)="downloadAsPDF()">Export To PDF</button>
</div>
Now you can run by bellow command:
ng serve
now you can check it.
Happy Coding.....