经过各方面的资源查询和不懈的研究,困扰本人一个多星期的问题终于解决。
先上效果图
添加一些文本和图片
点击确认提交,将内容添加到word并下载
打开
提示、警告:
一开始找到使用 Aspose.Word 来实现,就是这个
别去用,我研究了三四天,不知道是个人问题还是,最后个人觉得两字:rubbish!
来吧,上代码:
我使用的是wangEditor 这个富文本编辑器,强烈推荐。
https://www.wangeditor.com/doc/
官方网站,进去之后。开始使用-基本使用。点击地址,另存为下载。
将 wangEditor.min.js 添加到content文件夹下
视图代码:
<head>
<script src="~/Content/wangEditor.min.js"></script>
<script src="~/Content/jquery-3.5.1.min.js"></script>
</head>
@using (Html.BeginForm("ExportWord", "WangEditor", FormMethod.Post))
{
<div id="div1" style="margin-top:50px;">
<p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
<textarea id="text1" name="text1" style="width:100%; height:200px;display: none;"></textarea>
<input type="submit" value="确认提交">
}
<!-- 引入 wangEditor.min.js -->
<script type="text/javascript">
const E = window.wangEditor
const editor = new E('#div1')
const $text1 = $('#text1')
editor.config.onchange = function (html) {
//监控变化,同步更新到 textarea
$text1.val(html)
}
editor.config.showLinkImg = false //隐藏上传网络图片功能
editor.config.uploadImgShowBase64 = true
editor.config.uploadImgMaxSize = 20 * 1024 * 1024 //上传图片的最大大小 20M
//editor.config.height = 500 //设置编辑框的高度
editor.create()
//初始化 textarea 的值
$text1.val(editor.txt.html())
</script>
控制器代码:
自己添加好相应的引用
public class WangEditorController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// 获取Html字符串中指定标签的指定属性的值
/// </summary>
/// <param name="html">Html字符</param>
/// <param name="tag">指定标签名</param>
/// <param name="attr">指定属性名</param>
/// <returns></returns>
private List<string> GetHtmlAttr(string html, string tag, string attr)
{
Regex re = new Regex(@"(<" + tag + @"[\w\W].+?>)");
MatchCollection imgreg = re.Matches(html);
List<string> m_Attributes = new List<string>();
Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);
for (int i = 0; i < imgreg.Count; i++)
{
MatchCollection matchs = attrReg.Matches(imgreg[i].ToString());
for (int j = 0; j < matchs.Count; j++)
{
GroupCollection groups = matchs[j].Groups;
if (attr.ToUpper() == groups[1].Value.ToUpper())
{
m_Attributes.Add(groups[3].Value);
break;
}
}
}
return m_Attributes;
}
[ValidateInput(false)]
[HttpPost]
public FileResult ExportWord(string text1)
{
StringBuilder sb = new StringBuilder();
sb.Append("<!DOCTYPE html>");
sb.Append("<body>");
//将text1中的img转换为图片绝对地址 之前为 base64 存储。如果直接输出到word,会是一个大红叉。
//需要将base64 存储的格式解析,存储到本地,然后将text1中的图片格式替换为本地。
List<string> result = GetHtmlAttr(text1, "img", "src");
int j = 1;
foreach (var item in result)
{
string temp = item;
int index = item.IndexOf("base64");
string value = item.Substring(index + 7);
string address = Injpg(string.Format("text{0}", j), value);
text1 = text1.Replace(temp, address);
j++;
}
//
sb.Append(text1);
sb.Append("</body>");
var byteArray = System.Text.Encoding.Default.GetBytes(sb.ToString());
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
return File(byteArray, "application/ms-word", "wordtest" + ".doc");
}
public string Injpg(string name, string base64str)
{
string data = base64str;
byte[] arr = Convert.FromBase64String(data);
using (MemoryStream ms = new MemoryStream(arr))
{
Bitmap bmp = new Bitmap(ms);
string p = string.Format("/temp_img/{0}.jpg", name);//temp_img为自己在根目录下新建的一个文件夹
var w = Server.MapPath(p);
bmp.Save(w, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Close();
return w;
}
}
}
图片路径未替换前:
这种一长串的
替换后:
就是这么强大,烦恼!