1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace TCP 11 { 12 public partial class Form1 : Form 13 { 14 public Form1() 15 { 16 InitializeComponent(); 17 } 18 WebBrowser webBrowser = null; 19 public void ConvertToImg() 20 { 21 //string html = "<div><table border = \"1\" cellspacing = \"0\" cellpadding = \"3\" style = \"text-align:center;\"><tr><th style = \"width:60px;\">字段1</th><th style = \"width:60px;\">字段2</th><th style = \"width:60px;\">字段3</th></tr><tr style = \"color:green;\"><td>小明</td><td>22</td><td>185</td></tr><tr style = \"color:red;\"><td>小青</td><td>21</td><td>170</td></tr></table></div>"; 22 23 webBrowser = new WebBrowser(); 24 25 //是否显式滚动条 26 webBrowser.ScrollBarsEnabled = false; 27 28 //加载 html 29 webBrowser.Navigate("http://www.baidu.com"); 30 31 //页面加载完成执行事件 32 webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted); 33 } 34 35 private void webBrowser_DocumentCompleted(object sender, EventArgs e)//这个就是当网页载入完毕后要进行的操作 36 { 37 //获取解析后HTML的大小 38 System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle; 39 int width = rectangle.Width; 40 int height = rectangle.Height; 41 42 //设置解析后HTML的可视区域 43 webBrowser.Width = width; 44 webBrowser.Height = height; 45 46 Bitmap bitmap = new System.Drawing.Bitmap(width, height); 47 webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, width, height)); 48 49 //设置图片文件保存路径和图片格式,格式可以自定义 50 string filePath = AppDomain.CurrentDomain.BaseDirectory + "Img\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png"; 51 bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); 52 } 53 54 private void button1_Click(object sender, EventArgs e) 55 { 56 ConvertToImg(); 57 } 58 } 59 60 }
原文地址:https://www.cnblogs.com/bibuba/p/8797875.html
时间: 2024-11-10 00:13:20