npm install --save pdfmake
npm install html-to-pdfmake
npm install jspdf --save
ts file:
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';
...
@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();
HTML file:
<div class="container">
<div id="pdfTable" #pdfTable>
...
</div>
<button class="btn btn-primary" (click)="downloadAsPDF()">Export To PDF</button>
</div>
import { Component } from '@angular/core';
import { jsPDF } from "jspdf";
import html2canvas from 'html2canvas';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'html-to-pdf-angular-application';
public convertToPDF()
{
html2canvas(document.body).then(canvas => {
// Few necessary setting options
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jsPDF('p', 'mm', 'a4'); // A4 size page of PDF
var width = pdf.internal.pageSize.getWidth();
var height = canvas.height * width / canvas.width;
pdf.addImage(contentDataURL, 'PNG', 0, 0, width, height)
pdf.save('output.pdf'); // Generated PDF
});
}
}