How to use jsPDF with angular 2
Old question but this is an alternative solution that I got up and running in my angular app. I ended up modifying this jsPDF solution to work without using the ionic/cordova CLI.
npm install jspdf --save
npm install @types/jspdf --save
npm install html2canvas --save
npm install @types/html2canvas --save
Add an id to whichever div contains the content you want to generate the PDF
<div id="html2Pdf">your content here</div>
Import the libraries
import * as jsPDF from 'jspdf';
import * as html2canvas from 'html2canvas';
Add the method for generating the PDF
generatePdf() {
const div = document.getElementById("html2Pdf");
const options = {background: "white", height: div.clientHeight, width: div.clientWidth};
html2canvas(div, options).then((canvas) => {
//Initialize JSPDF
let doc = new jsPDF("p", "mm", "a4");
//Converting canvas to Image
let imgData = canvas.toDataURL("image/PNG");
//Add image Canvas to PDF
doc.addImage(imgData, 'PNG', 20, 20);
let pdfOutput = doc.output();
// using ArrayBuffer will allow you to put image inside PDF
let buffer = new ArrayBuffer(pdfOutput.length);
let array = new Uint8Array(buffer);
for (let i = 0; i < pdfOutput.length; i++) {
array[i] = pdfOutput.charCodeAt(i);
}
//Name of pdf
const fileName = "example.pdf";
// Make file
doc.save(fileName);
});
}
I found this solution worked well for my web app and was beneficial as I have control over when I want to generate the PDF (after receiving data asynchronously). As well, I didn't need install any libraries globally.
Here is how it should be for downloading a div
in Angular 11:
- Install npm package:
npm install jspdf --save
- Add template ref in
html
as:
<div #myTemp>
// other code here
<button (click)="print()"></button>
</div>
- Import in
xyz.component.ts
:
import { jsPDF } from "jspdf";
import html2canvas from 'html2canvas';
export class XYZComponent {
@ViewChild('myTemp') myTempRef: ElementRef;
print(){
const DATA = this.myTempRef.nativeElement;
html2canvas(DATA).then(canvas => {
let fileWidth = 200;
let fileHeight = canvas.height * fileWidth / canvas.width;
const FILEURI = canvas.toDataURL('image/png')
let PDF = new jsPDF('p', 'mm', 'a4');
let position = 0;
PDF.addImage(FILEURI, 'PNG', 5, 5, fileWidth, fileHeight)
PDF.save('angular-demo.pdf');
});
}
}
I have created a jsPdf demo based on this answer with help from @gsmalhotra
First install
npm install jspdf --save
I have used array of images, first converting the image to base64 (jsPDF doesn't allow image URLs)
getBase64Image(img) {
var canvas = document.createElement("canvas");
console.log("image");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
return dataURL;
}
Then in a loop, I have called above function which returns base64 image, and then added image to PDF using doc.addImage()
.
for(var i=0;i<this.images.length;i++){
let imageData= this.getBase64Image(document.getElementById('img'+i));
doc.addImage(imageData, "JPG", 10, (i+1)*10, 180, 150);
doc.addPage();
}
HTML code
<div class="col-md-4" *ngFor="let img of images;let i=index">
<img id="img{{i}}" class="img-fluid" crossOrigin="Anonymous" [src]="img.url">
</div>
Demo
Code
I have done it, after doing lot of R&D , their are few steps to follow as below : Install :
npm install jspdf --save
typings install dt~jspdf --global --save
npm install @types/jspdf --save
Add following in angular-cli.json:
"scripts": [ "../node_modules/jspdf/dist/jspdf.min.js" ]
html:
<button (click)="download()">download </button>
component ts:
import { Component, OnInit, Inject } from '@angular/core';
import * as jsPDF from 'jspdf'
@Component({
...
providers: [
{ provide: 'Window', useValue: window }
]
})
export class GenratePdfComponent implements OnInit {
constructor(
@Inject('Window') private window: Window,
) { }
download() {
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
// Save the PDF
doc.save('Test.pdf');
}
}