Blob格式的PDF文件调用打印,浏览器文件打印(兼容)
浏览器文件打印,解决:非整个浏览器页面打印,指定模块儿打印
要调用 iframe 中加载的 PDF 文件的打印功能,可以直接操作 iframe 的 contentWindow 对象,调用其内置的打印方法(PDF 浏览器插件或 PDF.js 渲染器通常会暴露 print() 方法)。以下是具体实现方式:
实现思路
- 确保 iframe 已完全加载 PDF(监听
load事件)。 - 通过 iframe 的
contentWindow调用 PDF 的打印方法(不同浏览器可能有差异,需兼容处理)。 - 若直接调用失败,降级使用
window.print()打印整个 iframe 内容。
<iframe :src="fileUrl" width="100%" height="700px" ref="pdfIframe" @load="handleIframeLoad"></iframe>
<el-button size="small" type="primary" @click="printPdf()">打印</el-button>
fileUrl 文件地址; @load="handleIframeLoad" 判断pdf文件是否加载完成。
// 监听 iframe 加载完成handleIframeLoad() {this.isIframeLoaded = true;console.log('PDF 加载完成,可打印');},// 打印 iframe 中的 PDFprintPdf() {if (!this.isIframeLoaded) {alert('PDF 尚未加载完成,请稍后再试');return;}const iframe = this.$refs.pdfIframe;const iframeWindow = iframe.contentWindow;try {// 方案1:直接调用 PDF 内置的打印方法(主流浏览器对 PDF 支持较好)if (iframeWindow.print) {// 部分浏览器中,PDF 的 print() 是异步的,需包裹在 setTimeout 中setTimeout(() => {iframeWindow.print();}, 100);} else {// 方案2:降级使用 window.print() 打印整个 iframe 区域this.printIframeWithWindowPrint(iframe);}} catch (error) {console.error('打印失败,使用降级方案', error);this.printIframeWithWindowPrint(iframe);}},// 降级方案:使用 window.print() 并指定只打印 iframe 内容printIframeWithWindowPrint(iframe) {// 保存当前页面的打印样式const originalStyle = document.body.style;// 隐藏页面其他内容,只显示 iframedocument.body.style.visibility = 'hidden';iframe.style.visibility = 'visible';iframe.style.position = 'fixed';iframe.style.top = '0';iframe.style.left = '0';iframe.style.width = '100%';iframe.style.height = '100%';// 触发打印window.print();// 恢复页面样式(打印完成后执行)setTimeout(() => {document.body.style = originalStyle;iframe.style = ''; // 恢复 iframe 原有样式}, 100);},
