偷天換日讓Silverlight支持圖表轉圖片
作者:Clingingboy
Silverlight不支持打印,不支持將元素轉圖片,所以很麻煩。所以采取一種取巧的做法。目前我們用VisifireChart來作為圖表呈現(xiàn),這個開源軟件同時支持Silverlight和WPF,Silverlight不能辦到的事情,但WPF可以。
所以實現(xiàn)圖表轉圖片可以分一下幾步走.
一.寫一份WPF客戶端程序
思路很簡單
1.1定義一個定時器,然后檢測某目錄的xml文件,這里暫定目錄名字為chart
- timer = new DispatcherTimer();
- timer.Interval = new TimeSpan(0, 0, 2);
- timer.Tick += new EventHandler(timer_Tick);
- timer.Start();
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- }
- }
1.2如果有的話,則進行反序列化成Chart對象進行呈現(xiàn)
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- LoadXml(files[0]);
- }
- }
- private void LoadXml(string xmlFile)
- {
- XmlDocument doc = new XmlDocument();
- doc.Load(xmlFile);
- StringReader stringReader = new StringReader(doc.InnerXml);
- XmlReader xmlReader = XmlReader.Create(stringReader);
- Chart chart = XamlReader.Load(xmlReader) as Chart;
- chart.AnimationEnabled = false;
- stringReader.Close();
- xmlReader.Close();
- this.Content=chart;
- }
1.3呈現(xiàn)好以后進行截圖
- void timer_Tick(object sender, EventArgs e)
- {
- string[] files = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "chart");
- if (files.Length > 0)
- {
- LoadXml(files[0]);
- PrintPicture(files[0]);
- }
- }
- private void PrintPicture(string fileName)
- {
- this.Dispatcher.BeginInvoke(new Action(() =>
- {
- int Height = (int)this.ActualHeight;
- int Width = (int)this.ActualWidth;
- RenderTargetBitmap bmp = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32);
- bmp.Render(this);
- string file = "C:\\temp\\a.jpg";
- BitmapEncoder encoder;
- encoder = new JpegBitmapEncoder();
- encoder.Frames.Add(BitmapFrame.Create(bmp));
- using (Stream stm = File.Create(file))
- {
- encoder.Save(stm);
- }
- File.Delete(fileName);
- }), System.Windows.Threading.DispatcherPriority.Render);
- }
1.4轉換成圖片完畢則刪除此xml文件
二.將編譯好的wpf程序放置在web根目錄,然后啟動此程序
三.使用ajax交互將當前顯示出來的xml傳送到chart目錄下
前端
- $.ajax({
- type: "POST",
- url: "ajaxServer.aspx",
- data: "name=" + vChart.dataUri,
- success: function(msg) {
- alert("Success");
- }
- });
后端
拷貝xml文件或者其他處理方式把xml弄到chart目錄下
- protected void Page_Load(object sender, EventArgs e)
- {
- File.Copy(Server.MapPath(this.Request["name"]), Server.MapPath("../chart/" + this.Request["name"]));
- }
注意點:轉換的時候注意wpf和silverlight的命名空間.也算是一個方法,對付圖表生成圖片是綽綽有余的.小技巧分享一下
【編輯推薦】
責任編輯:彭凡
來源:
cnblogs