ThinkJS入门学习实例(4): 网页截图

完整示例代码

六、网页截图

node.js有十几万个package可供使用,这使得实现各种功能非常方便。

在ThinkJS中使用node.js的package也是一样,npm install后,直接require即可。

网页截图需要使用node-webshot,node-webshot更多设置请参考项目主页:

  • 首先在View里写好HTML结构:

HTML文件路径为:App/View/Admin/index_screen.html

<div class="row">
 <div class="col-md-2">
 <form action="/admin/index/screen" method="POST">
 <div class="form-group">
 <input class="form-control" type="text" name="url" placeholder="请输入网址" />
 </div>
 <button class="btn btn-primary" type="submit">Submit</button>
 </form>
 </div>
</div>
  • 然后是Controller:

App/Lib/Controller/Admin/IndexController.js

// 网页截图
screenAction: function() {
 var self = this;
 var url = self.post('url');
 var imgName = url.replace(/http.*:\/\//g, '').replace(/[\/]|[\?]/g, '.');
 if (self.isPost()) {
 var options = {
 // 截图视窗宽度
 windowSize: {
 width: 1200
 },
 // 网页截图宽高:width = all 会继承windowSize的设置,height = all表示截取完整网页
 shotSize: {
 width: 'all',
 height: 'all'
 },
 streamType: 'png',
 // 渲染完成后延迟一秒截图
 renderDelay: 1000,
 timeout: 20000,
 defaultWhiteBackground: true
 };
 // 开始截图, 图片保存到 /www/screen/ 下
 webshot(url, 'screen/' + imgName + '.' + options.streamType, options, function(err) {
 if (err == null) {
 self.success('截图成功');
 } else {
 self.error('截图失败');
 }
 });
 } else {
 self.assign({
 'title': '网页截图'
 });
 self.display();
 }
}

如果提示截图成功,那么可以在/www/screen/可以看到图片了。

未完待续。。。

更多相关文章

水平有限,如果文章有啥错误,还请不吝赐教 :)

完整示例代码

w3ctech微信

扫码关注w3ctech微信公众号

共收到0条回复

AltStyle によって変換されたページ (->オリジナル) /