先放个效果大图
需求描述:这个word文档在后端存着,需要获取它的流,然后实现一个预览这个word的功能,然后下载、打印。预览的时候,本来要预览doc,但是查了一些up,都说doc显示的话文档格式有问题之类的bug,就决定转换成pdf,再预览了。。。
第一步获取数据流
点击预览的时候,获取文档流,这个地方一定要用axios的原生模式,就是说不能封装,一个up主说的,我也没弄明白,大概意思是:封装后会有一些拦截什么的,会出现白屏。
previewHandle() {
let urlpath=`${process.env.VUE_APP_BASE_API}/templates/download/downLoadProtocolPdfFile?id=${this.uploadId}`
axios({ method: "GET",
headers: {
Authorization: "Bearer " + getToken(),
},
url: urlpath,//后端给的接口
responseType: "blob", // 更改responseType类型为 blob
})
.then((res) => {
const blob = new Blob([res.data], { type: "application/pdf" });
this.iframeUrls = window.URL.createObjectURL(blob);
// window.open(window.URL.createObjectURL(blob1));
this.wordDialogVisible = true;
})
.catch((err) => {
console.log(err);
});
},
第二步 显示
<!-- word预览 -->
<el-dialog title="预览" :modal="false" :close-on-click-modal="false"
:visible.sync="wordDialogVisible" class="wordDialog" width="70%" >
<div class="dialogtext">
//'#toolbar=0' 这个加上之后,原生pdf上面的下载,打印分页都不会显示
<iframe id="print" width="100%" height="550"
:src="iframeUrls + '#toolbar=0'"/>
</div>
<div slot="footer" style="display: flex; justify-content: center">
<el-button type="primary">下载</el-button>
<el-button type="success" @click="handleWindowPrint('print')">
打印</el-button>
<el-button type="info" @click="wordDialogVisible = false"
>关闭</el-button>
</div>
</el-dialog>
第三步 调起打印,获取iframe里面的内容
contentWindow.print,别人说有兼容性的问题,这个还没碰到
handleWindowPrint(id) {
//这里的id是print,id样式名称,
document.getElementById(id).contentWindow.print();
},