Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG string to PNG output using Node / gm

I'd like to take an SVG string and output a PNG to the browser. I've taken a look at a couple of posts:

I can output a png but not an svg. I can write the svg to a file just fine - just can't stream it.

Here's what I have:

var gm = require('gm');
var im = gm.subClass({ imageMagick: true });

var inputsvg = 'public/test.svg';
var inputpng = 'public/test.png';

// works
im(inputsvg).write(output, function(err){
  if (!err) console.log('image converted.');
});

// works
im(inputpng).write(output, function(err){
  if (!err) console.log('image converted.');
});


res.set('Content-Type', 'image/png'); 

// works
im(inputpng).stream(function (err, stdout, stderr) {
  stdout.pipe(res);
});

// does not work - no errors given.
im(inputsvg).stream(function (err, stdout, stderr) {
  stdout.pipe(res);
});
like image 709
cyberwombat Avatar asked Apr 08 '13 03:04

cyberwombat


1 Answers

Okay got it.

var svg = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><svg width="840" height="430"  xmlns="http://www.w3.org/2000/svg" version="1.1"><rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)" /></svg>';

var buf = new Buffer(svg);
res.set('Content-Type', 'image/png');
gm(buf, 'svg.svg').stream('png', function (err, stdout, stderr) {
  stdout.pipe(res);
});

Some important points:

  • the xml line must be there
  • a width and height must be provided in the svg tag
  • the stream() function needs the format parameter ('png')

Hope that helps someone.

like image 76
cyberwombat Avatar answered Oct 22 '22 05:10

cyberwombat