当前位置:  编程技术>.net/c#/asp.net

Winform实现将网页生成图片的方法

    来源: 互联网  发布时间:2014-11-04

    本文导语:  通常浏览器都有将网页生成图片的功能,本文实例讲述了Winform实现将网页生成图片的方法。分享给大家供大家参考。具体方法如下: 工具截图如下: 生成后的图片如下: 手动填写网站地址,可选择图片类型和保持图片地址...

通常浏览器都有将网页生成图片的功能,本文实例讲述了Winform实现将网页生成图片的方法。分享给大家供大家参考。具体方法如下:

工具截图如下:

生成后的图片如下:

手动填写网站地址,可选择图片类型和保持图片地址,来生成页面的图片,当图片路径未选择时则保存桌面;

具体代码如下:

将html生成图片的类

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Drawing.Imaging; 
using System.Runtime.InteropServices; 
using System.Security;
namespace Print
{
  public class Test
  {
    public static Bitmap GetHtmlImage(Uri UrlString, int Width)
    {
      WebBrowser MyControl = new WebBrowser();
      MyControl.Size = new Size(Width, 10);
      MyControl.Url = UrlString;
      while (MyControl.ReadyState != WebBrowserReadyState.Complete)
      {
        Application.DoEvents();
      }
      MyControl.Height = MyControl.Document.Body.ScrollRectangle.Height + 20;
      MyControl.Url = UrlString;
      WebControlImage.Snapshot snap = new WebControlImage.Snapshot();
      Bitmap MyImage = snap.TakeSnapshot(MyControl.ActiveXInstance, new Rectangle(0, 0, MyControl.Width, MyControl.Height));
      MyControl.Dispose();
      return MyImage;
    }
    /// 
    /// WebBrowser获取图形 
    /// 
    private class WebControlImage
    {
      internal static class NativeMethods
      {
        [StructLayout(LayoutKind.Sequential)]
        public sealed class tagDVTARGETDEVICE
        {
          [MarshalAs(UnmanagedType.U4)]
          public int tdSize;
          [MarshalAs(UnmanagedType.U2)]
          public short tdDriverNameOffset;
          [MarshalAs(UnmanagedType.U2)]
          public short tdDeviceNameOffset;
          [MarshalAs(UnmanagedType.U2)]
          public short tdPortNameOffset;
          [MarshalAs(UnmanagedType.U2)]
          public short tdExtDevmodeOffset;
        }
        [StructLayout(LayoutKind.Sequential)]
        public class COMRECT
        {
          public int left;
          public int top;
          public int right;
          public int bottom;
          public COMRECT()
          {
          }
          public COMRECT(Rectangle r)
          {
            this.left = r.X;
            this.top = r.Y;
            this.right = r.Right;
            this.bottom = r.Bottom;
          }
          public COMRECT(int left, int top, int right, int bottom)
          {
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
          }
          public static NativeMethods.COMRECT FromXYWH(int x, int y, int width, int height)
          {
            return new NativeMethods.COMRECT(x, y, x + width, y + height);
          }
          public override string ToString()
          {
            return string.Concat(new object[] { "Left = ", this.left, " Top ", this.top, " Right = ", this.right, " Bottom = ", this.bottom });
          }
        }
        [StructLayout(LayoutKind.Sequential)]
        public sealed class tagLOGPALETTE
        {
          [MarshalAs(UnmanagedType.U2)]
          public short palVersion;
          [MarshalAs(UnmanagedType.U2)]
          public short palNumEntries;
        }
      }
      public class Snapshot
      {
        /// 
        /// ?煺? 
        /// 
        /// Com 对象 
        /// 图象大小 
        /// 
        public Bitmap TakeSnapshot(object pUnknown, Rectangle bmpRect)
        {
          if (pUnknown == null)
            return null;
          //必须为com对象 
          if (!Marshal.IsComObject(pUnknown))
            return null;
          //IViewObject 接口 
          UnsafeNativeMethods.IViewObject ViewObject = null;
          IntPtr pViewObject = IntPtr.Zero;
          //内存图 
          Bitmap pPicture = new Bitmap(bmpRect.Width, bmpRect.Height);
          Graphics hDrawDC = Graphics.FromImage(pPicture);
          //获取接口 
          object hret = Marshal.QueryInterface(Marshal.GetIUnknownForObject(pUnknown),
          ref UnsafeNativeMethods.IID_IViewObject, out pViewObject);
          try
          {
            ViewObject = Marshal.GetTypedObjectForIUnknown(pViewObject, typeof(UnsafeNativeMethods.IViewObject)) as UnsafeNativeMethods.IViewObject;
            //调用Draw方法 
            ViewObject.Draw((int)System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT,
            -1,
            IntPtr.Zero,
            null,
            IntPtr.Zero,
            hDrawDC.GetHdc(),
            new NativeMethods.COMRECT(bmpRect),
            null,
            IntPtr.Zero,
            0);
          }
          catch (Exception ex)
          {
            Console.WriteLine(ex.Message);
            throw ex;
          }
          //释放 
          hDrawDC.Dispose();
          return pPicture;
        }
      }
      [SuppressUnmanagedCodeSecurity]
      internal static class UnsafeNativeMethods
      {
        public static Guid IID_IViewObject = new Guid("{0000010d-0000-0000-C000-000000000046}");
        [ComImport, Guid("0000010d-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IViewObject
        {
          [PreserveSig]
          int Draw([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [In] NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [In] NativeMethods.COMRECT lprcBounds, [In] NativeMethods.COMRECT lprcWBounds, IntPtr pfnContinue, [In] int dwContinue);
          [PreserveSig]
          int GetColorSet([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [In] NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hicTargetDev, [Out] NativeMethods.tagLOGPALETTE 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)] System.Runtime.InteropServices.ComTypes.IAdviseSink pAdvSink);
          void GetAdvise([In, Out, MarshalAs(UnmanagedType.LPArray)] int[] paspects, [In, Out, MarshalAs(UnmanagedType.LPArray)] int[] advf, [In, Out, MarshalAs(UnmanagedType.LPArray)] System.Runtime.InteropServices.ComTypes.IAdviseSink[] pAdvSink);
        }
      }
    }
  }
}

winfrom后台处理方面代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace Excel文件处理
{
  public partial class Html : Form
  {
    public Html()
    {
      InitializeComponent();
    }
    private string ImageUrl = "";//图片地址
    private string ImageName = "";//图片名称
    private void button1_Click(object sender, EventArgs e)
    {
      string HtmlUrl = this.Txt_Url.Text.Trim(); 
      if (HtmlUrl=="")
      {
        MessageBox.Show("请输入网址");
        return;
      } 
      if (ImageUrl.Trim()=="")
      { 
        ImageUrl = @"C:UsersAdministratorDesktop";  
      }
      try
      {
        Uri ri = new Uri(this.Txt_Url.Text);
        Bitmap bit = Print.Test.GetHtmlImage(ri, 1200);
        ImageName = this.Txt_Name.Text.Trim();//图片名称
        if (ImageName != "")
        {
          if (ImageName.IndexOf('.') != -1)
          {//当用户输入图片后缀时,将后缀截取
            ImageName.Substring(0, ImageName.LastIndexOf('.'));
          }
        }
        else
          ImageName = DateTime.Now.Ticks.ToString();//时间名称
        switch (this.comboBox1.SelectedText)
        {
          case "GIF": ImageUrl += "\" + ImageName + ".gif"; break;
          case "JPG": ImageUrl += "\" + ImageName + ".jpg"; break;
          case "PNG": ImageUrl += "\" + ImageName + ".png"; break;
          default: ImageUrl += "\" + ImageName + ".png"; break;
        }

        switch (this.comboBox1.SelectedText)
        {
          case "GIF": bit.Save(ImageUrl, ImageFormat.Gif); break;
          case "JPG": bit.Save(ImageUrl, ImageFormat.Jpeg); break;
          case "PNG": bit.Save(ImageUrl, ImageFormat.Png); break;
          default: bit.Save(ImageUrl, ImageFormat.Png); break;
        }

        bit = null;
        ImageUrl = "";//图片地址
        ImageName = "";//图片名称
        MessageBox.Show("生产成功");
      }
      catch
      {
        MessageBox.Show("网址输入有误!");
        return;
      }
    }

    private void button2_Click(object sender, EventArgs e)
    { 
      //获取保存路径
      if (this.folderBrowserDialog1.ShowDialog()==DialogResult.OK)
      {
        if (this.folderBrowserDialog1.SelectedPath.Trim()!="")
        {
          ImageUrl = folderBrowserDialog1.SelectedPath;
          this.label6.Text = ImageUrl;
        }
      }
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。


    
 
 

您可能感兴趣的文章:

  • WinForm拖拽控件生成副本的解决方法
  • Winform实现抓取web页面内容的方法
  • WinForm实现关闭按钮不可用或隐藏的方法
  • WinForm实现读取Resource中文件的方法
  • C# Winform 整个窗口拖动的实现代码
  • c# winform 关闭窗体时同时结束线程实现思路
  • C#中禁止Winform窗体关闭的实现方法
  • C# winform编程中响应回车键的实现代码
  • c# 天气预报查询(winform方法)的实现代码(图文)
  • C#实现WinForm捕获最小化事件的方法
  • c#实现DataGridView控件隔行变色(winform)的代码
  • WinForm实现移除控件某个事件的方法
  • winform下实现win7 Aero磨砂效果实现代码
  • C# Winform实现捕获窗体最小化、最大化、关闭按钮事件的方法
  • WinForm实现同时让两个窗体有激活效果的特效实例
  • C# Winform 操作 INI 配置文件的实现代码
  • WinForm子窗体访问父窗体控件的实现方法
  • C# WinForm中Panel实现用鼠标操作滚动条的实例方法
  • WinForm特效之桌面上的遮罩层实现方法
  • c# winForm 窗口跳转后即关闭上一个窗口的实现代码
  • C# WinForm实现Win7 Aero透明效果代码
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • c#多线程更新窗口(winform)GUI的数据
  • .Net WInform开发笔记(二)Winform程序运行结构图及TCP协议在Winform中的应用
  • C# WinForm中禁止改变窗口大小的方法
  • WinForm相对路径的陷阱
  • c# Winform 全窗口拖动的代码
  • 解读在C#中winform程序响应键盘事件的详解
  • WinForm下 TextBox只允许输入数字的小例子
  • Winform跨线程操作的简单方法
  • C# WinForm程序完全退出的问题解决
  • C# WinForm窗体编程中处理数字的正确操作方法
  • C# Winform 让整个窗口都可以拖动
  • 使用C# Winform应用程序获取网页源文件的解决方法
  • C# Winform 禁止用户调整ListView的列宽
  • C# WinForm编程获取文件物理路径的方法
  • C# winform treeview添加右键菜单并选中节点的方法
  • C# Winform调用WEB Service API的示例代码
  • WinForm DataGridView控件隔行变色的小例子
  • IT科技资讯 iis7站长之家
  • WinForm窗体调用WCF服务窗体卡死问题
  • C#中Winform窗体Form的关闭按钮变灰色的方法
  • C#中使用IrisSkin2.dll美化WinForm程序界面的方法


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3