asciinema.org/bin/rasterize
2015-03-29 14:15:05 +00:00

79 lines
2.0 KiB
JavaScript
Executable File

#!/usr/bin/env phantomjs
var system = require('system');
if (system.args.length < 6) {
console.log("usage: " + system.args[0] + " <url> <filename> <format> <selector> <scale>");
console.log(" ex: " + system.args[0] + " page.html page.png png 'body > div' 2");
phantom.exit(1);
}
var url = system.args[1];
var filename = system.args[2];
var format = system.args[3];
var selector = system.args[4];
var scale = parseInt(system.args[5], 10);
var page = require('webpage').create();
page.viewportSize = { width: 9999, height: 9999 };
page.zoomFactor = scale;
page.onConsoleMessage = function(msg) {
console.log('console.log: ' + msg);
};
page.onError = function(msg, trace) {
console.log('Script error: ' + msg);
phantom.exit(1);
}
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
phantom.exit(1);
};
page.open(url, function(status) {
if (status !== "success") {
console.log("Failed to load " + url);
phantom.exit(1);
}
var rect = page.evaluate(function(selector) {
// Alternative to zoomFactor:
//
// /* scale the whole body */
// document.body.style.webkitTransform = "scale(2)";
// document.body.style.webkitTransformOrigin = "0% 0%";
// /* fix the body width that overflows out of the viewport */
// document.body.style.width = "50%";
//
// It has small issue with letter spacing though.
var elements = document.querySelectorAll(selector);
if (elements.length > 0) {
return elements[0].getBoundingClientRect();
}
}, selector);
if (!rect) {
console.log("Couldn't get geometry of requested DOM element");
phantom.exit(1);
return;
}
page.clipRect = {
left: rect.left * scale,
top: rect.top * scale,
width: rect.width * scale,
height: rect.height * scale
};
page.render(filename, { format: format });
phantom.exit(0);
});
// vim: ft=javascript