从node.js加载并修改SVG文件



我们有一个应发送png文件的API。该png文件是几个SVG文件的组成和属性的一些更改:背景色,图像大小..

我们在服务器上使用node.js。

我已经尝试使用D3成功地尝试修改SVG文件&JSDOM在后端使用D3:

var fs = require('fs');
var d3 = require('d3');
var JSDOM = require('jsdom').JSDOM;
var outputLocation = 'test.svg';
const window = (new JSDOM(`<html><head></head><body></body></html>`, { pretendToBeVisual: true })).window;
window.d3 = d3.select(window.document); //get d3 into the dom
d3.xml("./react02.svg").mimeType("image/svg+xml").get(function(error, xml) {
    var importedNode = document.importNode(xml.documentElement, true);
    if (error) throw error;
    console.log(xml);
    window.d3.select('body')
    .append('div').attr('class', 'container')
    .appendChild(importedNode);
});
fs.writeFileSync(outputLocation, window.d3.select('.container').html()) //using sync to keep the code simple

,但我总是有一个错误:

TypeError: Cannot read property 'innerHTML' of null
    at Selection.selection_html [as html] (/home/juanda/kk2/node_modules/d3-selection/build/d3-selection.js:793:20)
    at Object.<anonymous> (/home/juanda/kk2/test2.js:18:65)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Function.Module.runMain (module.js:665:10)
    at startup (bootstrap_node.js:201:16)
    at bootstrap_node.js:626:3

找不到任何示例/库阅读和修改服务器端的SVG文件。

从d3移至snapsvg,因为我不需要数据分析,只需使用SVG本身即可。这是我的代码:

let {JSDOM} = require('jsdom')
var resolve = require('resolve');
resolve('snapsvg', { basedir: __dirname }, function (err, resource) {
  if (err) console.error(err)
  else {
    const options = {
      runScripts: "dangerously",
      resources: "usable",
      url: "file:///prueba.html" // avoid cors error reading svg file
    };
    const dom = new JSDOM(`
      <!DOCTYPE html><html><body><div id="test"></div></body></html>
    `, options);
    var script = dom.window.document.createElement('script');
    script.src = `file://${resource}`;
    var head= dom.window.document.getElementsByTagName('head')[0];
    head.appendChild(script);
    // console.log(dom.serialize())
    script.onload = function () {
      // console.log("Script loaded and ready");
      // console.log(dom.window)
      var s = dom.window.Snap("#test");
      dom.window.Snap.load("file:///Users/juandaniel/Code/prueba/2375.svg", onSVGLoaded);
      function onSVGLoaded(data) {
        s.append(data);
        console.log(s.node.innerHTML)
      }
    };
  }
});

最新更新