1. We are going to add two modules

First, convert the page HTML to an image

1

npm install --save html2canvas

② Second, create PDF images

1

npm install jspdf --save

2, define global function.. Create an htmlTopdf.js file in the specified location. My personal habits in (‘ SRC/components/utils/htmlToPdf ‘)

Add the following methods to the page you want to export

Import html2Canvas from 'html2Canvas' import JsPDF from' JsPDF 'export default{install (Vue, Options) {vue.prototype.getpdf = function () {var title = this.htmltitle //#pdfDom is the Id of the element to export like <div Html2Canvas (document.querySelector('#pdfDom'), {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', 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') } ) } }Copy the code

3. Use our defined function file in main.js.

import htmlToPdf from '@/components/utils/htmlToPdf'
Vue.use(htmlToPdf)
Copy the code

4. In the required export page.. Just call our getPdf method.

Such as:

<el-button @click="getPdf"> </el-button>Copy the code