C# html生成图片保存下载

最近有个需求,需要把内容生成图片,我找到一些资料可以将html页面生成图片并保存下载

下面是简单的实现

1.html页面

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @if (ViewBag.type == 0)
        {
            <input type="button" value="保存" id="btnD" onclick="down()" />
        }

        <table>
            <tr>
                <th>Id</th>
                <th>姓名</th>
                <th>年龄</th>
            </tr>
            @foreach (var item in ViewBag.list)
            {
                <tr>
                    <td>@item.Id</td>
                    <td>@item.Name</td>
                    <td>@item.Age</td>
                </tr>
            }
        </table>
    </div>
    <script src="~/Scripts/jquery-3.3.1.js"></script>
    <script>
        function down() {
            $.ajax({
                url: "/test/GetfileName",
                type: "get",
                success: function (json) {
                    window.location.href = '/test/DownImg?fileName=' + json;
                }
            })

        }
    </script>
</body>
</html>

2.控制器

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Content;
using System.IO;

namespace WebApplication2.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index(int type=0)
        {
            List<Student> list = new List<Student>();
            for (int i = 0; i < 10; i++)
            {
                Student stu = new Student();
                stu.Id = 1 + 1;
                stu.Name = "张三"+i.ToString();
                stu.Age = 20 + i;
                list.Add(stu);
            }
            ViewBag.list = list;
            ViewBag.type = type;
            return View();
        }
        public string GetfileName()
        {
        //调用 Bitmap m_Bitmap
= WebSnapshotsHelper.GetWebSiteThumbnail("http://localhost:64806/Test/Index?type=1", 800, 1200, 800, 1200); //宽高根据要获取快照的网页决定 var path = Server.MapPath("/Content/img/"); if (!Directory.Exists(path)) Directory.CreateDirectory(path); var fileName =Guid.NewGuid()+ ".jpeg"; m_Bitmap.Save(path + fileName, System.Drawing.Imaging.ImageFormat.Jpeg); //图片格式可以自由控制 return fileName; } public ActionResult DownImg(string fileName) { var path = Server.MapPath("/Content/img/")+ fileName; return File(path, "image/jpeg", fileName); } } public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } }

3.新建类 WebSnapshotsHelper  我是b/s做的,所以需要引用  System.Windows.Forms

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Web;
using System.Windows.Forms;

namespace WebApplication2.Content
{
    public class WebSnapshotsHelper
    {
        Bitmap m_Bitmap;
        string m_Url;
        int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;
        public WebSnapshotsHelper(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
        {
            m_Url = Url;
            m_BrowserHeight = BrowserHeight;
            m_BrowserWidth = BrowserWidth;
            m_ThumbnailWidth = ThumbnailWidth;
            m_ThumbnailHeight = ThumbnailHeight;
        }
        public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
        {
            WebSnapshotsHelper thumbnailGenerator = new WebSnapshotsHelper(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
            return thumbnailGenerator.GenerateWebSiteThumbnailImage();
        }
        public Bitmap GenerateWebSiteThumbnailImage()
        {
            Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();
            m_thread.Join();
            return m_Bitmap;
        }
        private void _GenerateWebSiteThumbnailImage()
        {
            WebBrowser m_WebBrowser = new WebBrowser();

            //## 这边把脚本错误的压制设置为true.
            m_WebBrowser.ScriptErrorsSuppressed = true;

            m_WebBrowser.ScrollBarsEnabled = false;
            m_WebBrowser.Navigate(m_Url);
            m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();
            m_WebBrowser.Dispose();
        }
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser m_WebBrowser = (WebBrowser)sender;
            m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);

            // 设置文档窗口错误的处理。    
            m_WebBrowser.Document.Window.Error += OnWebBrowserDocumentWindowError;
        }

        /// <summary>
        /// 对WEB浏览器处理错误的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWebBrowserDocumentWindowError(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }
    }
}

生成结果 

原文地址:https://www.cnblogs.com/LiChen19951127/p/10936837.html