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{
  width: 100%;
  height: 500px;
  font-size: 200px;
  margin-bottom:10px;
  background: pink;
}
</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM