Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Created July 22, 2012 15:57
Show Gist options
  • Save crazy4groovy/3160121 to your computer and use it in GitHub Desktop.
Save crazy4groovy/3160121 to your computer and use it in GitHub Desktop.
PhantomJS script to loop through local directory and render HTML pages as PNG
/* tested on PhantomJS 1.6 */
var page = require('webpage').create(), loadInProgress = false, fs = require('fs');
var htmlFiles = new Array();
// console.log(fs.workingDirectory);
// console.log(phantom.args[0]);
var curdir = phantom.args[0] || fs.workingDirectory;
var curdirList = fs.list(curdir);
console.log("dir file count: " + curdirList.length);
// loop through files and folders //
for(var i = 0; i< curdirList.length; i++) {
var fullpath = curdir + fs.separator + curdirList[i];
// check if item is a file //
if(fs.isFile(fullpath)) {
// check that file is html //
if(fullpath.toLowerCase().indexOf('.html') != -1) {
// show full path of file //
// console.log('File path: ' + fullpath);
htmlFiles.push(fullpath); // todo: make this more async (i.e. pop on/off stack WHILE rending pages)
}
}
}
console.log('HTML files found: ' + htmlFiles.length);
// output pages as PNG //
var pageindex = 0;
var fileName = '';
var interval = setInterval(function() {
if (!loadInProgress && pageindex < htmlFiles.length) {
// console.log("image " + (pageindex + 1) + " of " htmlFiles.length);
fileName = htmlFiles[pageindex];
page.open(htmlFiles[pageindex]);
}
if (pageindex == htmlFiles.length) {
console.log("<< Image render complete! >>");
phantom.exit();
}
}, 250);
page.onLoadStarted = function() {
loadInProgress = true;
// console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
var dest = fileName + ".png";
console.log('saving: ' + fileName + ".png");
page.evaluate(
function () {
var scaleVal = "scale("+arguments[0] || '1.0'+")";
document.body.style.webkitTransform = scaleVal;
},
phantom.args[1]
);
page.render(dest); // RENDER PAGE //
// console.log('page ' + (pageindex + 1) + ' load finished');
pageindex++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment