jspdf
npm i jspdf
html2canvas
npm i html2canvas
| <div id="print-section"> | |
| <!-- template here --> | |
| </div> |
| import { DOCUMENT } from '@angular/common'; | |
| import { Component, Inject, OnInit } from '@angular/core'; | |
| import html2canvas from 'html2canvas'; | |
| import jsPDF from 'jspdf'; | |
| @Component({ | |
| selector: 'export-to-pdf', | |
| templateUrl: './export-to-pdf.component.html', | |
| styleUrls: ['./export-to-pdf.component.scss'] | |
| }) | |
| export class ExportToPDFComponent implements OnInit { | |
| today: Date = new Date(); | |
| constructor(@Inject(DOCUMENT) private document: Document, | |
| ) { | |
| } | |
| ngOnInit(): void { | |
| } | |
| exportToPDF() { | |
| const htmlWidth = $("#print-section").width(); | |
| const htmlHeight = $("#print-section").height(); | |
| const topLeftMargin = 15; | |
| let pdfWidth = htmlWidth + (topLeftMargin * 2); | |
| let pdfHeight = (pdfWidth * 1.5) + (topLeftMargin * 2); | |
| const canvasImageWidth = htmlWidth; | |
| const canvasImageHeight = htmlHeight; | |
| const totalPDFPages = Math.ceil(htmlHeight / pdfHeight) - 1; | |
| const data = this.document.getElementById('print-section'); | |
| html2canvas(data, { allowTaint: true }).then(canvas => { | |
| canvas.getContext('2d'); | |
| const imgData = canvas.toDataURL("image/jpeg", 1.0); | |
| let pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]); | |
| pdf.addImage(imgData, 'png', topLeftMargin, topLeftMargin, canvasImageWidth, canvasImageHeight); | |
| for (let i = 1; i <= totalPDFPages; i++) { | |
| pdf.addPage([pdfWidth, pdfHeight], 'p'); | |
| pdf.addImage(imgData, 'png', topLeftMargin, - (pdfHeight * i) + (topLeftMargin * 4), canvasImageWidth, canvasImageHeight); | |
| } | |
| pdf.save(`Document ${new Date().toLocaleString()}.pdf`); | |
| }); | |
| } | |
| } |
jspdf
npm i jspdf
html2canvas
npm i html2canvas
Did you get any solutions regarding above mention by @Mustafa-Omran ???
?
Any solution for @Mustafa-Omran question?
Finally a working solution. Rep++
Great solution!! If you can resolve the margin-bottom issue, this code will be worth thousands of dollars... :-D... Thanks!