背景:项目遇到了一个要导出pdf模板的需求,后端说没时间做(其实是嫌麻烦,不想写样式,没办法了,只好…)
头脑风暴:Y哒,我之前也没做过,百度了一下,发现前端还真能实现。那就开整!
步骤
1, 安装
npm install html2canvas jspdf --save
npm install jspdf --save
2.用法(为了方便,我直接封装成一个公共的函数,然后配合element的加载组件一起用),以下是代码:
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import { Loading, Message } from 'element-ui'
export function getPdf(htmlTitle, id) {
let downloadLoadingInstance
var title = htmlTitle //PDF标题
downloadLoadingInstance = Loading.service({
text: '正在下载数据,请稍候',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
})
html2Canvas(document.querySelector(`${id ? id : '#pdfDom'}`), {
allowTaint: true,
taintTest: false,
useCORS: true,
dpi: window.devicePixelRatio * 2, //将分辨率提高到特定的DPI 提高四倍
scale: 2 //按比例增加分辨率
})
.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 = 555.28
let imgHeight = (592.28 / contentWidth) * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
imgWidth = 595.28
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')
downloadLoadingInstance.close()
})
.catch((r) => {
console.error(r)
Message.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close()
})
}
3,vue里面使用:
<div id="pdfDom" class="pdfStyle">
// 这里展示PDF的内容的代码
</div>
<el-button type="primary" @click="downloadPDF()">下 载</el-button>
---------------------------------------------------------------------------------------------------------
注意:这里最重要的是id, 一定要和上面js里面代码写的id 保持一致,或者传你自己写的id也行
downloadPDF() {
let title = '123'
this.getPdf(title)
}
css: 样式没啥好说的,自己慢慢调吧