我们需要将 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;
}
想看看我是否走上了正轨并且没有错过另一种方法?