C#转换HTML内容为Bitmap

话不多说,直接贴代码

绘图部分,其中html内容为一个公网链接或者本地虚拟路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public static Bitmap ConverHTML(string htmPath)
{
string ImagePath = string.Empty;
WebBrowser web = new WebBrowser();
web.Navigate(htmPath);
while (web.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
//矩形容器宽高
Rectangle screen = Screen.PrimaryScreen.Bounds;
screen.Width = (int)(screen.Width * 0.55); //自定义55%宽
screen.Height = (int)(screen.Height * 0.3); //30%高
Size? imgsize = null;
//设置宽高
web.Width = screen.Width;
web.Height = screen.Height;
web.ScriptErrorsSuppressed = true;
web.ScrollBarsEnabled = false;
Rectangle body = web.Document.Body.ScrollRectangle;

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)
};
Rectangle imgRectangle;
if (imgsize == null)
imgRectangle = docRectangle;
else
imgRectangle = new Rectangle()
{
Location = new Point(0, 0),
Size = imgsize.Value
};
Bitmap bitmap = new Bitmap(web.Width, web.Height);
IViewObject ivo = web.Document.DomDocument as IViewObject;

using (Graphics g = Graphics.FromImage(bitmap))
{
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);
}
return bitmap;
}

调用com组件用来实例化操作系统窗体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[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);
}


C#转换HTML内容为Bitmap
https://wangyuangen.github.io/2020/06/16/ConvertHtmlToBmp/
作者
Yuangen Wang
发布于
2020年6月16日
许可协议