phantom.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const db = require('../models/db');
  3. const config = require('config');
  4. const phantom = require('node-phantom-simple');
  5. const os = require('os');
  6. module.exports = {
  7. // type = "pdf" or "png"
  8. takeScreenshot: function(space,type,on_success,on_error) {
  9. var spaceId = space._id;
  10. var space_url = config.get("endpoint")+"/api/spaces/"+spaceId+"/html";
  11. var export_path = os.tmpdir()+"/"+spaceId+"."+type;
  12. var timeout = 5000;
  13. if (type=="pdf") timeout = 30000;
  14. space_url += "?api_token="+config.get("phantom_api_secret");
  15. console.log("[space-screenshot] url: "+space_url);
  16. console.log("[space-screenshot] export_path: "+export_path);
  17. var on_success_called = false;
  18. var on_exit = function(exit_code) {
  19. if (exit_code>0) {
  20. console.error("phantom abnormal exit for url "+space_url);
  21. if (!on_success_called && on_error) {
  22. on_error();
  23. }
  24. }
  25. };
  26. phantom.create({ path: require('phantomjs-prebuilt').path }, function (err, browser) {
  27. if (err) {
  28. console.error(err);
  29. } else {
  30. return browser.createPage(function (err, page) {
  31. console.log("page created, opening ",space_url);
  32. if (type=="pdf") {
  33. var psz = {
  34. width: space.width+"px",
  35. height: space.height+"px"
  36. };
  37. page.set('paperSize', psz);
  38. }
  39. page.set('settings.resourceTimeout',timeout);
  40. page.set('settings.javascriptEnabled',false);
  41. return page.open(space_url, function (err,status) {
  42. page.render(export_path, function() {
  43. on_success_called = true;
  44. if (on_success) {
  45. on_success(export_path);
  46. }
  47. page.close();
  48. browser.exit();
  49. });
  50. });
  51. });
  52. }
  53. }, {
  54. onExit: on_exit
  55. });
  56. }
  57. };