PhantomJs 打印 SVG 源代码而不是渲染它

PhantomJs prints SVG source code instead of rendering it

我设置了一台新的 Windows 机器,我想在其中将一堆 SVG 文档光栅化为 PNG 图像。我已将 Ariya Hidayat 的 rasterize 脚本简化为:

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+' does not exist');
        phantom.exit(1);
    }

    page.onLoadFinished = function() {
        page.render(output);
        console.log('thumbnail created');
        phantom.exit(0);
    };

    page.open(svgPath);
}

下面是我调用脚本的方式:bin\phantomjs js/headless/rasterize.js "simple.svg" "simple.svg.png" 2>&1

simple.svg 包含此数据:

<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>

一旦脚本被执行(没有错误),simple.svg.png 将呈现如下:

这真的很奇怪,我很确定缩略图是在以前的机器上正确生成的。为什么它只渲染 SVG 的源代码?

看起来问题是我从文件系统加载了 SVG,而 PhantomJS 无法知道我想将 SVG 显示为图像而不是文本。 解决方案是实例化一个 local server ,我可以在其中从文件系统加载 SVG 并配置内容类型以使其像您期望的 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+' does 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]);
}

通过 Java 的 ProcesBuilder 执行转换时我得到了相同的结果,而通过 cmdline 启动它时它工作正常。我试图在源文件前加上 file:// 协议,例如file:///D:/phantomjs/test.svg 在我的案例中它按预期工作。