Nuxt2 前端 JS 将 HTML 转图片后用 PDF 下载,可用 js 调用浏览器的打印 HTML

128 阅读1分钟

本文讲 前端 JS 将 HTML 转图片后用 PDF 下载

缺点

  • 转成的PDF是由图片生成的,而不是文字
  • 文件大,打印后容易失真

下载依赖

"html2canvas": "^1.4.1",
"jspdf": "^2.5.1",

新增plugins

// 文件 plugins\htmlToPDF.js
import html2Canvas from 'html2canvas'
import  JsPDF  from 'jspdf'
import Vue from 'vue'

const htmlToPDF = {
  install(Vue, options) {
  // isVertical 横向还是竖向打印
    Vue.prototype.getPdf = function ( pdfDomId, htmlTitle, isVertical = true) {
      const title = htmlTitle  // DPF标题
      html2Canvas(document.querySelector(`#${pdfDomId}`), {
        // allowTaint: true,
        taintTest: false,
        useCORS: true,
        // y:72, // 对Y轴进行裁切
        // width:1200,
        // height:5000,
        dpi: window.devicePixelRatio * 5, // 将分辨率提高到特定的DPI 提高四倍
        scale: 5 // 按比例增加分辨率
      }).then(function (canvas) {
        const contentWidth = canvas.width
        const 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


        if (!isVertical) {
          pageHeight = contentWidth / 841.89 * 592.28
          imgWidth = 841.89
          imgHeight = 841.89 / contentWidth * contentHeight
        }

        canvas.setAttribute('crossOrigin', 'anonymous')
        const pageData = canvas.toDataURL('image/jpeg', 1.0)
        const PDF = new JsPDF(isVertical ? '' : 'l', '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 -= isVertical ?  841.89 : 595.28
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save(title + '.pdf')
      })
    }
  }
}

Vue.use(htmlToPDF)

在nuxt.config.js中新增plugins

  plugins: [
    '@/plugins/htmlToPDF',
  ],

调用

this.getPdf('contractPdf', '文件名.pdf', false)