Skip to content
Advertisement

How to pass HTML to JPG/PNG? In Javascript/Typescript

How can i convert an HTML to a JPG/PNG image? I already tried various options but none works for me, they only make the image of some parts of the HTML.

Example with html2canvas:

TS

capturar() {
    html2canvas(document.body).then(function(canvas) {
      document.body.appendChild(canvas);
    });
}

HTML

<div id="capture">
    <ion-grid class="grid-padding-info-verde">
      <ion-row class="row-info">

        <ion-col size="12">
          <ion-icon name="checkmark-circle" class="check-icono"></ion-icon>
        </ion-col>

        <ion-col size="12" class="info-col">
          <span class="trans-sub"> {{ this.fecha }}</span>
        </ion-col>

      </ion-row>
    </ion-grid>
</div>

This error I get when I use the example: enter image description here

“DOMException: Failed to set the ‘adoptedStyleSheets’ property on ‘ShadowRoot’: Sharing constructed stylesheets in multiple documents is not allowed”

Do you know any other tools? Basically I need to take a screenshot of only a part of my screen not the full screen. Any ideas?

Advertisement

Answer

You can use the package: https://www.npmjs.com/package/dom-to-image

In your page:

import domtoimage from 'dom-to-image';

capturar(){
    var node = document.getElementById('capture');
    var options = {quality: 1};

    domtoimage.toJpeg(node, options).then((dataUrl) => {
      console.log(dataUrl) //Image in base64 jpeg
    });
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement