vue 导出页面为PDF格式
- 导出页面为PDF格式js文件
我用的是vue2
html2canvas版本为 ^1.4.1 npm install html2canvas --save
jspdf版本为^2.5.1 npm install jspdf --save
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install(Vue, options) {
Vue.prototype.customGetPdf = function(config) {
console.log(options, config)
let title = config.name
html2Canvas(document.querySelector(config.ele), {
useCORS: true
}).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()
}
}
}
if(config.type === 'download') PDF.save(title + '.pdf')
else if(config.type === 'getFile') {
let blob = PDF.output('blob',{filename: title})
let file = new File([blob],title,{type:blob.type})
console.log('........file..........', file)
config.callback(file)
return file
}
})
}
}
}
- 在main.js 引入
import customGetPdf from '@/utils/customHtomToPdf'
Vue.use(customGetPdf)
- 使用(可直接点击下载)
<el-button
type="primary"
@click="
customGetPdf({
ele: '#pdfDom',
name: '文件name',
type: 'download'
})
"
>下载</el-button>
- 如果想传文件到后端
methods: {
getFile() {
let _this = this
let file = this.customGetPdf({
ele: '#pdfDom',
name: this.info.ciAutomaName,
type: 'getFile',
callback: function (val) {
let dataForm = new FormData()
dataForm.append('file', val)
uploadReportToWiki(dataForm).then((res) => {
if (res.data.message.code === 200) {
_this.$message({ type: 'success', message: '上传成功' })
} else
_this.$message({
type: 'error',
message: res.data.message.messageInfo
})
_this.loading = false
})
}
})
}
}