【问题标题】:Render web page to picture将网页渲染为图片
【发布时间】:2011-02-04 09:52:57
【问题描述】:

我有带有 URL 的字符串。例如“http://google.com”。

有没有什么方法可以下载这个页面并将其渲染为图片文件? ("test.jpg")

我尝试使用 WebBrowser 控件来下载和渲染图片,但它仅在 WebBrowser 以显示形式放置时才有效。在其他方面,它只渲染黑色矩形。

但我想渲染没有任何视觉效果的图片(创建、激活表单等)

【问题讨论】:

    标签: c# .net browser


    【解决方案1】:

    Internet Explorer 支持 IHtmlElementRenderer 接口,可用于将页面呈现到任意设备上下文。这是一个示例表单,向您展示如何使用它。从 Project + Add Reference 开始,选择 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);
        }
      }
    }
    

    【讨论】:

    • 这可以在非可视环境中使用吗,例如,在 Windows 服务器上的服务中以缩略图 html 页面?
    • 我不明白为什么不这样做,您不必将 WebBrowser 放在表单上以使其可用。
    • 但是,WebBrowser 需要一个 STA 线程和一个消息循环。您必须使用 Application.Run() 创建一个。
    • 这是一个旧答案,界面成为使用 GPU 加速的现代 IE 版本的牺牲品。
    【解决方案2】:

    不幸的是,MS 不赞成在 IE 9 中使用 IHtmlElementRenderer::DrawToDC()。 http://msdn.microsoft.com/en-us/library/aa752273(v=vs.85).aspx

    【讨论】:

      猜你喜欢
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      相关资源
      最近更新 更多