不打开浏览器完美全屏截图

最近在学习neo4j,里面有个子项目neo4j-browser,是一个angular+nodejs的web项目,里面用到了phantomjs(官方只提供源码下载,Linux/Mac下编译很简单,这里附上Windows已编译版本下载地址)这个东西,查阅了一下其官方文档,原来是一个webkit的js封装实现

Full web stack

No browser required

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
这里面有个截图的例子
var page = require(‘webpage’).create();

page.open(‘http://github.com/‘, function() {

page.render(‘github.png’);

phantom.exit();

});
例子很简单,只是网址是固定的,并且截屏的宽固定是600px,我根据example/rasterize.js做了少许修改在上面的例子添加了一些命令行参数解析,可以作为一个非常简单的截图工具使用,代码如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
var page = require('webpage').create(),
system = require('system'),
address, output, size;

if (system.args.length < 3 || system.args.length > 4) {
console.log('Usage: phantomjs take_snapshot.js URL savedFilename [paperwidth[*paperheight]]');
console.log(' support image format: png/jpg');
console.log(' [paperwidth[*paperheight]: default 800px*600px');
console.log(' "1920px" entire page, window width 1920px');
console.log(' "800px*600px" window, clipped to 800x600');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 800, height: 600 };
if (system.args.length == 4 && system.args[3].substr(-2) === "px") {
size = system.args[3].split('*');
if (size.length === 2) {
pageWidth = parseInt(size[0], 10);
pageHeight = parseInt(size[1], 10);
page.viewportSize = { width: pageWidth, height: pageHeight };
page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight };
} else {
console.log("size:", system.args[3]);
pageWidth = parseInt(system.args[3], 10);
pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any
console.log ("pageHeight:",pageHeight);
page.viewportSize = { width: pageWidth, height: pageHeight };
}
}
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}

使用方式例如可以是
phantomjs take_snapshot.js http://liudonghua.com liudonghua_1080p.png 1080px