LoginSignup
17
19

More than 5 years have passed since last update.

PhantomJSでHTMLファイルをpngに変換するスクリプトを書いた

Last updated at Posted at 2014-07-23

MITライセンスです。
ソースは https://github.com/hnakamur/html2png に置きました。

ソース

短いのでここにも引用します。

件名で変換と言っていますが、openでウェブページを開いてrender APIを使ってスクリーンショットをとっているだけです。

https
#!/usr/bin/env phantomjs
var page = require('webpage').create();
var system = require('system');

if (system.args.length !== 3) {
  console.log('Usage: ' + system.args[0] + ' html_file png_file');
  phantom.exit(1);
}

var htmlFile = system.args[1];
var pngFile = system.args[2];

page.open(htmlFile, function(status) {
  if (status === 'fail') {
    console.log('Error! failed to open ' + htmlFile);
    phantom.exit(1);
  }

  page.evaluate(function() {
    document.body.bgColor = 'white';
  });
  page.render(pngFile);
  phantom.exit();
});

PhantomJSはデフォルトの背景色は透明ですが、FAQ | PhantomJSの"Q: When using render(), why is the background transparent?"のコードを使って白にしています。

使い方

事前にPhantomJS | PhantomJSをインストールしてPATHを通しておいてください。

./html2png HTMLのファイルパスまたはURL PNGのファイルパス

出力例

./html2png http://phantomjs.org/ phantomjs.org.png

で変換した例です。

phantomjs.org.png

17
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
19