先看效果
如上录取通知书实现原理,需要一张背景图片,里面的文字全部是前端加上的,然后用html2canvas绘图成一张照片,下载使用
安装依赖:npm i html2canvas
引入:import Html2canvas from 'html2canvas'
代码:
<div class="results_notice" ref="resultsNotice">
<div class="offer">
<div class="offer_img">
<el-image class="offer_img" :src="resultsNotice" fit="scale-down" />
</div>
<div class="offer_text">
<div class="text" style="margin-bottom:16px">
恭喜你!
<span class="under">{{user.name}}</span>
同学:
</div>
<template>
<div class="text fLine">
你已与
<span class="under">{{aplStuCode.tcName}}</span>
<!-- <span class="under"></span>。 -->
</div>
</template>
<template>
<div
class="offer_text_sentence"
>岁月因青春慨然以赴,而更加静好;世间因少年挺身向前,而更加瑰丽。愿大家在今后的科研道路上不断学习知识,充实自己,成为未来科技的领军人才。</div>
</template>
</div>
<template>
<div class="offer_parent">导师签字:</div>
<div class="offer_student">学生签字:</div>
</template>
</div>
</div>
exportPDF () {
this.PDFloading = true
this.$nextTick(() => {
new Html2canvas(this.$refs.resultsNotice, {
useCORS: true,
// width: 1140,
// height: 480,
windowWidth: document.body.scrollWidth,
windowHeight: document.body.scrollHeight,
// x: 350,
// y: window.pageYOffset + 335
x: 0,
y: window.pageYOffset
}).then((canvas) => {
downloadOff(
canvas.toDataURL('image/png', 1.0),
`下载后的名称.png`
)
this.PDFloading = false
})
})
},
下载方法
export function downloadOff (url) {
const fileNameList = url.split('?')[0].split('/')
const fileName = fileNameList[fileNameList.length - 1]
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
// 请求头带上token
xhr.setRequestHeader('token', Vue.cookie.get('stuToken'))
xhr.responseType = 'blob'
xhr.onload = e => {
const a = document.createElement('a')
a.href = window.URL.createObjectURL(xhr.response)
a.download = fileName
a.click()
}
xhr.send()
// 打开新页面手动下载
// const a = document.createElement('a')
// a.setAttribute('download', '')
// a.setAttribute('target', '_blank')
// a.setAttribute('href', url)
// a.click()
}