Member-only story
How to print/download HTML Document as PDF using html2canvas and jspdf in Angular
2 min readApr 29, 2024
Hi,
In this blog, we are going to see how to print or download html div element using html2canvas and jspdf in Angular.
npm install the below 2 modules to use for this option.
npm install jspdf html2canvas
"html2canvas": "1.4.1",
"jspdf": "2.5.1"
Once you installed successfully, import the respected modules in ts file as shown in below; you need to declare html2canvas as constant to work with the module.
import jspdf from 'jspdf';
import * as _html2canvas from 'html2canvas';
const html2canvas: any = _html2canvas;
After you import, in html file create the div element or add Id for existing html code. As shown below, I have added “printcontent” for full-calendar to print and download.
<div class="dec-space" id="printcontent">
<full-calendar [options]="calendarOptions" #calendar>
</full-calendar>
</div>
Once you have div element with respected id, use the below code to generate pdf file.
// Genearate Pdf using canvas return the generated pdf
private async generatePdf(): Promise<jspdf> {
const htmlElement = document.getElementById('printcontent');
const canvas = html2canvas(htmlElement, {
onrendered: function (canvas) {
document.body.appendChild(canvas);
},
allowTaint: true,
useCORS: true…