gustavopaes
9/2/2013 - 4:30 PM

Cria um arquivo PNG com a página renderizada. Modo de uso: phantomjs http://www.uol.com.br/

Cria um arquivo PNG com a página renderizada. Modo de uso: phantomjs http://www.uol.com.br/

var page = require('webpage').create(),
  system = require('system');

page.viewportSize = { width: 1024, height: 768 };

if(system.args.length < 2) {
  console.log("Informe a URL para realizar o prinscreen.");
  console.log("phantomjs http://www.uol.com.br/");
  phantom.exit(1);
}

var url = system.args[1];

function waitFor(what, callback) {
  setInterval(function() {
    if( what() === true ) {
      callback()
    }
  }, 500);
}

page.open(url, function (status) {
  if (status !== 'success') {
    console.log('Unable to access the network!');
  } else {
    page.evaluate(function () {
      var body = document.body;

      if( !!body.style.backgroundColor === false ) {
        body.style.backgroundColor = "white";
      }

      // força o carregamento das imagens que estão programadas
      // para carregar durante o scroll do usuário -- lazyload.
      var images = document.querySelectorAll('img.lazyload'), t = images.length;
      window.l = images.length;
      window.c = 0;
      while( t-- ) {
        var original = images.item(t).getAttribute('data-original');
        if(!!original === true) {
          images.item(t).setAttribute('src', original);
          images.item(t).onload = images.item(t).onerror = function() {
            c += 1;
          };
        }
        else {
          l -= 1;
        }
      }
    });

    // Aguarda o carregamento de todas as imagens da página.
    // Só é usado em caso de lazyload instalado na págona. Sem o lazyload,
    // o printscreen será gerado no primeiro 'loop'
    waitFor(function() {
      return page.evaluate(function() {
        return window.c === window.l;
      });
    }, function() {
      // Gera o arquivo PNG
      var filename = url.replace(/^http(s)?:\/\//, '').replace(/[\/]/g, '-');
      filename += "_" + (+new Date()) + '.png';

      console.log(filename);
      page.render(filename);
      phantom.exit();
    });
  }
});