Phantomjs-screen-capture

提供:Dev Guides
移動先:案内検索

PhantomJS-画面キャプチャ

PhantomJSは、Webページのスクリーンショットを撮り、WebページをPDFに変換するのに非常に役立ちます。 ここで、それがどのように機能するかを示す簡単な例を示しました。

var page = require('webpage').create();
page.open('http://phantom.org/',function(status){
   page.render('phantom.png');
   phantom.exit();
});

上記のプログラムを実行すると、出力は phantom.png として保存されます。

最適なソリューション

WebページをPDFに変換する

PhantomJSは、Webページをヘッダーとフッターが追加されたPDFに変換するのにも役立ちます。 次の例を見て、その仕組みを理解してください。

var wpage = require('webpage').create();
var url = "https://en.wikipedia.org/wiki/Main_Page";
var output = "test.pdf";

wpage.paperSize = {
   width: screen.width+'px',
   height: '1500px',

   margin: {
      'top':'50px',
      'left':'50px',
      'rigtht':'50px'
   },
   orientation:'portrait',
   header: {
      height: "1cm",
      contents: phantom.callback(function(pageNumber, nPages) {
         return "<h5>Header <b>" + pageNumber + "/" + nPages + "</b></h5>";
      })
   },
   footer: {
      height: "1cm",
      contents: phantom.callback(function(pageNumber, nPages) {
         return "<h5>Footer <b>" + pageNumber + "/" + nPages + "</b></h5>";
      })
   }
}
wpage.open(url, function (status) {
   if (status !== 'success') {
      console.log('Page is not opening');
      phantom.exit();
   } else {
      wpage.render(output);
      phantom.exit();
   }
});

上記のプログラムは、次の output を生成します。

The above will convert the page into pdf and will be saved in test.pdf

キャンバスを画像に変換する

PhantomjsはCanvasをImageに簡単に変換できます。 次の例を見て、その仕組みを理解してください。

var page = require('webpage').create();
page.content = '<html><body><canvas id="surface" width="400" height="400"></canvas></body></html>';

page.evaluate(function() {
   var context,e1;
   el = document.getElementById('surface');

   context = el.getContext('2d');
   context.font = "30px Comic Sans MS";
   context.fillStyle = "red";
   context.textAlign = "center";
   context.fillText("Welcome to PhantomJS ", 200, 200);

   document.body.style.backgroundColor = 'white';
   document.body.style.margin = '0px';
});
page.render('canvas.png');
phantom.exit();

上記のプログラムは、次の output を生成します。

Phantomjsへようこそ