HTML to Image in C#(C#实现Html转换为Image,即网页截图)
2012-06-26 13:15
1711 查看
原文链接地址:
http://www.codeproject.com/Articles/58605/HTML-to-Image-in-C
HTML document as an image using a
libraries, so I hope this will be useful to someone.
在这篇文章里,我将会演示如何捕获HTML文档并保存为图片,使用WebBrowser对象和
根据MSDN的描述,
在我们开始之前,。。。
我们必须做的首要事情是,我们需要定义IViewObject接口。
Below is a summary description of the parameters that the
image.
image.
As you can see, I'm using a
HTML document is fully loaded and can be captured. The reason I'm doing this is because an
HTML document can trigger the
image will be the same as the size of the
HTML document. If you want to create a thumbnail
image of the
HTML document, use
http://www.codeproject.com/Articles/58605/HTML-to-Image-in-C
Introduction
In this article, I will show you how to capture anHTML document as an image using a
WebBrowserobject and the
IViewObject.Drawmethod, which according to MSDN draws a representation of an object onto the specified device context. Before we get started, I just want to mention that the obtained results were identical to those obtained using commercial
libraries, so I hope this will be useful to someone.
在这篇文章里,我将会演示如何捕获HTML文档并保存为图片,使用WebBrowser对象和
IViewObject.Draw方法。
根据MSDN的描述,
IViewObject.Draw用户将对象的表现画到制定的设备上下文中。
在我们开始之前,。。。
The IViewObject interface
The very first thing that we must do is to define theIViewObjectinterface.
我们必须做的首要事情是,我们需要定义IViewObject接口。
ComVisible(true), ComImport()] [GuidAttribute("0000010d-0000-0000-C000-000000000046")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IViewObject { [return: MarshalAs(UnmanagedType.I4)] [PreserveSig] int Draw( [MarshalAs(UnmanagedType.U4)] UInt32 dwDrawAspect, int lindex, IntPtr pvAspect, [In] IntPtr ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [MarshalAs(UnmanagedType.Struct)] ref Rectangle lprcBounds, [MarshalAs(UnmanagedType.Struct)] ref Rectangle lprcWBounds, IntPtr pfnContinue, [MarshalAs(UnmanagedType.U4)] UInt32 dwContinue); [PreserveSig] int GetColorSet([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect,[In] IntPtr ptd, IntPtr hicTargetDev, [Out] IntPtr ppColorSet); [PreserveSig] int Freeze([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [Out] IntPtr pdwFreeze); [PreserveSig] int Unfreeze([In, MarshalAs(UnmanagedType.U4)] int dwFreeze); void SetAdvise([In, MarshalAs(UnmanagedType.U4)] int aspects, [In, MarshalAs(UnmanagedType.U4)] int advf, [In, MarshalAs(UnmanagedType.Interface)] IAdviseSink pAdvSink); void GetAdvise([In, Out, MarshalAs(UnmanagedType.LPArray)] int[] paspects, [In, Out, MarshalAs(UnmanagedType.LPArray)] int[] advf, [In, Out, MarshalAs(UnmanagedType.LPArray)] IAdviseSink[] pAdvSink); }
Below is a summary description of the parameters that the
Drawmethod takes (this is the only method we will use):
UInt32 dwDrawAspect- specifies the aspect to be drawn. Valid values are taken from the
DVASPECTand
DVASPECT2enumerations. In this example, I'm using
DVASPECT.CONTENTso the value passed is 1.
int lindex- portion of the object that is of interest for the draw operation. Currently, only -1 is supported.
IntPtr pvAspect- pointer to the additional information.
IntPtr ptd- describes the device for which the object is to be rendered. We will render for the default target device, so the value passed will be
IntPtr.Zero.
IntPtr hdcTargetDev- information context for the target device indicated by the
ptdparameter.
IntPtr hdcDraw- device context on which to draw.
ref Rectangle lprcBounds- the size of the captured
image.
ref Rectangle lprcWBounds- the region of the
WebBrowserobject that we want to be captured.
IntPtr pfnContinue- pointer to a callback function (not used here).
UInt32 dwContinue- value to pass as a parameter to the function (not used here).
The HtmlCapture class
Now that we have defined ourIViewObjectinterface, it is time to move on and create a class that will be used to capture a web page as an
image.
public class HtmlCapture
{
private WebBrowser web;
private Timer tready;
private Rectangle screen;
private Size? imgsize=null;
//an event that triggers when the html document is captured
public delegate void HtmlCaptureEvent(object sender,
Uri url, Bitmap image);
public event HtmlCaptureEvent HtmlImageCapture;
//class constructor
public HtmlCapture()
{
//initialise the webbrowser and the timer
web = new WebBrowser();
tready = new Timer();
tready.Interval = 2000;
screen = Screen.PrimaryScreen.Bounds;
//set the webbrowser width and hight
web.Width = screen.Width;
web.Height = screen.Height;
//suppress script errors and hide scroll bars
web.ScriptErrorsSuppressed = true;
web.ScrollBarsEnabled = false;
//attached events
web.Navigating +=
new WebBrowserNavigatingEventHandler(web_Navigating);
web.DocumentCompleted += newWebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
tready.Tick += new EventHandler(tready_Tick);
}
#region Public methods
public void Create(string url)
{
imgsize = null;
web.Navigate(url);
}
public void Create(string url,Size imgsz)
{
this.imgsize = imgsz;
web.Navigate(url);
}
#endregion
#region Events
void web_DocumentCompleted(object sender,WebBrowserDocumentCompletedEventArgs e)
{
//start the timer
tready.Start();
}
void web_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
//stop the timer
tready.Stop();
}
void tready_Tick(object sender, EventArgs e)
{
//stop the timer
tready.Stop();
//capture html as an image
//...
}
#endregion
}
As you can see, I'm using a
Timerobject to determine if the
HTML document is fully loaded and can be captured. The reason I'm doing this is because an
HTML document can trigger the
DocumentCompletedevent multiple times. After the document is fully loaded, the
tready_Tickmethod is called.
void tready_Tick(object sender, EventArgs e) { //stop the timer tready.Stop(); //get the size of the document's body Rectangle body = web.Document.Body.ScrollRectangle; //check if the document width/height is greater than screen width/height Rectangle docRectangle = new Rectangle() { Location=new Point(0,0), Size=new Size(body.Width > screen.Width ? body.Width : screen.Width, body.Height > screen.Height ? body.Height : screen.Height) }; //set the width and height of the WebBrowser object web.Width = docRectangle.Width; web.Height = docRectangle.Height; //if the imgsize is null, the size of the image will //be the same as the size of webbrowser object //otherwise set the image size to imgsize Rectangle imgRectangle; if (imgsize == null) imgRectangle = docRectangle; else imgRectangle = new Rectangle() { Location=new Point(0,0), Size =imgsize.Value }; //create a bitmap object Bitmap bitmap = new Bitmap(imgRectangle.Width,imgRectangle.Height); //get the viewobject of the WebBrowser IViewObject ivo = web.Document.DomDocument as IViewObject; using (Graphics g = Graphics.FromImage(bitmap)) { //get the handle to the device context and draw IntPtr hdc = g.GetHdc(); ivo.Draw(1, -1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, hdc, ref imgRectangle, ref docRectangle, IntPtr.Zero, 0); g.ReleaseHdc(hdc); } //invoke the HtmlImageCapture event HtmlImageCapture(this, web.Url, bitmap); }
Using the code
HtmlCapturehas an overloaded method named
Create. If you use the
Create(string url)method, the size of the
image will be the same as the size of the
HTML document. If you want to create a thumbnail
image of the
HTML document, use
Create(string url,Size imgsz).
private void button2_Click(object sender, EventArgs e) { HtmlCapture hc = new HtmlCapture(); hc.HtmlImageCapture += new HtmlCapture.HtmlCaptureEvent(hc_HtmlImageCapture); hc.Create("http://www.codeproject.com"); //or hc.Create("http://www.codeproject.com",new Size(200,300)); } void hc_HtmlImageCapture(object sender, Uri url, Bitmap image) { image.Save("C:/"+ url.Authority+ ".bmp"); }
相关文章推荐
- HTML to Image in C#指定网页地址,获取内容为图片
- 找到网页的某一区域,截图,并保存 HTML to Image
- HTML to image in C#
- dom-to-image实现的网页截图
- Web开发之html2canvas 实现纯JS网页截图简单例子
- html2canvas根据DOM元素样式实现网页截图
- C# 使用 wkhtmltopdf 把HTML文本或文件转换为PDF
- C#实现HTML和UBB互相转换的方法
- 网页内联图片 html inline image
- 网络采集软件核心技术剖析系列(4)---使用C#语言如何将html网页转换成pdf(html2pdf)
- 将word转换为网页(WordToHtml)
- C# 实现HTML转换成图片的方法
- C#实现的滚动网页截图功能示例
- 原生JS实现淡入淡出效果(fadeIn/fadeOut/fadeTo) (转http://www.cnblogs.com/mrthink/archive/2011/01/29/1947532.html)
- C#实现网页截图功能
- ADO.NET .net core2.0添加json文件并转化成类注入控制器使用 简单了解 iTextSharp实现HTML to PDF ASP.NET MVC 中 Autofac依赖注入DI 控制反转IOC 了解一下 C# AutoMapper 了解一下
- zhtmltopdf linux下网页截图的php扩展安装
- Converting PDF to Text in C#(转换PDF为Text)
- 移动端H5页面截图【含 domtoimage、html2canvas 】
- 禁用IE的后退按钮|显示网页已过期|几种语言的实现方法|c#|javascript|html