vue中导出pdf
这种方法导出pdf的前提是,要导出的部分要在系统中有页面,然后用canvas画图的方式截取页面。
首先在项目中安装依赖
npm install html2canvas npm install jspdf
在需要调用的地方插入以下代码
this.getPdf('filename', "pdfDom");
在plugins文件夹下添加htmlToPdf.js文件
// 导出页面为PDF格式 import html2Canvas from 'html2canvas' import JsPDF from 'jspdf' export default { install(Vue, options) { Vue.prototype.getPdf = function (name, id) { let title = name || 'index' html2Canvas(document.querySelector(`#${id}`), { allowTaint: true, taintTest: false, useCORS: true, dpi: window.devicePixelRatio*4, //将分辨率提高到特定的DPI 提高四倍 scale:4 //按比例增加分辨率 }).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') } ) } } }
在main.js中引入htmlToPdf.js文件
import htmlToPdf from '@/plugins/htmlToPdf' Vue.use(htmlToPdf)
作者:慕夕呀 链接:https://zhuanlan.zhihu.com/p/383550401 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。