参考博客01(参考):Vue在线预览PDF(不需要安装插件)

参考博客02(推荐):vue+iframe预览pdf,页面显示pdf外框但是内容空白解决

最终实现方式为参考博客02

PdfPreview2.vue代码如下:

<template>
<div class="app">
<el-button @click="preview1">预览在线PDF</el-button>
<el-button @click="preview2">请求后端预览</el-button>
<el-dialog v-if="previewShow" title="预览" :visible.sync="previewShow" append-to-body width="90%">
<!-- PDF显示的地方 -->
<!-- <iframe ref="pdf" :src="previewUrl" width="100%"></iframe> -->
<iframe :src=previewUrl frameborder="0" height="900px" width="100%"></iframe>

<span slot="footer" class="dialog-footer">
<el-button type="primary" plain @click="previewShow = false">关 闭</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import { getToken } from "@/utils/auth";
import axios from "axios";

export default {
data() {
return {
previewShow: false,
previewUrl: "",
};
},
methods: {
// 直接传入一个地址
preview1() {
this.previewShow = true;
this.previewUrl = "https://www.gjtool.cn/pdfh5/git.pdf";
this.$nextTick(() => {
this.$refs.pdf.height = document.documentElement.clientHeight;
});
},
// 后端返回二进制流
preview2() {
this.previewShow = true;

axios({
method: 'get',
responseType: 'blob',
url: 'http://localhost:1024/dev-api/profile/upload/2023/07/07/TestDOCX_1688696521125_mark_20230707104114A001.pdf',//后端接口地址
headers: {
'Authorization': "Bearer " + getToken()
}
}).then(({ data }) => {
let blob = new Blob([data], { type: 'application/pdf' })
this.previewUrl = URL.createObjectURL(blob);
})


},
},
};
</script>
<style scoped></style>