引用
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
代码
public class WebsiteToImage
{
private string m_Url;
private string m_FileName = string.Empty;
public WebsiteToImage(string url, string fileName)
{
m_Url = url;
m_FileName = fileName;
}
private void _Generate()
{
var browser = new WebBrowser {ScrollBarsEnabled = false};
browser.Navigate(m_Url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var browser = (WebBrowser) sender;browser.ClientSize = new Size(browser.Document.Body.ScrollRectangle.Width,browser.Document.Body.ScrollRectangle.Bottom);
browser.ScrollBarsEnabled = false;
if (browser.ReadyState == WebBrowserReadyState.Complete)
{
// 获取网页高度和宽度,也可以自己设置
int height = browser.Document.Body.ScrollRectangle.Height;
int width = browser.Document.Body.ScrollRectangle.Width;
// 调节webBrowser的高度和宽度
browser.Height = height;
browser.Width = width;
Bitmap bitmap = new Bitmap(width, height); // 创建高度和宽度与网页相同的图片
Rectangle rectangle = new Rectangle(0, 0, width, height); // 绘图区域
browser.DrawToBitmap(bitmap, rectangle); // 截图
bitmap.Save(m_FileName); // 保存图片
}
}
}
调用
static void Main(string[] args)
{
var url = "https://product.suning.com/0000000000/10398812002.html";
var fileName = $@"D:\保存网页\图片\{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png";
WebsiteToImage websiteToImage = new WebsiteToImage($"{url}",fileName);
websiteToImage.Generate();
}