vue页面打印pdf

  1. cnpm install html2canvas;
    cnpm install jspdf --save;
  2.      <el-button
              @click="getPdf('print', 'aa')"
              icon="el-icon-refresh"
              size="mini">
                打印PNG
            </el-button>
  3. <div id="print">
        <内容>
    </div>
  4. import html2Canvas from 'html2canvas'
    import JsPDF from 'jspdf'
    export default {
      install(Vue) {
        // print,要打印区域的ID
        Vue.prototype.getPdf = function (print) {
          var title = print
          html2Canvas(document.querySelector(`#${print}`), {
            allowTaint: true,
            height: document.querySelector(`#${print}`).scrollHeight,
          }).then(function (canvas) {
            let contentWidth = canvas.width
            let contentHeight = canvas.height
            let pageHeight = contentWidth / 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)
            } else {
              while (leftHeight > 0) {
                PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                leftHeight -= pageHeight
                position -= 841.89
                if (leftHeight > 0) {
                  PDF.addPage()
                }
              }
            }
            // title图片名称
            PDF.save(title + '.pdf')
          }
          )
        }
      }
    }
posted @ 2023-02-13 17:05  QinHaoRan  阅读(344)  评论(0)    收藏  举报