html页面转成word文档

博客提及了FileSaver.js和jquery.wordexport.js。FileSaver.js在大部分CDN上可搜到,未贴代码;还提到了jquery.wordexport.js,但未作更多说明。
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../lib/jquery3.4.0.js"></script>
    <script src="../lib/FileSaver.js"></script>
    <script src="../lib/jquery.wordexport.js"></script>
</head>
<body>
<div id="content" class="content">
    <h1>
        这是一个word测试
    </h1>
    <h2>
        这是一个word测试
    </h2>
    <h3>
        这是一个word测试
    </h3>
    <h4>
        这是一个word测试
    </h4>
    <h5>
        这是一个word测试
    </h5>
    <table>
        <thead>
           <tr>
               <td>第一列</td>
               <td>第二列</td>
               <td>第三列</td>
           </tr>
        </thead>
        <tbody>
            <tr>
                <td>11</td>
                <td>12</td>
                <td>13</td>
            </tr>
            <tr>
                <td>21</td>
                <td>22</td>
                <td>23</td>
            </tr>
            <tr>
                <td>31</td>
                <td>32</td>
                <td>33</td>
            </tr>
            <tr>
                <td>41</td>
                <td>42</td>
                <td>43</td>
            </tr>
            <tr>
                <td>51</td>
                <td>52</td>
                <td>53</td>
            </tr>
        </tbody>
    </table>
</div>



<script>
    htmlToWord($("#content"),"test01");
    function htmlToWord(ele,name) {
        var rules = "table{border-collapse:collapse;margin:0 auto;text-align:center;width: 100%;}table td,table th{border:1px solid #cad9ea;color:#666;height:30px}table thead th{background-color:#F1F1F1;min-width:400px}table tr{background:#fff}",
            ss = document.styleSheets;
        for(var i = 0; i < ss.length; ++i) {
            for(var x = 0; x < ss[i].cssRules.length; ++x) {
                rules += ss[i].cssRules[x].cssText;
            }
        }

        //先clone来避免影响页面显示
        var clone = ele.clone();
        //找到所有echarts图表容器
        var charts = clone.find(".chart");
        //隐藏无需导出的dom
        clone.find(".input_div").hide();
        //简单控制流程
        var flag = charts.length;
        for(var i = 0; i < charts.length; i++) {
            //获取echarts对象
            var curEchart = echarts.getInstanceByDom(charts[i]);
            if(curEchart) {
                //将图表替换为图片
                var base = curEchart.getConnectedDataURL();
                var img = $('<img style="" src="' + base + '"/>');
                $(charts[i]).html(img);
                flag--;
            } else {
                flag--;
            }
        }
        var interval = setInterval(function() {
            if(!flag) {
                clearInterval(interval);
                //导出word
                clone.wordExport(name, rules);
            }
        }, 200)
    }
</script>
</body>
</html>
  •  
  • 109

FileSaver.js

大部分cdn上都能搜到,这里就不贴代码了

jquery.wordexport.js

if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
    (function($) {
        $.fn.wordExport = function(fileName,rule) {
            fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
            var static = {
                mhtml: {
                    top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html>\n_html_</html>",
                    head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
                    body: "<body>_body_</body>"
                }
            };
            var options = {
                maxWidth: 624
            };
            // Clone selected element before manipulating it
            var markup = $(this).clone();

            // Remove hidden elements from the output
            markup.each(function() {
                var self = $(this);
                if (self.is(':hidden'))
                    self.remove();
            });

            // Embed all images using Data URLs
            var images = Array();
            var img = markup.find('img');
            for (var i = 0; i < img.length; i++) {
                // Calculate dimensions of output image
                var w = Math.min(img[i].width, options.maxWidth);
                var h = img[i].height * (w / img[i].width);
                // Create canvas for converting image to data URL
                var canvas = document.createElement("CANVAS");
                canvas.width = w;
                canvas.height = h;
                // Draw image to canvas
                var context = canvas.getContext('2d');
                context.drawImage(img[i], 0, 0, w, h);
                // Get data URL encoding of image
                var uri = canvas.toDataURL("image/png");
                $(img[i]).attr("src", img[i].src);
                img[i].width = w;
                img[i].height = h;
                // Save encoded image to array
                images[i] = {
                    type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
                    encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
                    location: $(img[i]).attr("src"),
                    data: uri.substring(uri.indexOf(",") + 1)
                };
            }

            // Prepare bottom of mhtml file with image data
            var mhtmlBottom = "\n";
            for (var i = 0; i < images.length; i++) {
                mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
                mhtmlBottom += "Content-Location: " + images[i].location + "\n";
                mhtmlBottom += "Content-Type: " + images[i].type + "\n";
                mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";
                mhtmlBottom += images[i].data + "\n\n";
            }
            mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";

            //TODO: load css from included stylesheet
            //源码将styles置为"",这里我们只需改动成传入css,赋值给styles即可;
            var styles = rule || "";
            // Aggregate parts of the file together
            var fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;
            // Create a Blob with the file contents
            var blob = new Blob([fileContent], {
                type: "application/msword;charset=utf-8"
            });
            saveAs(blob, fileName + ".doc");
        };
    })(jQuery);
} else {
    if (typeof jQuery === "undefined") {
        console.error("jQuery Word Export: missing dependency (jQuery)");
    }
    if (typeof saveAs === "undefined") {
        console.error("jQuery Word Export: missing dependency (FileSaver.js)");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值