渲染网页图片网页、图片

2023-09-03 06:56:14 作者:自作多情的思念叫作犯贱

我的字符串URL。例如,http://google.com。

I have the string with URL. For example "http://google.com".

时有什么办法可以下载和显示此页到图片文件? (test.jpg放在)

Is there are any way to download and render this page to picture file? ("test.jpg")

我试图使用WebBrowser控件,下载和渲染的画面,但只有当web浏览器放置于显示形式的作品。在其他方面,它是呈现只有黑色矩形。

I tried to use WebBrowser control, to download and render picture, but it only works when WebBrowser placed in displayed form. In other ways it's render only black rectangle.

但我想呈现的画面没有任何的视觉效果(创建,激活表单等)

But i want to render picture without any visual effect (creating, activating form etc.)

推荐答案

Internet Explorer支持的IHtmlElementRenderer接口,可用来呈现一个页面到任意设备上下文。下面是一个示例的形式,展示了如何使用它。先从项目+添加引用,选择Microsoft.mshtml

Internet Explorer supports the IHtmlElementRenderer interface, available to render a page to an arbitrary device context. Here's a sample form that shows you how to use it. Start with Project + Add Reference, select Microsoft.mshtml

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1 {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      webBrowser1.Url = new Uri("http://stackoverflow.com");
      webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
    }

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
      if (!e.Url.Equals(webBrowser1.Url)) return;
      // Get the renderer for the document body
      mshtml.IHTMLDocument2 doc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
      mshtml.IHTMLElement body = (mshtml.IHTMLElement)doc.body;
      IHTMLElementRender render = (IHTMLElementRender)body;
      // Render to bitmap
      using (Bitmap bmp = new Bitmap(webBrowser1.ClientSize.Width, webBrowser1.ClientSize.Height)) {
        using (Graphics gr = Graphics.FromImage(bmp)) {
          IntPtr hdc = gr.GetHdc();
          render.DrawToDC(hdc);
          gr.ReleaseHdc();
        }
        bmp.Save("test.png");
        System.Diagnostics.Process.Start("test.png");
      }
    }

    // Replacement for mshtml imported interface, Tlbimp.exe generates wrong signatures
    [ComImport, InterfaceType((short)1), Guid("3050F669-98B5-11CF-BB82-00AA00BDCE0B")]
    private interface IHTMLElementRender {
      void DrawToDC(IntPtr hdc);
      void SetDocumentPrinter(string bstrPrinterName, IntPtr hdc);
    }
  }
}