Javascript 如何使用 highcharts 在服务器上保存图表的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8802528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:34:31  来源:igfitidea点击:

How to save an image of the chart on the server with highcharts?

javascriptimagehighcharts

提问by Benjamin Crouzier

With highcharts, you have a built-in button to download the current chart (example: http://www.highcharts.com/demo/, this button: arrow). You can save it as PNG, JPEG, PDF or SVG.

使用 highcharts,您有一个用于下载当前图表的内置按钮(例如:http://www.highcharts.com/demo/,该按钮:箭)。您可以将其另存为 PNG、JPEG、PDF 或 SVG。

What I'd like to do is to create a link that saves the image on the server, instead of downloading it. How could I do that ?

我想要做的是创建一个链接,将图像保存在服务器上,而不是下载它。我怎么能那样做?

I suppose that I have to modify the exportChartfunction in the exporting.src.js file. It looks like this (but I don't know javascript enough to do that) :

我想我必须修改exportChartexporting.src.js 文件中的函数。它看起来像这样(但我对 javascript 的了解不足以做到这一点):

exportChart: function (options, chartOptions) {
        var form,
            chart = this,
            svg = chart.getSVG(chartOptions);

        // merge the options
        options = merge(chart.options.exporting, options);

        // create the form
        form = createElement('form', {
            method: 'post',
            action: options.url
        }, {
            display: NONE
        }, doc.body);

        // add the values
        each(['filename', 'type', 'width', 'svg'], function (name) {
            createElement('input', {
                type: HIDDEN,
                name: name,
                value: {
                    filename: options.filename || 'chart',
                    type: options.type,
                    width: options.width,
                    svg: svg
                }[name]
            }, null, form);
        });

        // submit
        form.submit();

        // clean up
        discardElement(form);
    },

回答by gakhov

It could be done really easy with PhantomJS. You can render Highchartchart and save it to SVG, PNG, JPEG or PDF. The example below renders a demo Highchartsdiagram to SVG and PDF at the same time:

使用PhantomJS. 您可以渲染Highchart图表并将其保存为 SVG、PNG、JPEG 或 PDF。下面的示例将演示Highcharts图同时呈现为 SVG 和 PDF:

var system = require('system');
var page = require('webpage').create();
var fs = require('fs');

// load JS libraries
page.injectJs("js/jquery.min.js");
page.injectJs("js/highcharts/highcharts.js");
page.injectJs("js/highcharts/exporting.js");

// chart demo
var args = {
    width: 600,
    height: 500
};

var svg = page.evaluate(function(opt){
    $('body').prepend('<div id="container"></div>');

    var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            width: opt.width,
            height: opt.height
        },
        exporting: {
            enabled: false
        },
        title: {
            text: 'Combination chart'
        },
        xAxis: {
            categories: ['Apples', 'Oranges', 'Pears', 'Bananas', 'Plums']
        },
        yAxis: {
            title: {
                text: 'Y-values'
            }
        },
        labels: {
            items: [{
                html: 'Total fruit consumption',
                style: {
                    left: '40px',
                    top: '8px',
                    color: 'black'
                }
            }]
        },
        plotOptions: {
            line: {
                dataLabels: {
                    enabled: true
                },
                enableMouseTracking: false
            },
            series: {
                enableMouseTracking: false, 
                shadow: false, 
                animation: false
            }
        },
        series: [{
            type: 'column',
            name: 'Andrii',
            data: [3, 2, 1, 3, 4]
        }, {
            type: 'column',
            name: 'Fabian',
            data: [2, 3, 5, 7, 6]
        }, {
            type: 'column',
            name: 'Joan',
            data: [4, 3, 3, 9, 0]
        }, {
            type: 'spline',
            name: 'Average',
            data: [3, 2.67, 3, 6.33, 3.33],
            marker: {
                lineWidth: 2,
                lineColor: 'white'
            }
        }, {
            type: 'pie',
            name: 'Total consumption',
            data: [{
                name: 'Andrii',
                y: 13,
                color: '#4572A7'
            }, {
                name: 'Fabian',
                y: 23,
                color: '#AA4643'
            }, {
                name: 'Joan',
                y: 19,
                color: '#89A54E'
            }],
            center: [100, 80],
            size: 100,
            showInLegend: false,
            dataLabels: {
                enabled: false
            }
        }]
    });

    return chart.getSVG();
},  args);

// Saving SVG to a file
fs.write("demo.svg", svg);
// Saving diagram as PDF
page.render('demo.pdf');

phantom.exit();

If you save the code as demo.js, then just run bin/phantomjs demo.jsto generate demo.svgand demo.pdf

如果将代码另存为demo.js,则只需运行bin/phantomjs demo.js即可生成demo.svgdemo.pdf

回答by Anna

I just implement this using Nobita's method. I was creating a survey that showed the user's results in a chart, uploaded the image to my server and then sent out an email with the image in it. Here's a few things to note.

我只是使用大雄的方法来实现这一点。我正在创建一个调查,在图表中显示用户的结果,将图像上传到我的服务器,然后发送一封包含图像的电子邮件。这里有几点需要注意。

I had to make a few updates to the highcharts/exporting-server/index.php file which are the following:

我不得不对 highcharts/exporting-server/index.php 文件进行一些更新,如下所示:

I changed the directory from "temp" to something else and just note that it is in 4 different locations.

我将目录从“temp”更改为其他内容,只需注意它位于 4 个不同的位置。

I had to change shell_exec() adding "-XX:MaxHeapSize=256m" because it was giving me an error:

我不得不更改 shell_exec() 添加“-XX:MaxHeapSize=256m”,因为它给了我一个错误:

$output = shell_exec("java -XX:MaxHeapSize=256m -jar ". BATIK_PATH ." $typeString -d $outfile $width /mypathhere/results/$tempName.svg");

If you want it to download that image you can leave the following alone:

如果您希望它下载该图像,您可以单独保留以下内容:

header("Content-Disposition: attachment; filename=$filename.$ext");
header("Content-Type: $type");
echo file_get_contents($outfile);

But, I changed this because I wanted to send back the path to the image, so I deleted the above and replace this with the image path (Note that I'm just using the temporary name.):

但是,我改变了这一点,因为我想发回图像的路径,所以我删除了上面的内容并将其替换为图像路径(请注意,我只是使用了临时名称。):

echo "/mypathhere/results/$tempName.$ext";

Also, this file is deleting the svg file and also the new file you made. You need to remove the code that deletes the file:

此外,此文件正在删除 svg 文件以及您制作的新文件。您需要删除删除文件的代码:

unlink($outfile);

And you can also delete the line before it if you want to keep the svg file.

如果你想保留 svg 文件,你也可以删除它之前的行。

Make sure to include highcharts/js/modules/exporting.js

确保包含 highcharts/js/modules/exporting.js

Then, in your JS you can do something like the following:

然后,在您的 JS 中,您可以执行以下操作:

var chart = new Highcharts.Chart();    
var imageURL = '';
var svg = chart.getSVG();
var dataString = 'type=image/jpeg&filename=results&width=500&svg='+svg;
$.ajax({
    type: 'POST',
    data: dataString,
    url: '/src/js/highcharts/exporting-server/',
    async: false,
    success: function(data){
        imageURL = data;
    }
});

The URL you are posting to is the new version of the /exporting-server/index.php. Then, you can use the imageURL however you like.

您发布到的 URL 是 /exporting-server/index.php 的新版本。然后,您可以随意使用 imageURL。

回答by Nobita

I haven't done that before, but I believe you want to play with the index.phpfile located in the exporting-serverfolder. By default Highcharts provides (for free) a web service but you can modify that and create your own web service for exporting, or do whatever you want with the chart. Look at these instructions which can be found here Export module:

我以前没有这样做过,但我相信您想使用index.php位于exporting-server文件夹中的文件。默认情况下,Highcharts 提供(免费)Web 服务,但您可以修改它并创建自己的 Web 服务以进行导出,或者对图表执行任何您想要的操作。查看这些说明,可以在此处找到导出模块

"If you want to set up this web service on your own server, the index.php file that handles the POST is supplied in the download package inside the /exporting-server directory.

“如果你想在你自己的服务器上设置这个 web 服务,处理 POST 的 index.php 文件在 /exporting-server 目录中的下载包中提供。

  1. Make sure that PHP and Java is installed on your server.
  2. Upload the index.php file from the /exporting-server directory in the download package to your server.
  3. In your FTP program, create directory called temp in the same directory as index.php and chmod this new directory to 777 (Linux/Unix servers only).
  4. Download Batik from http://xmlgraphics.apache.org/batik/#download. Find the binary distribution for your version of jre
  5. Upload batik-rasterizer.jar and the entire lib directory to a location on your web server. In the options in the top of the index.php file, set the path to batik-rasterier.jar.
  6. In your chart options, set the exporting.url option to match your PHP file location. "
  1. 确保您的服务器上安装了 PHP 和 Java。
  2. 将下载包中 /exporting-server 目录下的 index.php 文件上传到您的服务器。
  3. 在您的 FTP 程序中,在与 index.php 相同的目录中创建名为 temp 的目录,并将这个新目录 chmod 为 777(仅限 Linux/Unix 服务器)。
  4. http://xmlgraphics.apache.org/batik/#download下载蜡染。查找您的 jre 版本的二进制分发版
  5. 将 batik-rasterizer.jar 和整个 lib 目录上传到您的 Web 服务器上的某个位置。在 index.php 文件顶部的选项中,将路径设置为 batik-rasterier.jar。
  6. 在您的图表选项中,设置 exporting.url 选项以匹配您的 PHP 文件位置。”

回答by Prashobh

You can try this

你可以试试这个

 var chart = $('#yourchart').highcharts();
    svg = chart.getSVG();   
    var base_image = new Image();
    svg = "data:image/svg+xml,"+svg;
    base_image.src = svg;
    $('#mock').attr('src', svg);

Take html of Mock and send to DB or save only the binary code .

将 Mock 的 html 发送到 DB 或仅保存二进制代码。

Save highchart as binary image

将 highchart 保存为二进制图像