vue 实现将 html 页面 以 PDF 的格式展示到页面

vue 实现将 html 页面 以 PDF 的格式展示到页面

1、 下载两个包:html2canvasjspdf

yarn add  html2canvas
yarn add  jspdf

2、书写 PDF 组件


import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
const htmlToPdf = {
 getPdf(title) {
  window.pageYoffset = 0
  document.documentElement.scrollTop = 0
  document.body.scrollTop = 0

  setTimeout(() => {
  // 获取页面的 包含 id 为 pdfDom 的标签
   html2Canvas(document.querySelector('#pdfDom'), {
    allowTaint: true,
    scale: 2
   }).then((canvas) => {
    const contentWidth = canvas.width
    const contentHeight = canvas.height
    const pageHeight = (contentWidth / 592.28) * 841.89
    let leftHeight = contentHeight
    let position = 0
    const imgWidth = 595.28
    const imgHeight = 592.28 / contentWidth * contentHeight
    const pageData = canvas.toDataURL('image/jpeg', 1.0)
    const 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()
      }
     }
    }
    PDF.save(title + '.pdf')
   })
  }, 100)
 }
}
export default htmlToPdf

3、 绘制 需要打印的 HTML 页面

内容可以随意写

<template>
  <div class="home">
  // 这个 div 的id, 要和上面的 pdf.js 的 id 保持一致。
    <div id="pdfDom">
      HomeView
    <br>
    <img src="../assets/logo.png" alt="">
    </div>
    <button>点击生成 pdf</button>
  </div>
</template>

vue 实现将 html 页面 以 PDF 的格式展示到页面_第1张图片

4、运用到页面

HTML 页面

<template>
  <div class="home">
    <div id="pdfDom">
      HomeView
    <br>
    <img src="../assets/logo.png" alt="">
    </div>
    <button @click="clickHandle">点击生成 pdf</button>
  </div>
</template>

逻辑代码

<script>

import pdf from '../components/Pdf'
export default {
  name: 'HomeView',
  components: {
  },
  methods: {
    clickHandle(){
      this.$nextTick(()=> {
      	// 参数是导出的文件名
        pdf.getPdf('导出文件')
      })
    }
  },
}
</script>

vue 实现将 html 页面 以 PDF 的格式展示到页面_第2张图片
vue 实现将 html 页面 以 PDF 的格式展示到页面_第3张图片

完成。

你可能感兴趣的:(vue.js,html,javascript)