vue将页面生成PDF文件

1、实现说明 通过dom-to-image将dom转为图片

      不使用html2canvas的原因是因为在开发过程中,因为页面dom较多,html2canvas出现卡顿响应很慢,通过dom-to-image可以很好的解决该问题

 2、 通过jspdf 将图片生成pdf

       在第一步将dom转换为图片后,需要通过jspdf将图片生成pdf

3、安装依赖 :

npm install dom-to-image

npm install jspdf --save

 4、 组件中引入:     

import domtoimage from 'dom-to-image';

import JsPDF from 'jspdf'

5、实现代码
     在dom中 将canvas元素隐藏

onPrint() {
            let that = this;
            let node = document.getElementById('pdfDom');
            console.log(node)
            domtoimage.toJpeg(node, {
              width: node.clientWidth,
              height: node.clientHeight,
              cacheBust: true,
              style: {
                margin: 0,
                background: '#fff',
              }
            })
            .then(function(dataUrl) {
              that.canvasWidth = node.clientWidth;
              that.canvasHeight = node.clientHeight;
              let imgObj = new Image()
              imgObj.src = dataUrl;
                    console.log(imgObj)
              //待图片加载完后,将其显示在canvas上
              imgObj.onload = function (img) {
                       console.log(img,'img')
                      let canvas = document.getElementById("canvasDom");
                      // canvas.width = node.clientWidth;
                      // canvas.height = node.clientHeight;
                      console.log(canvas.width,canvas.height,'canvas.width')
                      canvas.getContext("2d").drawImage(imgObj,0,0,that.canvasWidth,that.canvasHeight); //将图片绘制到canvas中
                      let contentWidth = canvas.width
                      let contentHeight = canvas.height
                      let pageHeight = contentWidth / 592.28 * 841.89 // a4纸的尺寸[592.28,841.89]
                      let leftHeight = contentHeight
                      let position = 0
                      let imgWidth = 595.28
                      let imgHeight = 592.28 / contentWidth * contentHeight
                      let pageData = canvas.toDataURL('image/jpeg', 1.0)
                      let PDF = new JsPDF('', 'pt', 'a4')
                      if (leftHeight < pageHeight) {
                          PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight) // 大于1页高度时分页
                      } else {
                          while (leftHeight > 0) {
                              PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                              leftHeight -= pageHeight
                              position -= 841.89
                              if (leftHeight > 0) {
                                  PDF.addPage()
                              }
                          }
                      }
                      PDF.save(that.htmlTitle + '.pdf')
              }
              return dataUrl
            })
            .catch(function(error) {
              console.error('oops, dom2img went wrong!', error);
            });
        },

你可能感兴趣的:(pdf,前端,javascript,vue.js)