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=& ...
随机推荐
- 2019-10-24-dotnet-列表-Linq-的-Take-用法
title author date CreateTime categories dotnet 列表 Linq 的 Take 用法 lindexi 2019-10-24 9:4:23 +0800 201 ...
- python基础十一之装饰器进阶
函数的双下划线方法 def hahahha(): """测试函数""" print('zxc') print(hahahha.__name_ ...
- P1025 最大完美度
题目描述 定义一个字符串的完美度为字符串中所有字符的完美度的和. 现在给你一个只含字母的字符串s, 每一个字母的完美度由你进行分配, 可以分配给一个字母[1,26]中的一个数字作为完美度, 但每个字母 ...
- H3C 因特网域名结构树
- 2019-3-1-获取-Nuget-版本号
title author date CreateTime categories 获取 Nuget 版本号 lindexi 2019-3-1 9:27:6 +0800 2019-02-25 15:51: ...
- linux I/O 端口分配
如同你可能希望的, 你不应当离开并开始抨击 I/O 端口而没有首先确认你对这些端口有 唯一的权限. 内核提供了一个注册接口以允许你的驱动来声明它需要的端口. 这个接口中 的核心的函数是 request ...
- 2018.11.25 齐鲁工业大学ACM-ICPC迎新赛正式赛题解
整理人:周翔 A 约数个数(难) 解法1:苗学林 解法2:刘少瑞 解法3:刘凯 解法4:董海峥 B Alice And Bob(易) 解法1:周翔 解法2:苗学林 解法3:刘少瑞 C 黑白 ...
- 使用 koa-router 路由拆分
根据功能不同,将路由拆分到不同的模块 目录结构: app.js const Koa = require('koa'); const Router = require('koa-router'); co ...
- k8s生产环境部署
建议配置: 服务器 900G*2 SSD 安装操作系统 CPU 16核心*2 40G网卡*2 RAM 64G*8 操作系统建议:Centos7.4/Centos 7.6 不建议使用CentOS8 分布 ...
- Strongly Connected Tournament
题解: 有一个很重要的性质就是 对于一张完全强联通图来说 一定有一个强联通分量入度为0(或者出度为0) 然后就一些计数题的基本套路 https://www.cnblogs.com/onioncyc/p ...