Vue如何將頁面匯出成PDF檔案
阿新 • • 發佈:2020-08-18
本文例項為大家分享了Vue將頁面匯出成PDF檔案的具體程式碼,供大家參考,具體內容如下
我在前端崗位上要實現個視覺化圖表頁的PDF檔案匯出,在這裡給大家分享下使用jsPDF和html2canvas包將Vue頁面匯出成PDF的方法。
1. 下載npm包
npm install html2canvas npm install jspdf
2. 建立外掛.js檔案
Vue-cli專案的話是在./utils資料夾下,我在這裡使用的nuxt框架,所以是在./plugins資料夾下。
import html2Canvas from 'html2canvas'; import JsPDF from 'jspdf'; export default { install (Vue,options) { Vue.prototype.getPdf = function () { var title = this.pdfTitle; // 匯出的pdf檔名 html2Canvas(document.querySelector(this.pdfSelector),{ //匯出的html元素 allowTaint: true }).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',imgWidth,imgHeight); } else { while (leftHeight > 0) { PDF.addImage(pageData,position,imgHeight); leftHeight -= pageHeight; position -= 841.89; if (leftHeight > 0) { PDF.addPage(); } } } PDF.save(title + '.pdf'); }) } } }
上面的外掛程式碼可以直接複製,然後在引用的Vue檔案中填入自己的引數就可以了。
3. 修改引用頁面
匯出按鈕呼叫getPdf方法,data填入引數。
<template> <div id="pdfPrint"> <!-- 呼叫getPdf方法 --> <el-button @click="getPdf('#pdfPrint')">儲存為PDF</el-button> </div> </template> <script> export default { data() { return { // 填入匯出的pdf檔名和html元素 pdfTitle: '因子評價報告',pdfSelector: '#pdfPrint',} },
大概就是這樣啦,非常地簡單。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。