C# 实现HTML转换成图片的方法


//调用委托来实现。返回值在定时器完成后才有用,比较难接收。C# <wbr>实现HTML转换成图片的方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices.ComTypes;

namespace FormatApplication.CommonClass
{
    /// <summary>
    /// 对HTML进行图片转换。
    /// </summary>
    public class ConvertHTML
    {
        private ConvertHTML() { }
        /// <summary>
        /// 图片保存路径。
        /// </summary>
        private static string SAVEHTMLIMAGE = string.Empty;

        /// <summary>
        /// 把网页转换成图片形式。
        /// </summary>
        /// <param name="htmlPath"></param>
        /// <returns></returns>
        public static void HTMLConvertImage(string htmlPath)
        {
            SAVEHTMLIMAGE = string.Empty;
            HtmlCapture hcap = new HtmlCapture();
            hcap.HtmlImageCapture += new HtmlCapture.HtmlCaptureEvent(hcap_HtmlImageCapture);
            hcap.Create(htmlPath);
        }

        static void hcap_HtmlImageCapture(object sender, Uri url, Bitmap image)
        {
            SAVEHTMLIMAGE = @"E:\cheng_Text\FormatApplication\测试文件\ConvertHTML.jpg";
            image.Save(SAVEHTMLIMAGE);
            image.Dispose();
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static string ProduceImagePath()
        {

            return SAVEHTMLIMAGE;
        }
    }

    #region==========IViewObje【实现接口类】================
    [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);
    }
    #endregion

    #region=============HtmlCapture【HTML抓图片方法实现】===============
    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 += new
              WebBrowserDocumentCompletedEventHandler(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();
            //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);

        }
        #endregion
    }
    #endregion
}
----------------------------------------------------------------------------------------------

//另一种用同步上,在上一个方法上修改。C# <wbr>实现HTML转换成图片的方法。C# <wbr>实现HTML转换成图片的方法。C# <wbr>实现HTML转换成图片的方法。

 /// <summary>
        /// 通过WebBrowser控件来实现从HTML到Bmp图片的生成。
        /// </summary>
        /// <param name="htmPath">HTML路径</param>
        /// <returns>Bmp图片路径</returns>
        private static string ConverHTML(string htmPath)
        {
            string ImagePath = string.Empty;
            WebBrowser web = new WebBrowser();
            web.Navigate(htmPath);
            while (web.ReadyState != WebBrowserReadyState.Complete)
            {
                System.Windows.Forms.Application.DoEvents();
            }
            Rectangle screen = Screen.PrimaryScreen.Bounds;
            Size? imgsize = null;
            //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;
            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 - 24, 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);
            }
            SAVEWORDJPG = string.Format(@"E:\cheng_Text\FormatApplication\测试文件\{0}.bmp", Guid.NewGuid().ToString());
            bitmap.Save(SAVEWORDJPG, System.Drawing.Imaging.ImageFormat.Bmp);
            bitmap.Dispose();
            web.Dispose();
            DeleteTempFile(TEMPHTMLPATH);
            return SAVEWORDJPG;
        }

        /// <summary>
        /// 删除指定的临时文件。
        /// </summary>
        /// <param name="filePath"></param>
        private static void DeleteTempFile(string filePath)
        {
            //删除临时HTML文件 。
            File.Delete(filePath);
            //删除目录文件内容。
            string[] files = filePath.Split('.');
            if (files[1].ToLower().Equals("htm"))
            {
                string dirPath = files[0] + ".files";
                foreach (string f in Directory.GetFileSystemEntries(dirPath))
                {
                    // 如果是文件存在 
                    if (File.Exists(f))
                    {
                        FileInfo fi = new FileInfo(f);
                        if (fi.Attributes.ToString().IndexOf("Readonly") != 1)
                        {
                            fi.Attributes = FileAttributes.Normal;
                        }
                        // 直接删除其中的文件 
                        File.Delete(f);
                    }
                }
                Directory.Delete(dirPath);
            }
        }

        #region==========IViewObje【实现接口类】================
        [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);
        }
        #endregion


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM