Skip to content

Instantly share code, notes, and snippets.

@Mustafa-Omran
Last active June 27, 2024 15:22
Show Gist options
  • Save Mustafa-Omran/c38bf7c06bd9e995031e68e1735a6721 to your computer and use it in GitHub Desktop.
Save Mustafa-Omran/c38bf7c06bd9e995031e68e1735a6721 to your computer and use it in GitHub Desktop.
Angular - Export Multiple Pages with PDF format - Using jsPDF && html2canvas packages
<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
@Mustafa-Omran
Copy link
Author

This works great, just one question, is there a way to avoid this?

image

@costea93 this solution depends on what you see on your screen, try to enable overview scroll

@ckm1234
Copy link

ckm1234 commented Dec 18, 2022

Did you get any solutions regarding this ?

@yoenispantoja
Copy link

yoenispantoja commented Apr 4, 2023

Great solution!! If you can resolve the margin-bottom issue, this code will be worth thousands of dollars... :-D... Thanks!

@shouvikchatterjee
Copy link

image
Getting this error while download

@BualiSina99
Copy link

Did you get any solutions regarding above mention by @Mustafa-Omran ???
?

@NelsonChad
Copy link

Any solution for @Mustafa-Omran question?

@talal-webook
Copy link

Finally a working solution. Rep++

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment