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);
});
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:
Hope that helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With