篇首语:本文由小编为大家整理,主要介绍了前端使用vue实现导出pdf相关的知识,希望对你有一定的参考价值。
1、使用html2canvas和jspdf插件实现
这个方式是通过html2canvasl来把html页面转换成图片,然后再通过jspdf将图片转换为pdf文件
(1)缺点
生成的pdf质量不高,画面有些模糊,失真严重
如果在分页的地方有图片的话,可能会把图片也给你一分为二了
(2)安装插件
npm install --save html2canvasnpm install jspdf --save
(3)创建 htmlToPdf.js 文件
import html2Canvas from "html2canvas"import JsPDF from "jspdf"export default install (Vue, options) Vue.prototype.getPdf = function (idStr, title) html2Canvas(document.querySelector("#" + idStr), // allowTaint: true, useCORS: true, // scale: 2, // 提升画面质量,但是会增加文件大小 ).then((canvas) => const contentWidth = canvas.width const contentHeight = canvas.height /* 导出不分页处理 */ const pageData = canvas.toDataURL("image/jpeg", 1.0) const pdfWidth = (contentWidth + 10) / 2 * 0.75 const pdfHeight = (contentHeight + 200) / 2 * 0.75 // 500为底部留白 const imgWidth = pdfWidth const imgHeight = (contentHeight / 2 * 0.75) // 内容图片这里不需要留白的距离 const PDF = new JsPDF("", "pt", [ pdfWidth, pdfHeight, ]) PDF.addImage(pageData, "jpeg", 0, 0, imgWidth, imgHeight) PDF.save(title + ".pdf") ) ,
(4)在项目文件中的 main.js 里面引入,并注册
import htmlToPdf from "@/scripts/common/utils/htmlToPdf"Vue.use(htmlToPdf)
(5)在你要导出的页面中,给你要导出的那个部分 加一个id名字
//给自己需要导出的ui部分.定义id为"pdfDom".此部分将就是pdf显示的部分
导出PDF
(6)然后 在methods 里面声明点击事件,在return里给他一个导出的名字,这就ok啦
export default data () return fileName: "页面导出PDF文件名"methods:export () this.getPdf("pdfDom", this.fileName)
以上是关于前端使用vue实现导出pdf的主要内容,如果未能解决你的问题,请参考以下文章