4

I'm trying to capture HTML to image in an Ionic 4 app. I tried using html2canvas, however, it doesn't work and shows this output in the console: enter image description here

This is my code:

var element = document.getElementById('capture');
  html2canvas(element).then(canvas => {
    var imgData = canvas.toDataURL("image/png");
    this.socialSharing.share(null, null, imgData);
});
dpapadopoulos
  • 1,834
  • 5
  • 23
  • 34
amitairos
  • 2,907
  • 11
  • 50
  • 84
  • Might be related: https://stackoverflow.com/questions/54650369/html2canvas-generating-blank-image-in-ionic4-angular-proj-no-error-in-console – jbgt Apr 26 '19 at 09:13

3 Answers3

6

I'm having the same issue. I managed to "fix" it by putting my code out of the <ion-content> tag. My guess is that html2canvas doesn't render shadow DOM elements (which is the case of <ion-content>, as of Ionic 4).

For instance this outputs an empty canvas:

<ion-content>
  <div id="capture">
    <h1>Test</h1>
  </div>
</ion-content>

But the following works:

<div id="capture">
  <h1>Test</h1>
</div>

This is not really a solution, but it's good enough for my use...

jbgt
  • 1,586
  • 19
  • 24
6

I was trying this component too but it does not work. The solution I found was to use the dom-to-image library. I attached an example of what I did. You just have to put the file extension you want to convert.

https://www.npmjs.com/package/jspdf

https://www.npmjs.com/package/dom-to-image

import * as jsPDF from 'jspdf';
import domtoimage from 'dom-to-image';

exportPdf(){
    const div = document.getElementById('pdf');
    const options = { background: 'white', height: 845, width: 595 };
    domtoimage.toPng(div, options).then((dataUrl) => {
        //Initialize JSPDF
        const doc = new jsPDF('p', 'mm', 'a4');
        //Add image Url to PDF
        doc.addImage(dataUrl, 'PNG', 0, 0, 210, 340);
        doc.save('pdfDocument.pdf');
    }
}
Oscar Diaz
  • 109
  • 2
  • 8
0

The latest html2canvas supports shadow dom, like https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js

BZ_QA
  • 106
  • 3