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 == )
{
<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生成图片保存下载的更多相关文章
- 微信小程序导出当前画布指定区域的内容并生成图片保存到本地相册(canvas)
最近在学小程序,在把当前画布指定区域的内容导出并生成图片保存到本地这个知识点上踩坑了. 这里用到的方法是: wx.canvasToTempFilePath(),该方法作用是把当前画布指定区域的内容导出 ...
- yum 保存下载的rpm 包
yum 保存下载的rpm 包 1 [root@bogon pluginconf.d]# vim /etc/yum.conf [main]cachedir=/var/cache/yum/$basearc ...
- MVC 生成图片,下载文件(图片不存在本地,在网上下载)
/// <summary> /// 生成图片 /// </summary> /// <param name="collection"></ ...
- 移动端js模拟截屏生成图片并下载功能的实现方案
一.根据PM需求如下: 移动端wap 实现将二维码生成图片下载至用户手机相册保存 二.根据现有思路: 1.使用第三方工具html2canvas,将页面中指定范围的dom转换为canvas 2.随后使用 ...
- vue 页面生成图片保存
需求:将页面中的元素转成图片,支持保存或下载.要求下载的图片包含页面背景,头像,用户名,文本为"我的邀请码"和个人二维码. 实现:将页面绘制到canvas中,生成base64图片链 ...
- MVC 生成图片,下载文件
/// <summary> /// 生成图片 /// </summary> /// <param name="collection"></ ...
- 如何模拟一个http请求并把response的内容保存下载下来,导出到excel中(结尾福利)
def doExport(self): # 模拟一个http请求 url = u'%s?dumptype=investigation&dumpid=%s&timezone=8' % ( ...
- C# ASP.NET 手写板并生成图片保存
前端: @{ Layout = null; } <!DOCTYPE html> <html lang="zh-CN"> <head> <t ...
- 通过JS将BSAE64生成图片并下载
HTML:<div style="display:block;margin:0 auto;width:638px;height:795px;"><div id=& ...
随机推荐
- H3C 域名解析显示及维护
- CKEditor配置,最适合新手两种方式详解。
CKEditor.js的配置,大概有两种方式,这里有基础版和全面的版本可以试验 https://cdn.ckeditor.com/4.8.0/full-all/ckeditor.js http://c ...
- JavaSE基础---多线程
进程:正在进行的程序.其实就是一个应用程序运行时的内存分配空间. 线程:进程中一个程序执行控制单元,一条执行路径.进程负责的事应用程序的空间的标识,线程负责的事应用程序的执行顺序. 进程和线程的关系: ...
- SPOJ - PHRASES Relevant Phrases of Annihilation (后缀数组)
You are the King of Byteland. Your agents have just intercepted a batch of encrypted enemy messages ...
- jekyll 在博客添加流程图
本文告诉大家如何在博客使用流程图. 如果你使用的是我博客的模板,那么就可以直接使用我说的文件,如果是自己的主题,就需要在自己文件对应的地方加上代码. 在我的博客里,需要添加下面的js到博客,可以打开 ...
- (转载)MySQL慢查询日志总结
转自:https://www.cnblogs.com/kerrycode/p/5593204.html 慢查询日志概念 MySQL的慢查询日志是MySQL提供的一种日志记录,它用来记录在MySQL中响 ...
- If条件语句实战
1.If条件判断语句 通常以if开头,fi结尾.也可加入else或者elif进行多条件的判断,if表达式如下: if (表达式) 语句1 else 语句2 fi 2.If常见判断逻辑运算符详解: -f ...
- Java 学习笔记(7)——接口与多态
上一篇说了Java面向对象中的继承关系,在继承中说到:调用对象中的成员变量时,根据引用类型来决定调用谁,而调用成员方法时由于多态的存在,具体调用谁的方法需要根据new出来的对象决定,这篇主要描述的是J ...
- slim的中间件
slim中间件的作用简单来说就是过滤数据,request过来的数据要经过中间件才能到达内部,然后内部数据要到达外部的时候,也要经过中间件,正常通过才能到达外部
- Logback 学习指南 一
因为项目中用到 SpringBoot,看到官方文档中提及默认的日志实现是 logback,因此就通过阅读手册和结合实践学习了下相关的知识,记录下以备查阅. 1. logback 是什么? logbac ...