I am trying to create a download function for my Angular application. I have managed to get this working, but I am having an issue described here:
https://github.com/niklasvh/html2canvas/issues/722
The images are from an external source, so are not being saved as part of the render. Apparently, you can set the boolean allowTaint and it will save the external images too, but as I am new to both Angular and html2canvas, I have no idea how to do this. My code is as follows:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ResultsService } from '../shared/results.service';
import { IResult } from '../shared/models/result.model';
import { IGroup } from '../shared/models/group.model';
import * as jsPDF from 'jspdf';
import * as html2canvas from "html2canvas";
@Component({
templateUrl: './results.component.html',
styleUrls: ['./results.component.scss']
})
export class ResultsComponent implements OnInit {
id: number;
result: IResult;
groups: IGroup[];
private sub: any;
constructor(
private _resultsService: ResultsService,
private _route: ActivatedRoute
) { }
ngOnInit() {
this.sub = this._route.params.subscribe(params => {
this.id = +params['id'];
});
this._resultsService.get(this.id).subscribe(result => {
this.result = result
this.groups = JSON.parse(result.data);
});
}
download() {
html2canvas(document.body).then(function(canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img,'JPEG',0,0);
doc.save('test.pdf');
});
}
}
Where in that code can I set the allowTaint option?
Turns out there are two ways of doing this. You can use the above method and just add the options as a constructor parameter like this:
html2canvas(document.body, { allowTaint: true }).then(function(canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img,'JPEG',0,0);
doc.save('test.pdf');
});
Or, as jsPdf already uses html2canvas you can just do this:
let pdf = new jsPDF();
pdf.addHTML(document.body, 0, 0, { allowTaint: true }, () => {
pdf.save("test.pdf");
});