PhantomJs prints SVG source code instead of rendering it -
i have set new windows machine rasterize bunch of svg documents png images. have simplified ariya hidayat's rasterize script :
var page = require('webpage').create(), system = require('system'), fs = require('fs'), svgpath, output; if (system.args.length < 3 || system.args.length > 5) { console.log('usage: rasterize.js url output'); phantom.exit(1); } else { svgpath = fs.workingdirectory + '/' + system.args[1]; output = system.args[2]; page.viewportsize = { width: 600, height: 120 }; if (!fs.isfile(svgpath)) { console.log(svgpath+' not exist'); phantom.exit(1); } page.onloadfinished = function() { page.render(output); console.log('thumbnail created'); phantom.exit(0); }; page.open(svgpath); }
and here how call script : bin\phantomjs js/headless/rasterize.js "simple.svg" "simple.svg.png" 2>&1
simple.svg
contains data :
<svg width="110" height="60" id="simple" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="10" y="10" height="50" width="100" style="stroke:#ff0000; fill: #0000ff"/> </svg>
once script has been executed (without error), simple.svg.png
rendered :
this strange, , i'm pretty sure thumbnail correctly generated on previous machine. why render svg's source code ?
it looks issue load svg file system, , phantomjs has no way of knowing want show svg image , not text. solution instantiate local server can load svg file system , configure content type make rendered expect svg :
var page = require('webpage').create(), server = require('webserver').create(), system = require('system'), fs = require('fs'), svgpath, output; var serverurl = '127.0.0.1:8888'; server.listen(serverurl, function (request, response) { var cleanedurl = request.url .replace(/\//g, fs.separator) .replace(/\?.*$/g, ''); var pagepath = fs.workingdirectory + cleanedurl; response.statuscode = 200; response.setheader("content-type", "image/svg+xml"); try { response.write(fs.read(pagepath)); } catch(err) { console.error('error while reading ' + cleanedurl + '(requested url : '+request.url+')'); response.close(); phantom.exit(1); } response.close(); }); if (system.args.length < 3 || system.args.length > 5) { console.log('usage: rasterize.js url output'); phantom.exit(1); } else { svgpath = fs.workingdirectory + '/' + system.args[1]; output = system.args[2]; page.viewportsize = { width: 600, height: 120 }; if (!fs.isfile(svgpath)) { console.log(svgpath+' not exist'); phantom.exit(1); } page.onloadfinished = function() { page.render(output); console.log('thumbnail created'); server.close(); phantom.exit(0); }; page.open('http://'+serverurl+'/'+system.args[1]); }
Comments
Post a Comment