10

How to generate an output file PDF using html2canvas with angular2

I tried to import the file html2canvas typescript and made a declaration like this to use it

declare let html2canvas: Html2CanvasStatic;

but I get html2canvas is not defined

html2canvas(document.body, {
  onrendered: function(canvas) {
    document.body.appendChild(canvas);
  }
});

I found this file typescript on github html2canvas typescript

how can use this for my application angular2

khalil _diouri
  • 791
  • 3
  • 12
  • 34

5 Answers5

15

I could use html2canvas with the followings changes:

package.json:

 "dependencies": {
     "html2canvas": "0.5.0-beta4",
     "@types/html2canvas": "0.5.32",
 }

After using npm install I could use html2canvas in my component.ts files like this:

import * as html2canvas from "html2canvas"

test() {
    html2canvas(document.body, {
        onrendered: function(canvas) {
        var img = canvas.toDataURL()
        window.open(img);
     }
    });

}

Without installing @types/html2canvasI could use the lib via require but not via the import:

html2canvas = require('hmtl2canvas');
mszalbach
  • 10,612
  • 1
  • 41
  • 53
4

If you are using Angular 4 you can include html2canvas under scripts list in .angular-cli.json as below

"scripts": [
    "../node_modules/html2canvas/dist/html2canvas.min.js"
]

After that import it in your class as below

import * as html2canvas from "html2canvas"

and then use it in your functions as below

html2canvas(parameters);
Anil Agrawal
  • 2,748
  • 1
  • 24
  • 31
  • 1
    If you use a global script import via angular-cli.json *don't* import it in your component as you'll load it twice : https://github.com/angular/angular-cli/wiki/stories-global-scripts – PaulCo Apr 02 '18 at 12:45
4

In 2018:

html2canvas(document.body).then((canvas) => {
    window.open().document.write('<img src="' + canvas.toDataURL() + '" />');
  });
ismaestro
  • 7,561
  • 8
  • 37
  • 50
1

This is in addition to above answer, i.e. add @types/html2canvas to dependencies and add import statement in your code.

However, using the above sample code, I am getting error in VisualStudioCode i.e.

'onrendered' does not exist in type 'Html2CanvasOptions'.

To resolve that, I used "then" as below:

html2canvas(document.body).then((canvas) => {
  document.body.appendChild(canvas);
});
pradeep
  • 400
  • 1
  • 4
  • 11
0
myClickFunction(event: any) {
html2canvas(event.target)
  .then((canvas) => {
    var img = canvas.toDataURL()
    window.open(img);
  })
  .catch(err => {
    console.log("error canvas", err);
  });
}
Matheus Lacerda
  • 5,983
  • 11
  • 29
  • 45