public
Last active

Rasterizes svg images to (alpha) png with phantomjs

  • Download Gist
svg2png
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
#! /usr/bin/env phantomjs
 
var webpage = require('webpage')
, URL, FILENAME, W, H;
;
 
if (phantom.args.length < 2 || phantom.args.length > 5) {
console.log('Usage: svg2png source.svg output.png [width||?] [height||?]');
phantom.exit();
}
else {
URL = phantom.args[0];
FILENAME = phantom.args[1];
W = Number(phantom.args[2]);
H = Number(phantom.args[3]);
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; }
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);
}
});
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.