用 ASP.NET 做網站截圖(程式碼範例)

來源:互聯網
上載者:User

一、添加引用

在解決方案上單擊右鍵,選擇“Add Reference...”,添加“System.Windows.Forms”,添加完後,Web.Config 中應該有類似下面的內容:

<system.web>
  <compilation debug="true">
    <assemblies>
      <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

二、 設定 STA 模式

在 @ Page 指令中加上 AspCompat="true",以強制該網頁在 STA(單一執行緒 Apartment) 模式下執行。結果類似如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" AspCompat="true" %>

三、寫代碼

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
 
public partial class _Default : System.Web.UI.Page
{
    private WebBrowser _webBrowser;
   
   
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = Request.QueryString["url"];
        if (string.IsNullOrEmpty(url))
        {
            url = "http://www.cftea.com/";
        }
       
        _webBrowser = new WebBrowser();
        _webBrowser.ScrollBarsEnabled = false; //不顯示捲軸
        _webBrowser.Navigate(url);
        _webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Completed);
       
        while (_webBrowser.ReadyState != WebBrowserReadyState.Complete)
        {
            System.Windows.Forms.Application.DoEvents(); //避免假死,若去掉則可能無法觸發 DocumentCompleted 事件。
        }
    }
   
   
    public void Completed(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        //設定瀏覽器寬度、高度為文檔寬度、高度,以便截取整個網頁。
        _webBrowser.Width = _webBrowser.Document.Body.ScrollRectangle.Width;
        _webBrowser.Height = _webBrowser.Document.Body.ScrollRectangle.Height;
        using (Bitmap bmp = new Bitmap(_webBrowser.Width, _webBrowser.Height))
        {
            _webBrowser.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
            bmp.Save("C:\\Capture.png", ImageFormat.Png);
        }
    }
}

四、說明

在調試時,若出錯,應該停止 ASP.NET Development Server,重新運行,如果你用的是 IIS,可能需要重新啟動 IIS(猜測是這樣),否則 Navigate 那句會出錯。

有些網站抓下來是空白,還沒有仔細研究過為什麼。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.