美文网首页
vue html2canvas + jspdf 实现 清晰度

vue html2canvas + jspdf 实现 清晰度

作者: 快乐的果哥 | 来源:发表于2020-07-21 09:38 被阅读0次

    <template>
    <div>
    <a-modal v-model="dialogVisible" title="Basic Modal" >
    <iframe id="iframe123" :src="iframeSrc" frameborder="0" width="500" height="300"></iframe>
    </a-modal>
    </div>
    </template>

    <script>
    import html2canvas from 'html2canvas';
    import newJsPDF from 'jspdf'
    export default {

      data() {
        return {
           dialogVisible:false,
           iframeSrc:'',
        };
      },
      methods: {
        getPdfFromHtml(ele, pdfFileName) {
          console.log(1111,ele);
          ele.style.fontFamily='宋体';
          ele.style.padding='0 20px';
          let scale = window.devicePixelRatio * 2
          html2canvas(ele,{
            dpi: 300,
            scale:scale,
            useCORS: true,//允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
            allowTaint: false,
            height: ele.offsetHeight,
            width: ele.offsetWidth,
            windowWidth: document.body.scrollWidth,
            windowHeight: document.body.scrollHeight,
          }).then(canvas=>{
            this.dialogVisible = true;
            const _this = this;
            //未生成pdf的html页面高度
            var leftHeight = canvas.height;
            var a4Width = 595.28
            var a4Height = 841.89
            //一页pdf显示html页面生成的canvas高度;
            var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);
    
            //pdf页面偏移
            var position = 0;
    
            var pageData = canvas.toDataURL('image/jpeg', 1.0);
    
            var pdf = new newJsPDF('x', 'pt', 'a4');
            var index = 1,
              canvas1 = document.createElement('canvas'),
              height;
            pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');
    
            // $('.head-content').append($(
            //   '<div class="pdfTip">' +
            //   '   <div>正在生成第<span class="pdfProgress">1</span>页,共<span class="pdfTotal"></span>页...' +
            //   '</div>'));
            function createImpl(canvas) {
              if (leftHeight > 0) {
                index++;
                var checkCount = 0;
                if (leftHeight > a4HeightRef) {
                  var i = position + a4HeightRef;
                  for (i = position + a4HeightRef; i >= position; i--) {
                    var isWrite = true
                    for (var j = 0; j < canvas.width; j++) {
                      var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data
    
                      if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                        isWrite = false
                        break
                      }
                    }
                    if (isWrite) {
                      checkCount++
                      if (checkCount >= 10) {
                        break
                      }
                    } else {
                      checkCount = 0
                    }
                  }
                  height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                  if(height<=0){
                    height = a4HeightRef;
                  }
                } else {
                  height = leftHeight;
                }
    
                canvas1.width = canvas.width;
                canvas1.height = height;
    
                // console.log(index, 'height:', height, 'pos', position);
    
                var ctx = canvas1.getContext('2d');
                ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);
    
                var pageHeight = Math.round(a4Width / canvas.width * height);
                // pdf.setPageSize(null, pageHeight)
                if(position != 0){
                  pdf.addPage();
                }
                pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, a4Width, a4Width / canvas1.width * height);
                leftHeight -= height;
                position += height;
                // $('.pdfProgress').text(index + 1);
                // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
                if (leftHeight > 0) {
                  //添加全屏水印
                  const base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAArCAYAAADIWo5HAAACLUlEQVR42u2Zy2sCMRDGV9tbtVJKrQ/0JBWLvbgsaOttQQqreO5R6GHP/v+HZiEDQ9i8k33YDHyXbcxufpN8maRRFCJEiBAhQoTgRIfoh+hKNBe0G9I2GVG3om9bEl2I9rcIoE/77Cq8Myd6sn2ZSBgAr80YARhI+gOwCdGW6EB/d6R9XDUGFrsAf2Fe7Fswk1JBmzMd1DNKgI2EywQyUKYjkxFeOwwxkwgAvBJNqEa0DzaTHcn3qWrXdA/ocQD8m11ABUDfQF0fpujjI2QAeoZetdYdfOzB9HgGNEF6owM8Ec3Q8wEDgP07T6ktgNyB8YgAqGZ0b+gRsS2AtQP/iAUAHlAdsEW7TY6eFVrVNQN8A2AjlZho5R5wYjJhoqMiADy4DFWLPJMcKBhv3AYThFi4yJyrAAAfDrY/1SVQVhLDOWDowIwzSQ1TqwfA1P5CU3yJlsPY8fmjcTMgptmeIwB3aFbsLCvM2BRAFR4AZXYxuEdmn38hmjoosY0B5IonxLNhIYTNby0odMoAJJL1/k10bwpgQztZKaxb2YXFRnAUhexDHzoAUsGxu3j+awNA5+RmcxW1UCx1eQB4SyI1AaBrbiMEYGrwexgYBlgrgGtU/ZUY3AlGhgByTvV5MQGgW1SomqBOUWLiATy1wgNsABQz51PzWHxTALzWAW0F0EM+MKPmnLj6x0lbAPDuC5zfNPsCcChZ25DZd4VBJCW7wrRp1+whQoQIESJEg+IPRa38G55TPkQAAAAASUVORK5CYII='
                  for(let i=0;i<6;i++){
                    for(let j=0;j<5;j++){
                      const  left = (j*120)+20;
                      pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                    }
                  }
                  setTimeout(createImpl, 500, canvas);
                } else {
                  // _this.iframeSrc = pdf.output('dataurlstring');
                  // debugger;
                  pdf.save(pdfFileName + '.pdf');
                  // $('.pdfTip').remove();
                }
              }
            }
    
            //当内容未超过pdf一页显示的范围,无需分页
            if (leftHeight < a4HeightRef) {
              pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
              this.dialogVisible = true;
              // this.iframeSrc = pdf.output('dataurlstring');
              // debugger;
              pdf.save(pdfFileName + '.pdf')
            } else {
              try {
                pdf.deletePage(0);
                // $('.pdfTip').show();
                // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
                setTimeout(createImpl, 500, canvas);
    
              } catch (err) {
                console.log(err);
              }
            }
          })
    
        },
        getPdfFromHtml2(ele, pdfFileName) {
          let eleW = ele.offsetWidth// 获得该容器的宽
          //   let eleH = ele.offsetHeight // 获得该容器的高
          let eleH = ele.scrollHeight// 获得该容器的高
          let eleOffsetTop = ele.offsetTop// 获得该容器到文档顶部的距离
          let eleOffsetLeft = ele.offsetLeft// 获得该容器到文档最左的距离
          var canvas = document.createElement("canvas")
          var abs = 0
          let win_in = document.documentElement.clientWidth || document.body.clientWidth// 获得当前可视窗口的宽度(不包含滚动条)
          let win_out = window.innerWidth// 获得当前窗口的宽度(包含滚动条)
          if (win_out > win_in) {
            // abs = (win_o - win_i)/2;    // 获得滚动条长度的一半
            abs = (win_out - win_in) / 2// 获得滚动条宽度的一半
          }
          canvas.width = eleW * 2// 将画布宽&&高放大两倍
          canvas.height = eleH * 2
          var context = canvas.getContext("2d")
          context.scale(2, 2) // 增强图片清晰度
          context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
    
          html2canvas(ele, {
            dpi: 300,
            useCORS: true,//允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
            allowTaint: false,
            height: ele.offsetHeight,
            width: ele.offsetWidth,
            windowWidth: document.body.scrollWidth,
            windowHeight: document.body.scrollHeight,
          }).then(canvas => {
            var contentWidth = canvas.width
            var contentHeight = canvas.height
            //一页pdf显示html页面生成的canvas高度;
            var pageHeight = (contentWidth / 592.28) * 841.89 // 这样写的目的在于保持宽高比例一致 pageHeight/canvas.width = a4纸高度/a4纸宽度// 宽度和canvas.width保持一致
            //未生成pdf的html页面高度
            var leftHeight = contentHeight
            //页面偏移
            var position = 0
            //a4纸的尺寸[595.28,841.89],单位像素,html页面生成的canvas在pdf中图片的宽高
            var imgWidth = 595.28
            var imgHeight = (595.28 / contentWidth) * contentHeight
            var pageData = canvas.toDataURL("image/jpeg", 1.0)
            var pdf = newJsPDF("", "pt", "a4")
            //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
            //当内容未超过pdf一页显示的范围,无需分页
            if (leftHeight < pageHeight) {
              //在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
              pdf.addImage(pageData, "JPEG", 5, 0, imgWidth, imgHeight)
              // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
            } else {
              // 分页
              while (leftHeight > 0) {
                pdf.addImage(pageData, "JPEG", 5, position, imgWidth, imgHeight)
                leftHeight -= pageHeight
                position -= 841.89
                 const base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAArCAYAAADIWo5HAAACLUlEQVR42u2Zy2sCMRDGV9tbtVJKrQ/0JBWLvbgsaOttQQqreO5R6GHP/v+HZiEDQ9i8k33YDHyXbcxufpN8maRRFCJEiBAhQoTgRIfoh+hKNBe0G9I2GVG3om9bEl2I9rcIoE/77Cq8Myd6sn2ZSBgAr80YARhI+gOwCdGW6EB/d6R9XDUGFrsAf2Fe7Fswk1JBmzMd1DNKgI2EywQyUKYjkxFeOwwxkwgAvBJNqEa0DzaTHcn3qWrXdA/ocQD8m11ABUDfQF0fpujjI2QAeoZetdYdfOzB9HgGNEF6owM8Ec3Q8wEDgP07T6ktgNyB8YgAqGZ0b+gRsS2AtQP/iAUAHlAdsEW7TY6eFVrVNQN8A2AjlZho5R5wYjJhoqMiADy4DFWLPJMcKBhv3AYThFi4yJyrAAAfDrY/1SVQVhLDOWDowIwzSQ1TqwfA1P5CU3yJlsPY8fmjcTMgptmeIwB3aFbsLCvM2BRAFR4AZXYxuEdmn38hmjoosY0B5IonxLNhIYTNby0odMoAJJL1/k10bwpgQztZKaxb2YXFRnAUhexDHzoAUsGxu3j+awNA5+RmcxW1UCx1eQB4SyI1AaBrbiMEYGrwexgYBlgrgGtU/ZUY3AlGhgByTvV5MQGgW1SomqBOUWLiATy1wgNsABQz51PzWHxTALzWAW0F0EM+MKPmnLj6x0lbAPDuC5zfNPsCcChZ25DZd4VBJCW7wrRp1+whQoQIESJEg+IPRa38G55TPkQAAAAASUVORK5CYII='
                 for(let i=0;i<6;i++){
                    for(let j=0;j<5;j++){
                       const  left = (j*120)+20;
                       console.log(555,left);
                       pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                    }
                 }
                //避免添加空白页
                if (leftHeight > 0) {
                     pdf.addPage()
                }
              }
            }
             // pdf.save();
             this.dialogVisible = true;
            // const a = pdf.output();
            // debugger;
             pdf.save(pdfFileName + ".pdf")
              this.$nextTick(()=>{
                 // const _iframeSrc = pdf.output('datauristring');
                 // window.open(pdf.output('datauristring'));
                 //    this.iframeSrc = pdf.output('dataurlstring');
                 // this.iframeSrc = pdf.output('datauristring');
                 // debugger;
                  // this.showPdf(_iframeSrc);
                  // console.log(555555,this.iframeSrc)
                 // document.getElementById("iframe123").src = pdf.output('datauristring');
              })
          })
        },
    
      }
    }
    

    </script>

    <style scoped lang="scss">

    </style>

    相关文章

      网友评论

          本文标题:vue html2canvas + jspdf 实现 清晰度

          本文链接:https://www.haomeiwen.com/subject/zywbkktx.html