效果图同上。
注意点:
1:动态创建的iframe是通过document.querySelector('#report-iframe').appendChild(iframe),里面的appendChild进行添加成功的
2:当创建出iframe之后,我们想拿到iframe里面的标签按钮,必须是在onload事件中才能得到,不然拿到的html是空的
3:iframe里面的标签按钮,直接通过普通的getElementById是获取不到的,这时候要使用document.querySelector('#report-iframe iframe').contentWindow.document.getElementById('你想获取的按钮的id'),这样才能顺利拿到iframe里面的标签按钮
4:这时候使用原生去监听按钮是否被点击
doc.addEventListener('click', function(e) {
that.markPrint()
})
这里的 that.markPrint()是我调的方法,通常使用this.markPrint(),但是这里要注意我们是在iframe里面进行调用,所以需要先定义const that=this
下面上关键代码
<el-dialog
title="报告打印"
:visible.sync="reportDialogVisible"
:close-on-click-modal="false"
width="80%"
:before-close="cancelReportDialog"
>
<div id="report-iframe" style="height: 100%">
</div>
<div slot="footer">
<el-button @click="cancelReportDialog">关 闭</el-button>
</div>
</el-dialog>
<el-button type="text" @click.stop="printSingleReport(scope.row.reportId,
scope.row.pathologyId)">
报告
</el-button>
js中:
async printSingleReport(reportId, pathologyId) {
if (!reportId) {
this.$message.error('未生成报告!')
return
}
const { data } = await printReport({ reportId })
this.reportUrl = data
this.reportDialogVisible = true
this.PrintpathologyId = pathologyId
this.$nextTick(() => {
this.viewReport()
})
},
viewReport() {
const url = '/wispath/pdfjs/web/viewer.html?file=' + encodeURIComponent(this.reportUrl)
this.createIframe(url)
},
async createIframe(src) {
const iframe = document.createElement('iframe')
iframe.style.width = '100%'
iframe.style.height = '100%'
iframe.style.margin = '0'
iframe.style.padding = '0'
iframe.style.overflow = 'hidden'
iframe.style.border = 'none'
iframe.src = src
iframe.id = 'reportIframe'
iframe.allow = 'fullscreen'
document.querySelector('#report-iframe').appendChild(iframe)
const that = this
iframe.contentDocument.body.onload = function() {
const doc = document.querySelector('#report-iframe iframe').contentWindow.document.getElementById('print')
doc.addEventListener('click', function(e) {
that.markPrint()
})
}
},