Convert HTML into PNG

5

How to convert, via code javascript or php, the html ( DOM ) of the page being displayed for an image? I need the page shown to the user to be converted to an image file in png format so that it can be downloaded and started automatically.

    
asked by anonymous 05.10.2017 / 18:37

4 answers

8

I would use the library: dom-to-image
You can read the documentation on the use her here

Here's an example:

var node = document.getElementById('my-node');

domtoimage.toPng(node)
    .then (function (dataUrl) {
        var img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img); //esse método exibe a imagem na própria pagina
    })
    .catch(function (error) {
        console.error('erro exibido caso falhe', error);
    });
  

How do I open the image on another page?

Simple, refer to a blank page as the document value to use.

  

How do I make the image to be transformed and its download started automatically?

domtoimage.toPng(document.getElementById('my-node'), { quality: 1 })
    .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = 'NomeDaImagem.png';
        link.href = dataUrl;
        link.click();
    });
    
05.10.2017 / 18:45
4

I do not think it's possible to save a screenshot with Javascript. But an interesting alternative is you draw the html you want on a canvas element, and then use the toDataURL() method to get the data on base 64, and save on image

document.getElementById('desenhar').onclick = function (){
  var c = document.getElementById("teste");
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(95,50,40,0,2*Math.PI);
  ctx.stroke();
}

document.getElementById('salvar').onclick = function (){
  console.log(document.getElementById('teste').toDataURL());
}
<canvas id="teste"></canvas><br>
<button id="desenhar">Desenhar</button>
<button id="salvar">Salvar</button>
    
05.10.2017 / 18:49
3

You can use the imagegrabscreen () and imagegrabwindow () function, which allows you to create browser screenshots.

See the comments in the manual to learn how to omit Chrome from your browser. With DCOM enabled, this would also work with remote Windows machines that have been configured to allow access through DCOM.

Links:

05.10.2017 / 18:47
2

You have a JS library for this as well: link

    
05.10.2017 / 18:49