IE瀏覽器整頁截屏程式(二)

來源:互聯網
上載者:User

 

在上一篇隨筆中,大家給出了不少建議,尤其是指出了截屏方法的不足之處。其實,使用上述方法去截屏也是逼不得已,因為公司實際項目需求中,還有其他一些要求,在此不便細說。如果僅僅為了截屏,我推薦大家直接用WebBrowser控制項來實現,非常簡單。

 

實現步驟如下:

(1)建立一個Form應用程式,在表單上添加一個Panel,假設Name為panel1,設定:panel1.AutoScroll=true。

(2)在panel1中放置一個WebBrowser控制項,假設Name為webBrowser1,設定:webBrowser1.ScriptErrorsSuppressed = true;(禁止彈出指令碼錯誤框)

(3)註冊webBrowser1.DocumentCompleted事件,當頁面載入完畢後,將webBrowser1的大小設定為和頁面一樣大。這是最關鍵的地方,否則就只能截取可見部分了。

(4)最後,調用webBrowser1.DrawToBitmap方法,將頁面畫到Bitmap上,然後儲存為圖片檔案。

 

C#原始碼如下:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace WebBrowserTest{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            webBrowser1.Navigate(textBox1.Text);        }        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)        {            if (e.Url.Equals(textBox1.Text))            {//這裡比較麻煩,有些網站並不滿足這個條件:webBrowser1.ReadyState == WebBrowserReadyState.Complete                //將WebBrowser控制項設定為和頁面一樣大(這步很關鍵,否則只能截取到可見部分)                Size rc = webBrowser1.Document.Body.ScrollRectangle.Size;                webBrowser1.Width = rc.Width + SystemInformation.VerticalScrollBarWidth;                webBrowser1.Height = rc.Height + SystemInformation.HorizontalScrollBarHeight;                //將頁面畫到一個畫布上,然後另存新檔圖片                using (Bitmap bitmap = new Bitmap(webBrowser1.Width, webBrowser1.Height))                {                    webBrowser1.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));                    bitmap.Save(@"d:\capture.png");                }                MessageBox.Show("OK");            }        }    }}

【總結】

使用WebBrowser控制項也有不足之處,比方說:

1、DocumentCompleted狀態判斷不穩定;

2、快顯視窗不好過濾。

3、必須依賴Form視窗。

此外,WebBrowser控制項是基於IE核心的,也有的朋友採用的是基於WebKit核心的瀏覽器組件,用起來也挺方便的。歡迎大家繼續指正。

 

最後給出sina.com.cn的首頁,看看效果(圖片太大,壓縮了一下,所以有點模糊):

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.