前端实现文档预览(支持word、ppt、pdf)-【@zuiyouliao/vue-file-viewer】

背景#

有的时候我们需要在前端页面上预览某些文档,文档的格式比如:word、ppt、pdf、图片等等

实现方案#

可以使用@zuiyouliao/vue-file-viewer第三方库,官方地址

方式1:通过组件方式引入#

优点:word/图片可以识别,方便快捷。
缺点:pdf/pptx文件无法识别。

安装依赖#

npm install --save @zuiyouliao/vue-file-viewer

vue中使用#

<template>
  <div class="app">
    <vue-file-viewer :fileUrl="file" style="height: 500px" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      // file: 'https://home.me7.cn/fileTest/word.docx',
      // file: 'https://home.me7.cn/fileTest/pdf.pdf',
      // file: 'http://localhost:3000/public/ddd.pptx',
      file: 'http://localhost:3000/public/test.jpg',
    }
  },
}
</script>

<style lang="less" scoped></style>

方式2:通过iframe嵌入此库构建后的产物,通过链接的方式#

下载源码编译构建后的产物#

https://github.com/zyl-ui/vue-file-viewer/tree/master/public/file-viewer

将构建后的产物放在 public文件夹下。#

vue文件代码#

<template>
  <div class="app">
    <iframe
      src="./file-viewer/index.html?fileUrl=https://home.me7.cn/fileTest/pdf.pdf"
      scrolling="auto"
      style="border: 0; height: 500px; width: 100%"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {}
  },
}
</script>

<style lang="less" scoped></style>

效果#

总结#

推荐采用方式2,此方式通过iframe中嵌入构建后的html然后实现对文档的预览。

注意:在vue或者webpack项目中我们需要对这块构建后的html,使用复制插件将此内容复制到打包后的文件中。vue项目中`public`目录的内容会在打包的时候会原封不动的复制,但是在webpack项目的话你需要使用`copy-webpack-plugin`进行复制

posted @   ^Mao^  阅读(994)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
· DeepSeek本地性能调优
· 一文掌握DeepSeek本地部署+Page Assist浏览器插件+C#接口调用+局域网访问!全攻略
历史上的今天:
2021-08-07 TypeScript的基本使用(2)
2021-08-07 TypeScript的基本使用(1)
点击右上角即可分享
微信分享提示
主题色彩