最近有个需求,需要把内容生成图片,我找到一些资料可以将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. 查看laravel版本

    方法1: 使用php artisan --version ,只要能看懂这个命令的人一定已经具有初步的Laravel知识.再介绍一种不需要命令,直接去文件中去查看的方法. 方法2: 在项目文件中找ven ...

  2. Codeforces Beta Round #4 (Div. 2 Only) D. Mysterious Present(LIS)

    传送门 题意: 现在我们有 n 个信封,然后我们有一张卡片,并且我们知道这张卡片的长和宽. 现给出这 n 个信封的长和宽,我们想形成一个链,这条链的长度就是这条链中所含有的信封的数量: 但是需要满足① ...

  3. 中和IOS七层架构和TCP/IP四层架构的五层架构

    五层架构分别为应用层.运输层.网络层.数据链路层.物理层. IOS架构把应用层又细分为应用层.表示层.会话层 TCP/IP把网络层改名网际层,数据链路层和物理层结合成网络接口层 其实只要学习五层协议, ...

  4. linux PCI 接口

    尽管许多计算机用户认为 PCI 是一种电路布线方法, 实际上它是一套完整的规格, 定义 了一个计算机的不同部分应当如何交互. PCI 规范涉及和计算机接口相关的大部分问题. 我们不会在这里涵盖全部; ...

  5. Vue学习笔记-目录结构

    1.采用脚手架构建的项目基本目录结构 可能会有些许差别,但是大致基本目录都差不多 2.项目入口(index.html,main.js,App.vue) 一般情况下,我们都习惯性将 index.html ...

  6. slim中的请求头

    请求头 每个 HTTP 请求都有请求头.这些元数据描述了 HTTP 请求,但在请求体中不可见.Slim 的 PSR 7 请求对象提供了几个检查请求头的方法. 获取所有的请求头,返回一个数组:getHe ...

  7. 25.python之面向对象

    一 三大编程范式 正本清源一:有人说,函数式编程就是用函数编程--->傻逼 编程范式即编程的方法论,标识一种编程风格 大家学习了基本的python语法后,大家就可以写python代码了,然后每个 ...

  8. .data()与.detach()的区别

    .data()和.detach()都可以获取Variable内部的Tensor,但.detach()更加安全 https://zhuanlan.zhihu.com/p/38475183

  9. Kubernetes从私有镜像仓库中拉取镜像

    当我们尝试从私有仓库中拉取镜像时,可能会收到这样提示:requested access to the resource is denied Error response from daemon: pu ...

  10. 深入JVM(二)JVM概述

    深入JVM(一)JVM指令手册 深入JVM(二)JVM概述 一.JVM的原理 Java虚拟机是Java平台的基石,解决了硬件和操作系统的相互独立性.不同平台(Windows,Linux和MacOS)的 ...