2012-02-03 118 views
0

我是一名asp.net軟件培訓生。將div標籤的內容轉換爲圖像格式

這是我的div標籤。現在

<div id="contentsDiv"> 
    <b>Write some thing</b> 
    <br/><br> 
    <img alt="Koala" src="Images/Koala.jpg" width="400" height="400" /> 
    <br< /><br> 
    <i>Some thing means any thing </i> 
</div> 



<asp:Button ID="Export" runat="server" Text="Export" onclick="Export_Click" /> 

,出口點擊按鈕,我想標籤的內容轉換爲圖像並保存在特定文件夾中的形象。

回答

1

爲HTML內容轉換爲圖像的東西不是很容易..但我認爲你可以做到這一點

class Program 
    { 
     [STAThread] 
     static void Main(string[] args) 
     { 

      var bmp = MakeScreenshot(@"<div><h1>Hello World</h1></div>"); 

      bmp.Save(@"c:\pdf\test.jpg"); 
     } 


     public static Bitmap MakeScreenshot(string html) 
     { 
      // Load the webpage into a WebBrowser control 
      WebBrowser wb = new WebBrowser(); 
      wb.Navigate("about:blank"); 
      if (wb.Document != null) 
      { 

       wb.Document.Write(html); 

      } 

      wb.DocumentText = html; 

      wb.ScrollBarsEnabled = true; 
      wb.ScriptErrorsSuppressed = true; 
      //  wb.Navigate(this.Uri); 
      while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } 


      // Set the size of the WebBrowser control 
       // Take Screenshot of the web pages full width 
       wb.Width = wb.Document.Body.ScrollRectangle.Width; 
       // Take Screenshot of the web pages full height 
       wb.Height = wb.Document.Body.ScrollRectangle.Height; 

      if (wb.Height <= 0) 
      { 
       wb.Height = 768; 
      } 

      // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control 
      Bitmap bitmap = new Bitmap(wb.Width, wb.Height); 
      wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); 
      wb.Dispose(); 

      return bitmap; 
     } 
    } 
+0

它顯示了一些錯誤,請告訴我在哪個文件中這個代碼必須寫入ie.fileName.aspx.cs或fileName.cs – Jumbo 2012-02-06 10:47:09

+0

它在.net framework 3.5控制檯應用程序中的代碼 – 2012-02-06 17:59:22

0

請給我們介紹一下你的web應用和目標想才達到一些更多的細節。您可能是指客戶端導出,但我無法100%確定。

如果是這種情況,可以將此div繪製到畫布元素中,然後使用HTMLCanvasElement對象的toDataURL來允許用戶通過瀏覽器的「封閉」div內容進行保存。

var c = document.getElementById('the_canvas_element_id'); 
var t = c.getContext('2d'); 

當用戶點擊 「導出」,這樣做:在Canvas tutorial

window.open('', document.getElementById('the_canvas_element_id').toDataURL()); 

更多信息和this blog

它是一個軟件見習:)相當艱鉅的任務。