<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>
<script src="https://cdn.bootcss.com/jspdf/1.3.4/jspdf.debug.js"></script>

vue里面结合element的js下载pdf_vue


把文件放在脚手架的文件静态或者动态的文件夹里面

使用HTML导入

<script src=".js/html2canvas.js"></script>
<script src="./js/jspdf.debug.js"></script>
<script src="./js/pdfdown.js"></script>

pdfdownjs如下采用的是全局变量 容易污染 所以 在组件结束的生命周期里面

destroyed () {
window.but = null // 释放变量
clearTimeout()
}
downPdf () {
this.$confirm('是否缩放最佳下载视图', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$message({
type: 'success',
message: '缩放成功'
})
window.scrollTo(0, 350) // 滚动条位置
this.showHaddin = false // 控制样式的隐藏
this.elCollapseBox = 2
setTimeout(() => { // 定时器的原因 如果你之前操作节点 是为了等待 dom的完成加载之后进行操作
const data = window.but() // promise 为了等待下载完成 再执行 加载的控制
data.then(x => {
if (x) {
this.$refs['main-one'].style.zoom = 1
this.showHaddin = true
this.elCollapseBox = 1
}
})
}, 1500)
}).catch(() => {
this.$message({
type: 'info',
message: '取消缩放'
})
})
}

pdfdownjs文件内容

window.but = async function () {
var target = document.getElementById('noticeContent')
target.style.background = '#FFFFFF'
let copyDom = target.cloneNode(true) //拿到打印的所有节点信息
document.querySelector('body').appendChild(copyDom)
let pdf = html2canvas(copyDom, {
onrendered: function async (canvas) {
var contentWidth = canvas.width
var contentHeight = canvas.height
// 一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 592.28 * 841.89
// 未生成pdf的html页面高度
var leftHeight = contentHeight
// 页面偏移
var position = 0
// a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28
var imgHeight = 592.28 / contentWidth * contentHeight
console.log(imgHeight)
var pageData = canvas.toDataURL('image/jpeg', 1.0)
var pdf = new jsPDF('', 'pt', 'a4')
// 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
// 当内容未超过pdf一页显示的范围,无需分页
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('content.pdf')
copyDom.remove()
}
})
await pdf // 为的是等待执行完成
return new Promise((suc,fail)=>{
suc(true)
})
}