Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Generate pdf from HTML using jspdf

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.

like image 769
FlorisdG Avatar asked Apr 07 '17 11:04

FlorisdG


2 Answers

Anyone still trying to convert an Html div to a pdf can opt to use html2pdf, with a couple of lines you can do everything with ease.

var element = document.getElementById('element-to-print');
html2pdf(element);
like image 77
Sadiq Ali Avatar answered Sep 22 '22 04:09

Sadiq Ali


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';
like image 45
Greg Avatar answered Sep 25 '22 04:09

Greg