shields/svg-to-img.js
Thaddee Tyl 6620d46f23 Local font loading into SVG in Phantom.js
Ensures use of Verdana server-side when rendering images.
2014-01-05 22:02:02 +01:00

30 lines
1.1 KiB
JavaScript

var fs = require('fs');
var os = require('os');
var path = require('path');
var phantom = require('phantomjs');
var childProcess = require('child_process');
var phantomScript = path.join(__dirname, 'phantomjs-svg2png.js');
// If available, use the font here.
var fontPath = './Verbana.ttf';
try {
// This happens at startup. Needn't be async.
var fontBase64 = fs.readFileSync(fontPath, 'base64');
} catch(e) {}
module.exports = function (svg, format, out, cb) {
var tmpFile = path.join(os.tmpdir(),
"svg2img-" + (Math.random()*2147483648|0) + "." + format);
// Conversion to PNG happens in the phantom script.
childProcess.execFile(phantom.path, [phantomScript, svg, tmpFile],
function(err, stdout, stderr) {
if (stdout) { console.log(stdout); }
if (stderr) { console.log(stderr); }
if (err != null) { console.error(err.stack); if (cb) { cb(err); } return; }
var inStream = fs.createReadStream(tmpFile);
inStream.pipe(out);
// Remove the temporary file after use.
inStream.on('end', function() { fs.unlink(tmpFile, cb); });
});
};