Angular2 - Generate pdf from HTML using jspdf

FlorisdG picture FlorisdG · Apr 7, 2017 · Viewed 42.1k times · Source

For a project I'm working on I need to be able to generate a PDF of the page the user is currently on, for which I'll use jspdf. Since I have a HTML I need to generate a PDF with, I'll need the addHTML() function. There are a lot of topic about this, saying

You'll either need to use html2canvas or rasterizehtml.

I've chosen to use html2canvas. This is what my code looks like at the moment:

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');
        });
      }
    });
  }
}

When this function is called, I get a console error:

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

Why exactly is this? I give a canvas as parameter and it still says I need to use html2canvas.

Answer

Greg picture Greg · Apr 13, 2017

What I found worked was adding:

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

to the index.html file (it could presumably be elsewhere).

I then used:

const elementToPrint = document.getElementById('foo'); //The html element to become a pdf
const pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML(elementToPrint, () => {
    doc.save('web.pdf');
});

Which no longer uses html2canvas in the code.
You can then remove the following import:

import * as html2canvas from 'html2canvas';