Vue implements downloading of html content as a pdf file

1. Installation dependencies

The following two dependencies are mainly used:

html2canvas: By obtaining an element of HTML and then generating a Canvas, users can save it as a picture.

jspdf: HTML5-based client-side solution for generating PDF documents for various purposes.

npm install html2canvas jspdf --save

2. How to use

The following is used locally

/ 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
    
    
  install (Vue, options) {
    
    
    Vue.prototype.getPdf = function () {
    
    
   //获取页面标题,作为文件名称,也可以使用时间戳生成不重复的文件名使用
      var title = this.htmlTitle
      html2Canvas(document.querySelector('#pdfDom'), {
    
    
        allowTaint: true,
        //防止页面过宽导致右侧出现黑灰色背景区域
        scale: 2
      }).then(function (canvas) {
    
    
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        //A4纸张标准宽高进行转换
        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()
            }
          }
        }
        //文件导出生成
        PDF.save(title + '.pdf')
      }
      )
    }
  }
}    

It can also be introduced in the global main.js file and mounted globally:

import htmlToPdf from '@/components/utils/htmlToPdf'
// 使用Vue.use()方法就会调用工具方法中的install方法
Vue.use(htmlToPdf)

3. Call the export method in the page to export and download files

1. The page label elements are as follows:

<div id="pdfDom">
   <!-- 要下载的HTML页面,页面是由后台返回 -->
  <div v-html="pageData" class="markdown-body"></div>
</div>
<el-button type="primary" size="small" @click="getPdf('#pdfDom')">点击下载</el-button>

2. The js part of the page is as follows:

export default {
    
    
  data () {
    
    
      return {
    
    
        htmlTitle: '页面导出PDF文件名'
      }
  }
}

The above content is reproduced at: https://www.cnblogs.com/guobin-/p/14451837.html


Supplement: You can add padding to the content container to beautify the printing result:

.markdown-body{
    
    
  width:70%;
  margin:50px auto;
  padding:50px 30px;//打印页面四周留白
}

Guess you like

Origin blog.csdn.net/weixin_43939111/article/details/129437582