Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render web page to picture

Tags:

browser

c#

.net

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

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

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.)

like image 882
Steck Avatar asked Apr 05 '10 11:04

Steck


2 Answers

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);
    }
  }
}
like image 144
Hans Passant Avatar answered Sep 21 '22 11:09

Hans Passant


Unfortunately, MS deprecated use of IHtmlElementRenderer::DrawToDC() in IE 9. http://msdn.microsoft.com/en-us/library/aa752273(v=vs.85).aspx

like image 45
mixmix Avatar answered Sep 21 '22 11:09

mixmix