业务很简单,就是把网页转成图片保存下来。之前也用过html2canvas来实现这一功能,测试下来除了发现截图糊了一点外倒也没什么毛病,但是这次实现完在Chrome上测试时却出现了网络错误的提示(大概是图片太大的缘故orz),于是想到走后台来实现这一功能,找了一下发现以下方案,大概就是先组装好这个页面来让WebBrowser来访问,最后把整个WebBrowser界面以字节流的方式输出给用户浏览器。具体代码如下:
protected void btnExport_Click(object sender, EventArgs e) { try { Thread thread = new Thread(new ThreadStart(ExportImageFromHtml)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); while (thread.IsAlive) System.Windows.Forms.Application.DoEvents(); } catch (Exception ex) { this.HandleException(ex); } }
public void ExportImageFromHtml() { string url = "http://ie.icoa.cn/"; Bitmap bitmap = new Bitmap(CommonWebUtil.CaptureWebPage(url)); Response.ContentType = "image/jpeg"; string fileName = lbltitle.Text.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("\"", "").Replace("<", "").Replace(">", "").Replace("|", ""); fileName += "_证书.jpg"; MemoryStream ms = new MemoryStream(); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Seek(0, SeekOrigin.Begin); byte[] bytes = ms.GetBuffer(); Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }
public static Bitmap CaptureWebPage(string URL) { //create a hidden web browser, which will navigate to the page System.Windows.Forms.WebBrowser web = new System.Windows.Forms.WebBrowser(); // we don't want scrollbars on our image web.ScrollBarsEnabled = false; // don't let any errors shine through web.ScriptErrorsSuppressed = true; // let's load up that page! web.Navigate(URL); //web.Navigate(URL, "_self", null, "User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64;Trident/7.0; rv:11.0) like Gecko"); // wait until the page is fully loaded while (web.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete) System.Windows.Forms.Application.DoEvents(); System.Threading.Thread.Sleep(1500); // allow time for page scripts to update // the appearance of the page // set the size of our web browser to be the same size as the page int width = web.Document.Body.ScrollRectangle.Width; int height = web.Document.Body.ScrollRectangle.Height; web.Width = width; web.Height = height; // a bitmap that we will draw to System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height); // draw the web browser to the bitmap web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, width, height)); return bmp; // return the bitmap for processing }
当然,采用webbrowser的方式存在着一定的弊端,因为其采用的是默认IE7的兼容视图,一开始我也陷入了死胡同,找了许多的解决方案:换webkit,修改注册表。但是后来突然发现我可以修改网页的meta标签,让其强制采用IE11进行渲染。
<meta http-equiv="x-ua-compatible" content="IE=11" />
山穷水尽疑无路,柳暗花明又一村。hhhh