Skip to content

Instantly share code, notes, and snippets.

@ajsharma
Created February 14, 2019 23:59
Show Gist options
  • Save ajsharma/060b5aade07606c67afd5840f2e0438b to your computer and use it in GitHub Desktop.
Save ajsharma/060b5aade07606c67afd5840f2e0438b to your computer and use it in GitHub Desktop.
#!/usr/local/bin/phantomjs --ssl-protocol=tlsv1
// Script to screenshot the given URL. It renders when it receives
// a callPhantom invocation with {renderNow: true}. The viewport
// defaults to the URL's body size.
var system = require('system');
// --------------------- Set Timeout ---------------------
function timeoutAndExit() {
console.info("Screenshot timeout, exiting")
phantom.exit();
}
var timeout = system.args[1]
setTimeout(timeoutAndExit, timeout)
// --------------------- Init Args ---------------------
var urlToRender = system.args[2]
var outputFile = system.args[3]
// --------------------- Load and Screenshot Page ---------------------
var page = require('webpage').create();
if (system.args[4] === 'pdf') {
page.paperSize = { width: 1003, height: 800, margin: 16 };
}
page.onError = function (msg, trace) {
console.log(urlToRender + ' - An error occurred: ' + msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
page.onCallback = function(data) {
console.log(urlToRender + ' - Received phantom callback: ' + JSON.stringify(data));
if (!data.renderNow) {
return
}
if (system.args[4] === 'pdf') {
console.log('Rendering PDF to: ' + outputFile)
page.render(outputFile, {format: 'pdf', quality: 30})
} else {
console.log('Rendering PNG to: ' + outputFile)
page.render(outputFile, {format: 'png', quality: 30})
}
phantom.exit();
};
console.info("Requesting url: " + urlToRender)
page.open(urlToRender, function() {
console.info('Opened page, waiting for signal')
});
@ajsharma
Copy link
Author

to run:

rm ./imgs/share_test.png || true  && ./aj/share_test.js 12000 "http://localhost:3000/shared/85784dbf-bf8b-4f33-a19e-e5892c7c6677?screenshot=true" ./imgs/share_test.png && open ./imgs/share_test.png

@ajsharma
Copy link
Author

share_test.js is name of script in this case

@ajsharma
Copy link
Author

install phantom from here http://phantomjs.org/download.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment