vue中将网页打印成pdf实例代码
整理文档,搜刮出一个vue中将网页打印成pdf的代码,稍微整理精简一下做下分享。
<template> <div class="pdf-wrap" id="pdfWrap"> <button v-on:click="getPdf">点击下载PDF</button> <div class="pdf-dom" id="pdfDom"></div> </div> </template> <style lang="scss" scoped> </style> <script type="text/ecmascript-6"> import html2Canvas from '@/components/html2canvas.js' import JsPDF from '@/components/jsPdf.debug.js' export default { methods: { getPdf: function () { let _this = this let pdfDom = document.querySelector('#pdfDom') html2Canvas(pdfDom, { onrendered: 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(_this.pdfData.title + '.pdf') } }) html2Canvas() }, } } </script>
需要引入
html2canvas.js'
和
jsPdf.debug.js
这两个插件库可轻松百度到。如果eslint验证报错,可在eslintignore中设置不对这两个文件进行验证。
相关推荐
elizabethxxy 2020-11-11
CodeAsWind 2020-11-03
Andyshrk 2020-08-29
千锋 2020-08-20
82550495 2020-08-03
demm 2020-07-28
waiwaiLILI 2020-07-20
higher0 2020-07-08
songfens 2020-07-05
hermanncain 2020-06-25
Aleks 2020-06-13
Elmo 2020-06-13
学习进步 2020-06-11
Kwong 2020-06-11
GhostLWB 2020-06-08
xmwang0 2020-06-08
菇星獨行 2020-05-15
ChenRuiyz 2020-05-15