<template>
<button @click="printFile">打印</button>
</template>
<script>
export default {
name: 'PrintFile',
data() {
return {
// 需要打印的PDF路径
fileUrl: 'http://xxx.pdf'
}
},
methods: {
printFile() {
// 新建一个iframe节点
const iframe = document.createElement('iframe')
// 设置节点不显示
iframe.style.display = 'none'
// 把要打印的PDF文件路径赋值给src属性
iframe.src = this.fileUrl
// 添加节点到文档中
document.body.appendChild(iframe)
// 等待文件加载完成后进行打印
iframe.onload = function () {
iframe.contentWindow.print()
}
},
</script>
需要注意的是,要打印的PDF文件必须和自己的服务放在同一个服务下,不能跨域。不然浏览器会因为安全策略进行拦截