vue 如何预览pdf文件?
…
…
1. 使用 vue-pdf 插件
1.0 效果图
1.1 插件安装
yarn add vue-pdf
1.2 代码展示
html:
<template>
<div>
<pdf ref="pdf" v-for="i in numPages" :key="i" :page="i" :src="laoclUrl">></pdf>
</div>
</template>
<script>
import pdf from "vue-pdf";
export default {
name: "Home",
components: { pdf },
data() {
return {
numPages: 1, // pdf文件页数
laoclUrl: "" // 预览路径
};
},
mounted() {
this.previewPdf();
},
methods: {
// 简历预览
previewPdf() {
// pdf地址
let fileUrl = "http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf";
// 计算总页数
let loadingTask = pdf.createLoadingTask(fileUrl);
loadingTask.promise
.then(pdf => {
this.numPages = pdf.numPages;
})
.catch(err => {
console.error("pdf 加载失败", err);
});
this.laoclUrl = fileUrl;
}
}
};
</script>
2. 使用 PDF .js 插件
2.0 效果图
2.1 插件安装
yarn add pdfjs
2.2 简单封装组件
<template>
<div>
<iframe height="100%" width="100%" :src="`${getFilePath}`"></iframe>
</div>
</template>
<script>
export default {
name: "PDFJSViewer",
props: {
fileName: String,
path: String
},
computed: {
getFilePath: function() {
if (this.fileName !== "") {
return this.path + "?file=" + this.fileName;
}
return this.path;
}
}
};
</script>
2.3 使用组件
<template>
<div class="index_container full">
<PDFJSViewer :path="`${laoclUrl}`" :fileName="'pdf preview'" />
</div>
</template>
<script>
import PDFJSViewer from "/src/components/pdfViewer/pdfViewer";
export default {
name: "Home",
components: { PDFJSViewer },
data() {
return {
// 预览路径
laoclUrl: ""
};
},
mounted() {
this.previewPdf();
},
methods: {
// 简历预览
previewPdf() {
this.laoclUrl = "http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf";
}
}
};
</script>
3. 兼容word格式文件预览(.doc 、.docx)
发现在预览word文件时,会先弹窗一个下载弹窗,同时也会正常展示word文件。
但是对于一些需求来说,是不希望多出来一个弹窗的。该如何解决呢?
this.laoclUrl = "https://view.officeapps.live.com/op/view.aspx?src=你的word地址(必须是http/https的)";
参考地址: https://blog.youkuaiyun.com/qq_41312395/article/details/109450562