数据 - 将仪表板导出到图像

时间:2015-10-26 17:07:08

标签: c# asp.net-mvc datazen-server

我们要求将Datazen信息中心报告保存到图像文件中。

报告将通过iframe托管在MVC视图中。基础报告将通过Datazen中的活动目录身份验证进行保护。

我在想我会在STA模式下启动的线程中使用WebBrowser控件。这种工作,但当我尝试查看网址时,我会看到登录屏幕,如:

http://MyServerAddress/viewer/dashboard?dashboardguid=17EF844E-DEBE-4FE5-B22E-CD6F74A9E6C9

这是我到目前为止的代码。

    public ActionResult Save()
    {
        var url = "http://MyServerAddress/viewer/dashboard?dashboardguid=17EF844E-DEBE-4FE5-B22E-CD6F74A9E6C9";

        FileContentResult result = null;
        Bitmap bitmap = null;

        var thread = new Thread(
            () =>
            {
                bitmap = ExportUrlToImage(url, 1280, 1024);
            });

        thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
        thread.Start();
        thread.Join();

        if (bitmap != null)
        {
            using (var memstream = new MemoryStream())
            {
                bitmap.Save(memstream, ImageFormat.Jpeg);
                result = this.File(memstream.GetBuffer(), "image/jpeg");
            }
        }

        return result;
    }

    private Bitmap ExportUrlToImage(string url, int width, int height)
    {
        // Load the webpage into a WebBrowser control
        WebBrowser wb = new WebBrowser();
        wb.ScrollBarsEnabled = false;
        wb.ScriptErrorsSuppressed = true;

        string hdr = "Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("username" + ":" + "password")) + System.Environment.NewLine;


        wb.Navigate(url, null, null, hdr);
        while (wb.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }

        // Set the size of the WebBrowser control
        wb.Width = width;
        wb.Height = height;

        Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
        wb.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, wb.Width, wb.Height));
        wb.Dispose();

        return bitmap;
    }

想看看我是否正在走上正轨并没有错过另一种方法?

1 个答案:

答案 0 :(得分:0)

最后,我们决定使用以下客户端库Html2Canvas

需要注意CORS问题,因此请确保Datazen iframe托管在与您的网页相同的服务器/端口等上。

渲染整个页面时出现问题(即父页面和iframe内容),因此我最终只导出了iframe内容。

$(document).ready(function () {

        $("#btnSave").click(function () {
            // just render the body of the datazen iframe 
            var body = $("#iframe").contents().find('body');
            html2canvas(body, {
                allowTaint: true,
                onrendered: function (canvas) {
                    // canvas is the final rendered <canvas> element
                    var myImage = canvas.toDataURL("image/png");
                    window.open(myImage);
                }
            })
        });