js 导出html为doc

js导出word使用了插件: jquery.wordexport.js和FileSaver.js

https://github.com/markswindoll/jQuery-Word-Export

https://github.com/eligrey/FileSaver.js/

并且依赖jquery

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bootstrap 模板</title>
  <style>
      html, div, p{
          margin: 0; 
          padding: 0;
      }
      p {
        margin: 5px 0;
        margin-left: 20px;
        line-height: 28px;
      }
     
      .export-word {
        width: 120px;
        margin: 0 auto;
        margin-top: 50px;
        text-align: center;
        padding-bottom: 100px;
      }
      .export-word button {
        width: 120px;
        height: 35px;
        line-height: 35px;
        text-align: center;
        border: 1px solid #dddddd;
      }
  </style>
</head>
<body>
  <div class="content-main" style="width: 1240px; margin: 0 auto;border: 1px dashed #ddd;font-size: 14px;">
    <div style="padding: 50px;">
      <div style="font-size: 30px; font-weight: bold;text-align: center;">试卷</div>
      <div class="question-list">
        <div style="font-weight: bold;font-size: 16px;margin-top: 50px;margin-bottom: 10px;">单选题</div>
        <div class="list-body">

          <div style="margin-bottom: 20px;">
            <div style="margin-bottom: 10px;">1.下列变化中属于化学变化的是</div>
            <div class="question-item">
              <p>A “干冰”升华</p>
              <p>B 车胎爆炸</p>
              <p>C 铁生锈</p>
              <p>D 灯泡通电发光</p>
            </div>
          </div>
          <div style="margin-bottom: 20px;">
            <div style="margin-bottom: 10px;">2.空气质量日报是环境监测部门对一个地区空气质量情况所做的监测报告。目前计入空气主要污染物的是一氧化碳、二氧化氮、二氧化硫、可吸入颗粒物和臭氧等。下列情况能直接造成空气污染的是</div>
            <div class="question-item">
              <p>A 把煤作为主要燃料</p>
              <p>B 使用含磷洗衣粉</p>
              <p>C 随意丢弃废电池</p>
              <p>D 利用太阳能、风能等清洁能源</p>
            </div>
          </div>
          

        </div>
      </div>

    </div>
  </div>

  <div class="export-word"><button>导出为word</button></div>

  <script src="/assets/aad7f4a/jquery.js"></script>
  <script src="/js/FileSaver.min.js"></script>
  <script src="/js/jquery.wordexport.js"></script>
  <script>
        $(function () {
            $(".export-word button").click(function (event) {
              var styles = ' html, div, p{margin: 0; padding: 0;} p {margin: 5px 0;margin-left: 20px;line-height: 28px;}';
              $(".content-main").wordExport("question", styles)
            });
        })
    </script>
</body>
</html>

源码是的style是需要在源码中写的,我修改了下源码

第3行:$.fn.wordExport = function(fileName) 改为 $.fn.wordExport = function(fileName, styles)

第65行: var styles = ‘’; 改为 var styles = styles;

 

关于跨域

if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
    (function($) {
        $.fn.wordExport = function(fileName, styles) {
            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++) {
                img[i].crossOrigin = "Anonymous";
                // 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');
                // 跨域
                newImg = new Image();
                newImg.width = w
                newImg.height = h
                newImgBase64 = '' ;//base64 
                newImg.src = img[i].src
                newImg.setAttribute("crossOrigin",'Anonymous'); //设置图片的跨域属性
                newImg.onload = function(){//图片加载完,再draw 和 toDataURL                     
                    context.drawImage(newImg,0, 0, w, h);                     
                    newImgBase64 = canvas.toDataURL("image/png");                 
                };  

                // Get data URL encoding of image
                //var uri = canvas.toDataURL("image/png");
                var uri = newImgBase64;
                $(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
            var styles = styles;

            // 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)");
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用原生JavaScript输出HTML,并将其导出为Word文档并带有页码,可以按照以下步骤进行操作: 1. 首先,创建一个包含要导出为Word的HTML内容的div元素,并将其样式设置为不可见,隐藏在页面上。 ```html <div id="exportContent" style="display: none;"> <!-- 这里是要导出HTML内容 --> </div> ``` 2. 使用JavaScript来将HTML内容输出为Word文档。 ```javascript function exportToWord() { // 获取要导出HTML内容 var exportContent = document.getElementById("exportContent").innerHTML; // 创建新的Blob对象(文件) var blob = new Blob(['\ufeff', exportContent], { type: 'application/msword' }); // 创建下载链接 var url = URL.createObjectURL(blob); // 创建临时链接元素 var link = document.createElement('a'); link.href = url; // 设置链接属性,包括文件名和下载 link.download = 'export.doc'; link.click(); // 释放URL对象 URL.revokeObjectURL(url); } ``` 3. 在导出Word文档之前,需要确保页码正确地显示在HTML中。你可以使用CSS来设置页码的样式,并使用JavaScript来将页码插入到导出HTML内容中。 ```css @page { @bottom-right { content: "Page " counter(page); } } ``` ```javascript // 获取所有带有class为“page”的元素,并将页码插入其中 var pages = document.getElementsByClassName("page"); for (var i = 0; i < pages.length; i++) { var currentPage = i + 1; pages[i].innerHTML += "<span class='page-number'>Page " + currentPage + "</span>"; } ``` 以上代码将页码插入带有class为“page”的所有元素中。 最后,在你想要触发导出操作的地方,例如一个按钮的点击事件中,调用exportToWord()函数即可导出HTML为带有页码的Word文档。 ```html <button onclick="exportToWord()">导出为Word</button> ``` 希望以上步骤能帮助你使用原生JavaScript输出HTML导出为带有页码的Word文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值