asp.net 生成word,处理图片,富文本框内容图片处理


//基本导出方法
public
void Download() { Random rd = new Random(); string fileName = DateTime.Now.ToString("yyyyMMddhhmm") + rd.Next() + ".doc"; //存储路径 string path = Server.MapPath(fileName); //创建字符输出流 StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8); //需要导出的内容 // string str = "<html><head><title>无标题文档</title></head><body>这里放从数据库导出的word文档内容</body></html>"; string str = ""; str += "<html><head><title>无标题文档</title></head><body>"; str += "<div>阅读报表</div>"; str += "<table border='1'><tr>"; str += "<td>20000</td>"; str += "<td>10000</td></tr><tr>"; str += "<td>30000</td>"; str += "<td>30000</td><tr>"; str += "</table></body></html>"; //写入 sw.Write(str); sw.Close(); Response.Clear(); Response.Buffer = true; this.EnableViewState = false; Response.Charset = "utf-8"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.ContentType = "application/octet-stream"; Response.WriteFile(path); Response.Flush(); Response.Close(); Response.End(); }

 //图片处理方法 图片转字节 base64 放到img src 中 如 <img src="data:image/jpeg;base64,ImgToBase64String(string Imagefilename)) /> 
private string ImgToBase64String(string Imagefilename) { string result = ""; try { using (FileStream fs = new FileStream(Imagefilename,FileMode.Open,FileAccess.Read)) { byte[] byteArray = new byte[fs.Length]; fs.Read(byteArray, 0, byteArray.Length); result = Convert.ToBase64String(byteArray); } } catch { result = ""; } return result; }
 /// <summary>
        /// 富文本框 内容里面的 图片处理
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string ContentHandler(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            HtmlDocument document = new HtmlDocument();
            document.LoadHtml(text);
            var imgNodes = document.DocumentNode.SelectNodes("//img");
            if (imgNodes != null)
            {
                Parallel.ForEach(imgNodes, imgNode =>
                {
                    var src = imgNode.GetAttributeValue("src", "");
                    if (!string.IsNullOrEmpty(src))
                    {
                        var filename = context.Server.MapPath(src);
                        if (File.Exists(filename))
                        {
                            imgNode.SetAttributeValue("src", "data:image/jpeg;base64," + ImgToBase64String(filename));

                        }
                    }
                });
            }

            return document.DocumentNode.OuterHtml;

        }

 

posted @ 2021-12-01 09:02  紫寻落  阅读(187)  评论(0编辑  收藏  举报