zoukankan      html  css  js  c++  java
  • vue (将html转为图片,多张图片打包为zip)

    效果图

    安装依赖
     "file-saver": "^2.0.2"
    "jszip": "^3.5.0",
    
    实现页面代码
    <template>
      <div class="home">
        <!-- <button type="button" class="btn btn-primary" v-on:click="printOut22"> -->
        <!-- <button type="button" class="btn btn-primary" v-on:click="getPdf('#subOutputRank')">
          导出PDF
        </button> -->
        <!-- <button @click="makeImage">生成图片</button> -->
        <button @click="download">下载图片压缩包</button>
        <div class="box">
          <div class="getPDF imgArea" id="subOutputRank" ref="custom_table">
            <p class="item">11</p>
            <p class="item">22</p>
            <p class="item">33</p>
            <p class="item">44</p>
          </div>
        </div>
        
      </div>
    </template>
    
    <script>
    import JSZip from 'jszip'
    import FileSaver from 'file-saver'
    export default {
      name: 'Home',
      data() {
        return {
          htmlTitle: '页面导出PDF文件名',
        }
      },
      methods:{
        //生成图片
        makeImage(){
          const tableWidth = this.$refs.custom_table.clientWidth;  // 具体内容的宽度
          const tableHeight = this.$refs.custom_table.clientHeight;  // 具体内容的高度
          const targetDom = document.querySelector(".imgArea");
          let copyDom = targetDom.cloneNode(true);
          copyDom.style.width = tableWidth;
          copyDom.style.height = tableHeight;
          document.querySelector("body").appendChild(copyDom);
          const options =  { useCORS: true, backgroundColor: null }
          html2canvas(copyDom,options ).then(
            canvas => {
              //document.body.appendChild(canvas);
              this.imgURL = canvas.toDataURL("image/png");
              //必须同源(访问的网站域名与服务器域名一致)才能下载
              const eleLink = document.createElement("a");
              console.log(11,this.imgURL );
              eleLink.href = this.imgURL;    // 转换后的图片地址
              eleLink.download = +new Date() + "_实时采集数据";
              document.body.appendChild(eleLink);
              // 触发点击
              eleLink.click();
              // 然后移除
              document.body.removeChild(eleLink);
              document.body.removeChild(copyDom);
            }
          );
        },
        download(){
          var arrImages=[];
          let options =  { useCORS: true, backgroundColor: null }
          const targetDoms = document.querySelectorAll(".item");
          for(let i=0,len=targetDoms.length;i<len;i++){
            let copyDom = targetDoms[i].cloneNode(true);
            copyDom.style.width = targetDoms[i].clientWidth;
            copyDom.style.height = targetDoms[i].clientHeight;
            document.querySelector("body").appendChild(copyDom);
            html2canvas(copyDom,options ).then(
              canvas => {
                //document.body.appendChild(canvas);
                let imgURL = canvas.toDataURL("image/png");
                console.log(i,imgURL);
                arrImages.push({fileUrl:imgURL,renameFileName:i+'.png'});
                if(i==len-1){
                   console.log('图片包',arrImages);
                  this.filesToRar(arrImages, '我的压缩包');
                }
              }
            );
          }
        },
        /**文件打包
         * arrImages:文件list:[{fileUrl:文件url,renameFileName:文件名}]
         * filename 压缩包名
         * */
        filesToRar(arrImages, filename) {
          let _this = this;
          let zip = new JSZip();
          let cache = {};
          let promises = [];
          _this.title = '正在加载压缩文件';
    
          for (let item of arrImages) {
            const promise= _this.getImgArrayBuffer(item.fileUrl).then(data => {
              // 下载文件, 并存成ArrayBuffer对象(blob)
              zip.file(item.renameFileName, data, { binary: true }); // 逐个添加文件
              // zip.file(item.renameFileName, data, {base64: true}); // 逐个添加文件
              cache[item.renameFileName] = data;
            });
            promises.push(promise);
          }
    
          // let img = zip.folder("images");
          // arrImages.forEach((v,i)=>{
          //   img.file(v.renameFileName, v.fileUrl, {base64: true})
          // })
    
          Promise.all(promises).then(() => {
            zip.generateAsync({ type: "blob" }).then(content => {
              _this.title = '正在压缩';
              // 生成二进制流
              FileSaver.saveAs(content, filename); // 利用file-saver保存文件  自定义文件名
              _this.title = '压缩完成';
            });
          }).catch(res=>{
            _this.$message.error('文件压缩失败');
          });
        },
      //获取文件blob
        getImgArrayBuffer(url){
          let _this=this;
          return new Promise((resolve, reject) => {
              //通过请求获取文件blob格式
            let xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", url, true);
            xmlhttp.responseType = "blob";
            xmlhttp.onload = function () {
              if (this.status == 200) {
                resolve(this.response);
              }else{
                reject(this.status);
              }
            }
            xmlhttp.send();
          });
    
        },
      },
    }
    </script>
    <style lang='less' scoped>
    .box{
      overflow: scroll;
      height: 100vh;
    }
    .item{
       100%;
      height: 500px;
      font-size: 200px;
      margin-bottom:10px;
      background: pink;
    }
    </style>
    
  • 相关阅读:
    切片 Slice
    表单与v-model
    vue-内置指令
    go单元测试
    go异常处理
    设计模式
    django数据库事务
    go interface衍生的插件化处理
    goroutine
    drf之序列化
  • 原文地址:https://www.cnblogs.com/miaSlady/p/13559286.html
Copyright © 2011-2022 走看看