2012-02-03 44 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

它是一个软件见习:)相当艰巨的任务。