Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Rasterizes svg images to (alpha) png with phantomjs
#! /usr/bin/env phantomjs
// -*- js2 -*-
var webpage = require('webpage')
, system = require('system')
, URL, FILENAME, W, H;
;
if (system.args.length < 2 || system.args.length > 5) {
console.log('Usage: svg2png source.svg output.png [width||?] [height||?]');
phantom.exit();
}
else {
URL = system.args[1];
FILENAME = system.args[2];
W = Number(system.args[3]);
H = Number(system.args[4]);
if (isNaN(W)) W = undefined;
if (isNaN(H)) H = undefined;
peek(URL, grabSize);
}
function peek(url, fn) {
var page = webpage.create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open(url, function (status) {
if (status !== 'success')
console.log('Unable to load ' + url);
else
fn(page);
});
}
function grabSize(page) {
page.onConsoleMessage = function(msg) {
var d = JSON.parse(msg);
if (!W && !H) { W = d.w; H = d.h; }
if ( W && !H) { H = W * d.h / d.w; }
if (!W && H) { W = H * d.w / d.h; }
console.log(JSON.stringify(d), W, H);
screenshot(URL, FILENAME, W, H);
};
page.evaluate(function() {
var svg = document.documentElement
, w = svg.getAttribute('width')
, h = svg.getAttribute('height')
, box = svg.viewBox.animVal
, b_w = box.width
, b_h = box.height
;
if (b_w && b_h) {
if (w && !h) h = w * b_h / b_w;
if (h && !w) w = h * b_w / b_h;
if (!w&& !h) {
w = b_w;
h = b_h;
}
}
console.log(JSON.stringify({ w: Number(w), h: Number(h) }));
});
}
function screenshot(url, filename, w, h) {
var page = webpage.create();
page.viewportSize = { width: w, height: h };
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load ' + url);
phantom.exit();
}
else {
window.setTimeout(function () {
page.render(filename);
phantom.exit();
}, 200);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.