For my current project, I am in need of generating a PDF of the page that the user is currently viewing. To accomplish this task, I have decided to utilize jspdf
. Since I have HTML content that needs to be converted into a PDF format, I will make use of the addHTML()
function provided by jspdf. There are several discussions on this topic, where some suggest:
You can either opt for
html2canvas
orrasterizehtml
.
After considering both options, I have chosen to go with html2canvas
. Below is a snippet of the code that I have implemented so far:
import { Injectable, ElementRef, ViewChild } from '@angular/core';
import * as jsPDF from 'jspdf';
import * as d3 from 'd3';
import * as html2canvas from 'html2canvas';
@Injectable ()
export class pdfGeneratorService {
@ViewChild('to-pdf') element: ElementRef;
GeneratePDF () {
html2canvas(this.element.nativeElement, <Html2Canvas.Html2CanvasOptions>{
onrendered: function(canvas: HTMLCanvasElement) {
var pdf = new jsPDF('p','pt','a4');
pdf.addHTML(canvas, function() {
pdf.save('web.pdf');
});
}
});
}
}
However, upon invoking this function, I encounter an error message in the console:
EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:4 caused by: You need either https://github.com/niklasvh/html2canvas or https://github.com/cburgmer/rasterizeHTML.js
This leaves me puzzled as to why I am prompted to use html2canvas
despite passing a canvas parameter. What could be the reason behind this requirement?