phantom.js 1.85 KB
Newer Older
mntmn's avatar
mntmn committed
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
'use strict';

require('../models/schema');
var config = require('config');
var phantom = require('node-phantom-simple');

module.exports = {
  // type = "pdf" or "png"
  takeScreenshot: function(space,type,on_success,on_error) {
    var spaceId = space._id;
    var space_url = config.get("endpoint")+"/api/spaces/"+spaceId+"/html";

    var export_path = "/tmp/"+spaceId+"."+type;

    var timeout = 5000;
    if (type=="pdf") timeout = 30000;

    space_url += "?api_token="+config.get("phantom_api_secret");

    console.log("[space-screenshot] url: "+space_url);
    console.log("[space-screenshot] export_path: "+export_path);

    var on_success_called = false;

    var on_exit = function(exit_code) {
      if (exit_code>0) {
        console.log("phantom abnormal exit for url "+space_url);
        if (!on_success_called && on_error) {
          on_error();
        }
      }
    };

    phantom.create({ path: require('phantomjs-prebuilt').path }, function (err, browser) {
35
      if(err){
Martin Guether's avatar
Martin Guether committed
36
        console.log(err);
37
38
39
      }else{
        return browser.createPage(function (err, page) {
          console.log("page created, opening ",space_url);
mntmn's avatar
mntmn committed
40

41
42
43
44
45
46
47
          if (type=="pdf") {
            var psz = {
              width: space.advanced.width+"px",
              height: space.advanced.height+"px"
            };
            page.set('paperSize', psz);
          }
mntmn's avatar
mntmn committed
48

49
50
          page.set('settings.resourceTimeout',timeout);
          page.set('settings.javascriptEnabled',false);
mntmn's avatar
mntmn committed
51

52
53
54
55
56
57
58
59
60
          return page.open(space_url, function (err,status) {
            page.render(export_path, function() {
              on_success_called = true;
              if (on_success) {
                on_success(export_path);
              }
              page.close();
              browser.exit();
            });
mntmn's avatar
mntmn committed
61
          });
62
63
64
        });        
      }

mntmn's avatar
mntmn committed
65
66
67
68
69
    }, {
      onExit: on_exit
    });
  }
};