
vue项目实现在线文档预览效果:Office、PDF、Word等格式一网打尽
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue

·
在项目中遇到过一个实际需求,需要能够预览office、pdf、word等在线文件,要是让我们自己手写完全没一点思路,不过好在优秀的开源插件@vue-office/docx,@vue-office/excel,@vue-office/pdf直接就帮我们高效的实现了,让在线预览变得如此简单,话不多说我们开始学习如何在项目中使用这些插件帮我们完成需求点。
实现在线文档预览我们需要准备下面这些:
1、首先了解需求需要安装所需要的插件
npm安装
npm install @vue-office/docx @vue-office/excel @vue-office/pdf --save
yarn安装
yarn add @vue-office/docx @vue-office/excel @vue-office/pdf
2、文档插件通过加载文档的URL或文件路径来获取文档内容,并在网页上进行渲染和展示。
<template>
<div class="wrap">
<NavBar></NavBar>
<van-loading v-if="loading" size="24px">加载中...</van-loading>
<vue-office-docx v-if="fileType === 'docx' || fileType === 'doc'" :src="filePath" style="height: 100vh"
@rendered="rendered" @error="HandlError"></vue-office-docx>
<vue-office-pdf v-if="fileType === 'pdf'" :src="filePath" style="height: 100vh" @rendered="rendered"
@error="HandlError"></vue-office-pdf>
<vue-office-excel v-if="fileType === 'xlsx' || fileType === 'xls'" :src="filePath" style="height: 100vh"
@rendered="rendered" @error="HandlError"></vue-office-excel>
<!-- 签名 -->
</div>
</template>
<script>
import VueOfficeDocx from "@vue-office/docx";
import VueOfficeExcel from "@vue-office/excel";
import VueOfficePdf from "@vue-office/pdf";
//引入相关样式
import "@vue-office/docx/lib/index.css";
export default {
data() {
return {
loading: true,
info: {},
filePath: "", // 预览地址
fileType: "", // 文件类型
baseUrl: process.env.VUE_APP_BASE_URL + "/graphicDoc/preview?dir=",
};
},
components: {
NavBar: () => import("@/components/NavBar"),
VueOfficeDocx,
VueOfficeExcel,
VueOfficePdf,
},
created() {
this.info = JSON.parse(decodeURIComponent(this.$route.query.info));
this.filePath = this.baseUrl + this.info.filePath;
this.fileType = this.info.fileType;
console.log(this.info);
},
methods: {
/* pdf,word组件渲染完毕 */
rendered() {
this.loading = false;
},
/* pdf,word组件渲染出错 */
HandlError(errorInfo) {
this.$toast("该文件暂不支持在线预览");
this.loading = false;
},
},
};
</script>
<style scoped lang="scss">
.wrap {
width: 100vw;
height: 100vh;
padding: 40px 0 0 0;
.content {
white-space: pre;
width: 100%;
height: 100%;
padding: 20px 10px;
background: #fff;
overflow-x: auto;
}
.van-loading {
background-color: #fff;
position: absolute;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
}
</style>
3、最关键的一步,千万不要忘记引入css样式了,不然文档可能无法正常预览哦
import "@vue-office/docx/lib/index.css";
这样就轻松解决了在线文档预览的需求了。




vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:6 个月前 )
9e887079
[skip ci] 5 个月前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 8 个月前
更多推荐
所有评论(0)