diff --git a/phantomjs-svg2png.js b/phantomjs-svg2png.js index 481b8bf..783cd74 100644 --- a/phantomjs-svg2png.js +++ b/phantomjs-svg2png.js @@ -1,20 +1,35 @@ var page = require('webpage').create(); var system = require('system'); var svg = system.args[1]; -var svgUrl = 'data:image/svg+xml,' + window.encodeURI(svg); var tmpFile = system.args[2]; -page.viewportSize = getSvgDimensions(svg); -page.open(svgUrl, function(status) { - if (status !== 'success') { - console.error('Failed to load the following SVG data:'); - console.error(svgUrl); - phantom.exit(1); - } else { - page.render(tmpFile); - phantom.exit(); - } -}); +// Optional local font loading. +var fs = require('fs'); +var fontPath = './Verdana.ttf'; +if (fs.isFile(fontPath)) { + var fontData = fs.read(fontPath, 'b'); + btoa(fontData, function(fontBase64) { + svg = svg.slice(0, svg.indexOf('')) + ''; + renderSvg(svg); + }); +} else { renderSvg(svg); } + +function renderSvg(svg) { + var svgUrl = 'data:image/svg+xml,' + window.encodeURI(svg); + page.viewportSize = getSvgDimensions(svg); + page.open(svgUrl, function(status) { + if (status !== 'success') { + console.error('Failed to load the following SVG data:'); + console.error(svgUrl); + phantom.exit(1); + } else { + page.render(tmpFile); + phantom.exit(); + } + }); +} function getSvgDimensions(svg) { var frag = window.document.createElement('div'); @@ -22,6 +37,17 @@ function getSvgDimensions(svg) { var svgRoot = frag.querySelector('svg'); return { width: parseFloat(svgRoot.getAttribute('width') || 80), - height: parseFloat(svgRoot.getAttribute('height') || 19) + height: parseFloat(svgRoot.getAttribute('height') || 18) }; } + +function btoa(data, cb) { + page.open('about:blank', function(status) { + if (status !== 'success') { + console.error('Failed to load blank page.'); + phantom.exit(1); + } else { + cb(page.evaluate(function(data) { return window.btoa(data); }, data)); + } + }); +} diff --git a/svg-to-img.js b/svg-to-img.js index 81f8840..42fea57 100644 --- a/svg-to-img.js +++ b/svg-to-img.js @@ -5,6 +5,13 @@ 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); diff --git a/template.svg b/template.svg index 1cc7fb8..2f8e181 100644 --- a/template.svg +++ b/template.svg @@ -18,7 +18,7 @@ - + {{=it.text[0]}} {{=it.text[1]}}