Posted in Javascript onJune 15, 2017
整理文档,搜刮出一个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中设置不对这两个文件进行验证。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
vue中将网页打印成pdf实例代码
- Author -
激烈的海胆声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@