服务器端d3 - 将SVG编码为Base64映像 [英] Server Side d3 - Encoding SVG as a Base64 Image

查看:66
本文介绍了服务器端d3 - 将SVG编码为Base64映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将D3图表编码为用于HTML电子邮件的base64图像

I'm trying to encode a D3 chart as a base64 image for use in HTML emails

到目前为止,我有:

var express = require('express');
var app = express();
var jsdom = require('jsdom');

app.get('/chart', function (request, response) {
    try {
        jsdom.env(
            "<html><body><svg id=\"svg\"></svg></body></html>",
            ['http://d3js.org/d3.v3.min.js'],
            function (err, window) {
                var svg = window.d3.select("svg")
                    .attr("width", 100)
                    .attr("height", 100);

                svg.append("rect")
                    .attr("x", 10)
                    .attr("y", 10)
                    .attr("width", 80)
                    .attr("height", 80)
                    .style("fill", "orange");

                var encoded = ...; // How do I now encode this?

                response.send({
                    "html": window.d3.select("body").html(),
                    "encoded": encoded
                });
            }
        );
    } catch (err) {
        console.error(err);
    }
});

// Run Server
var port = process.env.PORT || 8305;
var server = app.listen(port, function () {
    var host = server.address().address;
    console.log('App listening at http://%s:%s', host, port);
});

这会输出SVG html,但是我还想要第二个响应字段 encoded ,其中应包含以下内容,我可以在我的HTML电子邮件中使用:

This outputs the SVG html which is useful however I would also like a second response field encoded which should contain something like below that I can use in my HTML email:

"encoded": "data:image/png;base64,iVBORw0KGgoAAAANSUhEU...etc"

我如何编码这个SVG?如果可能的话,我想避免任何文件写入,直接从SVG到编码图像。此外,我知道您可以在电子邮件中使用SVG,但我更倾向于使用编码图像格式。谢谢!

How do I encode this SVG? I would like to avoid any file writing if possible and go straight from SVG to encoded image. Also, I'm aware you can use SVGs in emails but I would much rather it be in an encoded image format. Thanks!

推荐答案

使用NodeJS构建d3图表并将其转换为编码PNG而不使用文件存储的完整解决方案(必要的大多数云托管)

Full solution which builds a d3 chart using NodeJS and converts it to an encoded PNG without using file storage (neccessary for most cloud hosting)

let express = require('express');
let app = express();

let jsdom = require('jsdom');
let Buffer = require('buffer').Buffer;
let svg2png = require('svg2png');

app.post('/chart', function (request, response) {
    try {
        jsdom.env(
            "<svg id=\"svg\"></svg>",
            ['http://d3js.org/d3.v3.min.js'],
            function (err, window) {
                let svg = window.d3.select("svg")
                    .attr("width", 100)
                    .attr("height", 100)
                    .attr("xmlns", "http://www.w3.org/2000/svg");

                svg.append("rect")
                    .attr("x", 10)
                    .attr("y", 10)
                    .attr("width", 80)
                    .attr("height", 80)
                    .style("fill", "orange");

                let data = "data:image/png;base64,";
                let svgString = svg[0][0].outerHTML;
                let buffer = new Buffer("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + svgString);
                let promise = svg2png(buffer, {width: 300, height: 400}); // This options block is optional but height and width should be specified on the SVG HTML otherwise
                promise.then(buffer => {
                    let dataURI = data + buffer.toString('base64');
                    response.set('Content-Type', 'application/json');
                    response.send({
                        "html": svgString,
                        "encoded": dataURI
                    });
                });
            }
        );
    } catch (err) {
        console.warn(err);
    }
});

// Run Server
let port = process.env.PORT || 8305;
let server = app.listen(port, function () {
    let host = server.address().address || 'localhost';
    console.log('Example app listening at http://%s:%s', host, port);
});

响应中的编码字段可以是在HTML电子邮件中使用:

The encoded field in the response can be used in a HTML email using:

<img src="{encoded-value}"/>

例如

<img src="data:image/png;base64,iVBORw0KGgoAAA..."/>

这篇关于服务器端d3 - 将SVG编码为Base64映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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