最近有个需求,需要把内容生成图片,我找到一些资料可以将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 == )
{
<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=)
{
List<Student> list = new List<Student>();
for (int i = ; i < ; i++)
{
Student stu = new Student();
stu.Id = + ;
stu.Name = "张三"+i.ToString();
stu.Age = + 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;
}
}
}

生成结果

C# html生成图片保存下载的更多相关文章

  1. 微信小程序导出当前画布指定区域的内容并生成图片保存到本地相册(canvas)

    最近在学小程序,在把当前画布指定区域的内容导出并生成图片保存到本地这个知识点上踩坑了. 这里用到的方法是: wx.canvasToTempFilePath(),该方法作用是把当前画布指定区域的内容导出 ...

  2. yum 保存下载的rpm 包

    yum 保存下载的rpm 包 1 [root@bogon pluginconf.d]# vim /etc/yum.conf [main]cachedir=/var/cache/yum/$basearc ...

  3. MVC 生成图片,下载文件(图片不存在本地,在网上下载)

    /// <summary> /// 生成图片 /// </summary> /// <param name="collection"></ ...

  4. 移动端js模拟截屏生成图片并下载功能的实现方案

    一.根据PM需求如下: 移动端wap 实现将二维码生成图片下载至用户手机相册保存 二.根据现有思路: 1.使用第三方工具html2canvas,将页面中指定范围的dom转换为canvas 2.随后使用 ...

  5. vue 页面生成图片保存

    需求:将页面中的元素转成图片,支持保存或下载.要求下载的图片包含页面背景,头像,用户名,文本为"我的邀请码"和个人二维码. 实现:将页面绘制到canvas中,生成base64图片链 ...

  6. MVC 生成图片,下载文件

    /// <summary> /// 生成图片 /// </summary> /// <param name="collection"></ ...

  7. 如何模拟一个http请求并把response的内容保存下载下来,导出到excel中(结尾福利)

    def doExport(self): # 模拟一个http请求 url = u'%s?dumptype=investigation&dumpid=%s&timezone=8' % ( ...

  8. C# ASP.NET 手写板并生成图片保存

    前端: @{ Layout = null; } <!DOCTYPE html> <html lang="zh-CN"> <head> <t ...

  9. 通过JS将BSAE64生成图片并下载

    HTML:<div style="display:block;margin:0 auto;width:638px;height:795px;"><div id=& ...

随机推荐

  1. httpclient: Content-Length header already present问题

    现象:用httpclient发送http请求时,客户端返回: org.apache.http.client.ClientProtocolException at org.apache.http.imp ...

  2. java 获得Class对象

    如何得到各个字节码对应的实例对象? 每个类被加载后,系统会为该类生成对应的Class对象,通过Class对象可以访问到JVM中的这个类, 3种方式: 1.调用某个类的class属性获取Class对象, ...

  3. C# 从 short 转 byte 方法

    本文告诉大家多个方法转换 short 和 byte 有简单的也有快的 快速简单的方法 static short ToShort(short byte1, short byte2) { return ( ...

  4. SpringBoot: 浅谈文件上传和访问的坑 (MultiPartFile)

    本次的项目环境为 SpringBoot 2.0.4, JDK8.0. 服务器环境为CentOS7.0, Nginx的忘了版本. 前言 SpringBoot使用MultiPartFile接收来自表单的f ...

  5. 2018百度之星初赛B - A,D,F

    总结:这一次的百度之星之行到这里也就结束了,充分的认识到了自己的不足啊...果然还是做的题太少,,见识的题型也还太少,对于STL的掌握还是不够到位啊!!(STL大法是真的好,建议大家认认真真的好好学学 ...

  6. Java 学习笔记(6)——继承

    之前说过了Java中面向对象的第一个特征--封装,这篇来讲它的第二个特征--继承.一般在程序设计中,继承是为了减少重复代码. 继承的基本介绍 public class Child extends Pa ...

  7. Python12_关于文件概念的讨论与序列化

    文件是什么? 存储在一些设备上的信息的集合.一堆字节: ====================================================到底什么是二进制文件.和文本文件,它们有 ...

  8. JS事件之自建函数bind()与兼容性问题解决

    JavaScript事件绑定常用方法 对象.事件 = 函数; 它只能同时为一个对象的一个事件绑定一个响应函数 不能绑定多个,如果有多个,后面的会覆盖前面的 addEventListener() 此方法 ...

  9. 在Linux CentOS下如何安装tar.gz和RPM软件包

    1.安装tar.gz软件包: 在Linuxr(Centos下)如何安装tar.gz软件包,该方式实质上就是源代码安装方式,具体如下: 在Linux中使用wget命令下载要安装的文件,命令格式如下:wg ...

  10. 浅谈Redis的基本原理和数据类型结构的特性和应用开发场景

    一.Redis介绍 1,redis介绍(Redis安装在磁盘:Redis数据存储在内存) redis是一种基于键值对(key-value)数据库,其中value可以为string.hash.list. ...