- 文件系统模块
- PhantomJS - 属性
- PhantomJS - 方法
- 系统模块
- PhantomJS - 属性
- Web 服务器模块
- PhantomJS - 属性
- PhantomJS - 方法
- 其他
- 命令行界面
- PhantomJS - 屏幕截图
- PhantomJS - 网页自动化
- PhantomJS - 网络监控
- PhantomJS - 测试
- PhantomJS - REPL
- PhantomJS - 示例
- PhantomJS 有用资源
- PhantomJS - 快速指南
- PhantomJS - 有用资源
- PhantomJS - 讨论
PhantomJS - 屏幕截图
PhantomJS 在截取网页截图和将网页转换为 PDF 方面非常有用。我们在此提供了一个简单的示例,来演示其工作原理。
示例
var page = require('webpage').create();
page.open('http://phantom.org/',function(status){
page.render('phantom.png');
phantom.exit();
});
执行上述程序,输出将保存为 phantom.png。
将网页转换为 PDF
PhantomJS 还支持将网页转换为 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();
}
});
上述程序生成以下输出。
The above will convert the page into pdf and will be saved in test.pdf
将画布转换为图像
Phantomjs 可以轻松地将画布转换为图像。请查看以下示例,了解其工作原理。
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();
上述程序生成以下输出。
广告