启明办公

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 65|回复: 1

vue 预览word,xlsx,pdf 文件

[复制链接]

1

主题

6

帖子

10

积分

新手上路

Rank: 1

积分
10
发表于 2022-12-31 11:36:29 | 显示全部楼层 |阅读模式
1.简单版本:url为文件下载地址,前提文件公共且公网

1.word官方预览链接(支持三种格式,部分word带特殊符号或流程图无法显示)

      const routeUrl = file.url; // 文件路径
      const url = encodeURIComponent(routeUrl);
      const officeUrl = "https://view.xdocin.com/view?src=" + url;
2.office官方预览(pdf不能展示)

let officeUrl = 'http://view.officeapps.live.com/op/view.aspx?src='+url
2.xlsx插件

想吃小鱼的猫:xlsx文件预览vue
1. npm i xlsx@0.16.0 --save  (注意版本)

只适合简单预览,效果不好看不推荐!


2.npm i luckyexcel

3.word插件

npm i docx-preview --save
<template>
  <div>
    <el-button @click="goPreview">点击预览word文件</el-button>
    <el-button @click="downLoad">点击下载word文件</el-button>
    <div class="docWrap">
      <!-- 预览文件的地方(用于渲染) -->
      <div ref="file"></div>
    </div>
  </div>
</template>

<script>
// 引入axios用来发请求
import axios from "axios";
// 引入docx-preview插件
let docx = require("docx-preview");
export default {
  mounted() {
    console.log("使用插件的renderAsync方法来渲染", docx); //
  },
  methods: {
    // 预览
    goPreview() {
      axios({
        method: "get",
        responseType: "blob", // 因为是流文件,所以要指定blob类型
        url: "http://ashuai.work:10000/getDoc", // 自己的服务器,提供的一个word下载文件接口
      }).then(({ data }) => {
        console.log(data); // 后端返回的是流文件
        docx.renderAsync(data, this.$refs.file); // 渲染到页面
      });
    },
    // 下载
    downLoad() {
      axios({
        method: "get",
        responseType: "blob", // 因为是流文件,所以要指定blob类型
        url: "", // 提供的一个word下载文件接口
      }).then(({ data }) => {
        console.log(data); // 后端返回的是流文件
        const blob = new Blob([data]); // 把得到的结果用流对象转一下
        var a = document.createElement("a"); //创建一个<a></a>标签
        a.href = URL.createObjectURL(blob); // 将流文件写入a标签的href属性值
        a.download = "出师表.docx"; //设置文件名
        a.style.display = "none"; // 障眼法藏起来a标签
        document.body.appendChild(a); // 将a标签追加到文档对象中
        a.click(); // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
        a.remove(); // 一次性的,用完就删除a标签
      });
    },
  },
};
</script>
<style lang="less" scoped>
.docWrap {
  // 指定样式宽度
  width: 900px;
  overflow-x: auto;
}
</style>

4.pdf预览

下载js文件:http://mozilla.github.io/pdf.js/getting_started/#download


<div style="height:800px;">
  <iframe :src="pdfSrc" width="100%" height="100%"></iframe>
</div>

getSeePdf(file){
      this.pdffile=file
      let routeUrl = '文件地址url';
      let pSrc = routeUrl + '?r=' + new Date();
      this.pdfSrc = 'static/pdf/web/viewer.html?file=' + encodeURIComponent(pSrc) + '.pdf';
    },
回复

使用道具 举报

1

主题

3

帖子

6

积分

新手上路

Rank: 1

积分
6
发表于 2025-3-6 16:29:20 | 显示全部楼层
锄禾日当午,发帖真辛苦。谁知坛中餐,帖帖皆辛苦!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|启明办公

Copyright © 2001-2013 Comsenz Inc.Template by Comsenz Inc.All Rights Reserved.

Powered by Discuz!X3.4

快速回复 返回顶部 返回列表