html转word 文档 doc docx

在做项目时,要将富文本编辑器,或是html内容 导出为word。

先引入文件保存js

<script src="FileSaver.js"></script>

方法一

使用 html-docx.js、FileSaver.js 文件

导出为Docx
docx体积更小,而且word2007也可以打开

1.引用插件html-docx.js

<script src="html-docx.js"></script>

2.构建完整的html内容文档

var content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ 要导出的html信息 +'</html>

content要导出的html信息,建议在服务端自己拼接完成。

若是想从页面抓取html信息,可以用下面的方法(不建议,客户端消耗高)

html:

<div id="content">
    要导出的html信息
    <img src="xxx">
</div>
 
function convertImagesToBase64 (content) {
      var regularImages = content.querySelectorAll("img");
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      [].forEach.call(regularImages, function (imgElement) {
        // preparing canvas for drawing
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        canvas.width = imgElement.width;
        canvas.height = imgElement.height;
 
        ctx.drawImage(imgElement, 0, 0);
        // by default toDataURL() produces png image, but you can also export to jpeg
        // checkout function's documentation for more details
        var dataURL = canvas.toDataURL();
        imgElement.setAttribute('src', dataURL);
      })
      canvas.remove();
    }
var content = document.getElementById('#content');
convertImagesToBase64(content);//转换图片为base64
 
content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ content +'</html>'

3.利用脚本导出word

 var converted = htmlDocx.asBlob(content);
 saveAs(converted, 'test.docx');// 用 FielSaver.js里的保存方法 进行输出

方法二

导出为Doc

使用 html-docx.js、FileSaver.js 、wordexport文件

1.引入jquery和wordexport

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="wordexport.js"></script>

2.使用导出

$(元素).wordExport(文件名,isBase64)

isBase64 用于标识 元素中的图片是否都处理为了base64,默认为false,内置处理方法,可以去看看

注意

无论是html-docx.js还是 wordexport.js 都需要将html中的图片转为base64形式

而且,图片的宽度高,最好自己设置下,否则下载的图片会以图片原始大小下载,就会出现以下,图片在文档超出情况

处理图片的宽高,可以采用 正则替换,这里给出两种替换参考(平时不太写正则,所以有点挫)

C#:

string reg = "<img.*? src=[\"'](.*?)['\"].*?>";
MatchCollection collections = Regex.Matches(description, reg);
if (collections.Count > 0)
{
    foreach (Match match in collections)
    {
        Regex regWidth = new Regex("width\\s*=\\s*\\S+ ");
        if (!regWidth.IsMatch(img))//img 中不存在width 
        {
            //获取其他属性进行替换
            Regex reg1 = new Regex(@"style\s*=(['""\s]?)[^'""]*?\1"); ;
            img = reg1.Replace(img, "width=\"350\" height=\"216\" ");//按黄金比例替换
        }
        else
        {
            Match mathWidth = regWidth.Match(img);
            if (mathWidth.Success)
            {
                string widh = mathWidth.Value.Substring(7).Substring(0, mathWidth.Value.Substring(7).Length - 2);//width
                if (int.Parse(widh) > 400) {//原宽超出400
                    Regex regHeight = new Regex(@"height\s*=(['""\s]?)[^'""]*?\1");
                    Match mathHeight = regHeight.Match(img);
                    if (mathHeight.Success)
                    {
                        string height = mathHeight.Value.Substring(8).Substring(0, mathHeight.Value.Substring(8).Length - 1);
                        img = regHeight.Replace(img, "height=\" " + 350 * int.Parse(height) / int.Parse(widh) + "\"");//按比例替换 高
                    }
                    img = regWidth.Replace(img, "width=\"350\"");
                }
            }
        }
    }
}

若是二进制流存储的图片数据,可以通过Bitmp来读取原始大小 ,然后按照原始比例再进行缩放

 
 
//通过二进制流 获取图片原始宽高
private int[] GetScaleImgSizeByByte(byte[] image)
{
    MemoryStream stream = new MemoryStream(image);//内存流写入
    Bitmap bmp = new Bitmap(stream);
    int width = 600;//先指定一个固定大小 和word页面边距最大宽差不多
    int height = 600;
    if (bmp.Width > 600)
    {
        height = (int)(width * ((double)bmp.Height / (double)bmp.Width));
    }
    if (height > 600 || bmp.Height > 600)
    {//调完宽后判断高 
        height = 600;
        width = (int)(height / ((double)bmp.Height / (double)bmp.Width));
    }
    return new int[] { width, height };
}

js正则替换:

 var str = htmlText.replace(/(<img[^>]*)(\/?>)/gi, function (match, capture) {
     if(match.match(/width\s*?=\s*?([‘"])[\s\S]*?\1/ig)==null)
     match = match.replace(/(<img[^>]*)(\/?>)/gi,"$1 width='350' $2")//没有宽就增加宽
     return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, '').replace(/width\s*?=\s*?([‘"])[\s\S]*?\1/ig ,"width='350'");
});

方式三   使用poi 

经过调研使用各种方式之后发现这种方法应该是对样式复杂的报告是最切合的
提供poi封装脚手架函数 Poi-tl Documentation

猜你喜欢

转载自blog.csdn.net/qq_34316431/article/details/118566173