以编程方式将D3.js图形导出为静态SVG文件 [英] Exporting D3.js graphs to static SVG files, programmatically

查看:754
本文介绍了以编程方式将D3.js图形导出为静态SVG文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以编程方式生成大量D3图形。它们目前包含带有SVG,CSS和JS的HTML。

I'm generating a large number of D3 graphs programmatically. They currently consist of HTML with SVG, CSS, and JS.

我想以编程方式将这些图形导出为纯SVG。我无法弄清楚如何做到这一点。

I would like to export these graphs to plain SVG programmatically. I'm having trouble figuring out how to do this.

我发现的最接近的解决方案是:将JavaScript生成的SVG转换为文件 - 但问题是,我需要以编程方式,而不是使用工具,如Chrome开发工具或SVG撬杠,需要手动点击/保存。

The closest solution I found is this: Convert JavaScript-generated SVG to a file -- but the problem is that I need to do it programmatically, rather than by using a tool like Chrome Developer Tools or SVG Crowbar which requires manual clicking/saving.

我更喜欢使用Python,但在这一点上我可以使用任何工具/编程语言。

I'd prefer to use Python, but at this point I am open to any tools/programming language.

推荐答案

这里是我会做的:


  1. 下载并安装< =http://phantomjs.org/ =noreferrer> phantomjs ,这是一个无头的webkit浏览器,您可以从命令行运行并通过脚本自动化。

  1. Download and install phantomjs, which is a headless webkit browser you can run from the command line and automate via scripts.

将此javascript另存为renderHTML.js:

Save this javascript as renderHTML.js:

var args = require('system').args,
    page = require('webpage').create(),
    url = args[1];

page.onConsoleMessage = function (msg) {
    console.log(msg);
};

page.onLoadFinished = function() {
    page.evaluate(function() {
        console.log(document.documentElement.outerHTML);
    });
    phantom.exit();
};

page.open(url);


  • 使用上述脚本指定要呈现的网址,运行phantomjs,如下:

  • Run phantomjs with the above script specifying the url to render, like so:

    phantomjs renderHTML.js {urltorender} > {localfiletosave}
    


  • 您现在拥有指定网址的文档的整个HTML内容,包括通过JavaScript(直到页面加载)在本地文件中完成的动态内容修改。

  • You now have the entire HTML content of the document at the specified URL, including dynamic content modifications done via javascript (until page load) in a local file. Post process the local file to meet your requirements using whatever language you like.

    如果您在储存前需要进一步进行JavaScript修改,该文件,可以使用phantomjs api在调用console.log之前调度和/或等待事件。只需在步骤2中修改脚本。

    If you need further javascript modifications before saving the file, you can use the phantomjs api to dispatch and/or wait for events before calling console.log. Just modify the script in step 2.

    如果你碰巧知道并喜欢javascript,你可以跳过第4步,将你所想到的任何后处理直接放入该脚本在步骤2.

    If you happen to know and like javascript, you can skip step 4 and put whatever "post processing" you have in mind directly into the script in step 2.

    这篇关于以编程方式将D3.js图形导出为静态SVG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆