使用vue2实现word,pdf等的在线预览

目录

一. 查看word 

1. 引用mammoth

2. 页面

3. js

 二. 查看Excel

1. 引用sheetjs

2. 页面

2. JS

三. 汇总

1. 页面

2. JS

补充:vue移动端实现word在线预览

 1. 引用

2. 页面 


Excel文件预览

word文件预览

pdf文件预览 

一. 查看word 

1. 引用mammoth

安装 npm install --save mammoth

引入import mammoth from “mammoth”;

2. 页面

<div id="wordView" v-html="vHtml"/></div> 

3. js

data() {
  return {
    vHtml: "",
    wordURL:''  //文件地址,看你对应怎末获取、赋值
  };
},
created() {
  // 具体函数调用位置根据情况而定
  this.readExcelFromRemoteFile(this.wordURL);
}
methods:{
    // 在线查看word文件
    readExcelFromRemoteFile: function (url) {
      var vm = this;
      var xhr = new XMLHttpRequest();
      xhr.open("get", url, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function () {
        if (xhr.status == 200) {
          mammoth
            .convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) })
            .then(function (resultObject) {
              vm.$nextTick(() => {
                // document.querySelector("#wordView").innerHTML =
                //   resultObject.value;
                vm.vHtml = resultObject.value;
              });
            });
        }
      };
      xhr.send();
    },
}

 二. 查看Excel

1. 引用sheetjs

安装 npm install --save xlsx

 引入import XLSX from “xlsx”;

2. 页面

<!-- excel查看详情 -->
  <div id="table" v-if="!isWord">
    <el-table :data="excelData" style="width: 100%">
      <el-table-column
         v-for="(value, key, index) in excelData[2]"
         :key="index"
          :prop="key"
          :label="key"
      ></el-table-column>
     </el-table>
 </div>

2. JS

data() {
  return {
    excelData: [],
    workbook: {},
    excelURL: "", //文件地址,看你对应怎末获取、赋值
  };
},
created() {
  // 具体函数调用位置根据情况而定
  this.readWorkbookFromRemoteFile(this.wordURL);
}
methods:{
    // 在线查看excel文件
    readWorkbookFromRemoteFile: function (url) {
      var xhr = new XMLHttpRequest();
      xhr.open("get", url, true);
      xhr.responseType = "arraybuffer";
      let _this = this;
      xhr.onload = function (e) {
        if (xhr.status === 200) {
          var data = new Uint8Array(xhr.response);
          var workbook = XLSX.read(data, { type: "array" });
          console.log("workbook", workbook);
 
          var sheetNames = workbook.SheetNames; // 工作表名称集合
          _this.workbook = workbook;
          _this.getTable(sheetNames[0]);
        }
      };
      xhr.send();
    },
   getTable(sheetName) {
      console.log(sheetName);
      var worksheet = this.workbook.Sheets[sheetName];
      this.excelData = XLSX.utils.sheet_to_json(worksheet);
      console.log(this.excelData);
    },
}

三. 汇总

1. 页面

<el-dialog
      title="预览"
      append-to-body
      :visible.sync="dialog.dialogVisible"
    >
      <div :class="[checkClass]" class="check" />
      <div v-if="dialog.isPdf" v-loading="iframeLoading" class="pdfClass">
        <iframe
          :src="dialog.src"
          type="application/x-google-chrome-pdf"
        />
      </div>
      <!-- <div v-else-if="dialog.isExcel" class="excelClass" v-html="excelHtml" /> -->
      <div v-else-if="dialog.isExcel">
        <el-table
          :data="excelData"
          border
          stripe
          :header-cell-style="{'background':'#F5F4F7'}"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
            :resizable="false"
            align="center"
          />
          <el-table-column
            v-for="(value, key, index) in excelData[0]"
            :key="index"
            :prop="key"
            :label="key"
          />
        </el-table>
      </div>
      <div v-else-if="dialog.isWord" class="wordClass" v-html="wordHtml" />
      <div v-else class="imgfile">
        <img
          :src="dialog.src"
          alt=""
        >
      </div>
    </el-dialog>

2. JS

<script>
import { uploadFile, downloadFileByUniq, downloadFileByFileNames, downloadFileByUniq2 } from '@/base/api/common/'
import XLSX from 'xlsx'
import mammoth from 'mammoth'
export default {
data() {
    return {
      excelHtml: '',
      wordHtml: '',
      excelData: [],
    dialog: {
        dialogVisible: false,
        src: '',
        isPdf: false,
        isExcel: false,
        isWord: false
      },
}
methods: {
// 预览
    previewFn(item) {
      if (!(item.url.includes('.png') || item.url.includes('.jpg') || item.url.includes('.jpeg') || item.url.includes('.bmp') || item.url.includes('.JPG') || item.url.includes('.PNG') || item.url.includes('.JPEG') || item.url.includes('.BMP') || item.url.includes('.pdf') || item.url.includes('.txt') || item.url.includes('.xls') || item.url.includes('.doc'))) {
        this.$message.error('文件类型不支持预览')
        return false
      }
      if (item.url.includes('.pdf') || item.url.includes('.txt')) {
        this.dialog.isPdf = true
        this.dialog.isExcel = false
        this.dialog.isWord = false
        this.dialog.src = ''
        this.iframeLoading = true
        downloadFileByUniq(
          encodeURIComponent(item.url)
        ).then(res => {
          const blob = new Blob([res], { type: item.url.includes('.pdf') ? 'application/pdf;' : '' })
          const href = window.URL.createObjectURL(blob)
          this.dialog.src = href
        }).finally(() => {
          this.iframeLoading = false
        })
      } else if (item.url.includes('.xls')) {
        this.dialog.isExcel = true
        this.dialog.isWord = false
        this.dialog.isPdf = false
        downloadFileByUniq2(
          encodeURIComponent(item.url)
        ).then(data => {
          const workbook = XLSX.read(new Uint8Array(data), { type: 'array' }) // 解析数据
          var worksheet = workbook.Sheets[workbook.SheetNames[0]] // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
          // this.excelHtml = XLSX.utils.sheet_to_html(worksheet) // 渲染成html
          const sheet2JSONOpts = {
            /** Default value for null/undefined values */
            defval: ''// 给defval赋值为空的字符串,不然没值的这列就不显示
          }
          // 渲染成json
          this.excelData = XLSX.utils.sheet_to_json(worksheet, sheet2JSONOpts)
          console.log(this.excelData)
        })
      } else if (item.url.includes('.doc')) {
        var vm = this
        this.dialog.isWord = true
        this.dialog.isExcel = false
        this.dialog.isPdf = false
        downloadFileByUniq2(
          encodeURIComponent(item.url)
        ).then(data => {
          mammoth.convertToHtml({ arrayBuffer: new Uint8Array(data) })
            .then(function(resultObject) {
              vm.$nextTick(() => {
                vm.wordHtml = resultObject.value
              })
            })
        })
      } else {
        this.dialog.isPdf = false
        this.dialog.isExcel = false
        this.dialog.isWord = false
        this.dialog.src = item.downloadUrl
      }
      this.dialog.dialogVisible = true
      this.checkClass = 'check' + item.intinvoicestatus
    },}

补充:vue移动端实现word在线预览

 1. 引用

word预览同样要使用插件,这里使用的是mammoth插件,首先vue项目引入:

npm install mammoth

在预览的页面导入

import mammoth from ‘mammoth’

同样的也引用了手势缩放和移动,在我pdf预览那篇文章有说明手势的操作,使用的AlloyFinger 手势插件。

2. 页面 

<template>
  <div class="excel-container">
    <van-nav-bar
      left-text="返回"
      title="word查看"
      left-arrow
      :fixed="true"
      :placeholder="true"
      @click-left="back"
    />
    <div ref="docPreview"></div>
  </div>
</template>

3. JS

<script>
  import mammoth from 'mammoth'
  import AlloyFinger from "../../../static/js/alloyfinger.js";
  import transform from "../../../static/js/transform.js";
  import To from "../../../static/js/to.js";
  export default {
    data () {
      return {
        id: '',
        url:"",// excel文件地址
        goPath: '',       //将要去的界面
      }
    },
    beforeRouteEnter (to, from, next) { //监听从哪个页面过来
       let path = from.fullPath;
       next(vm => vm.setPath(path));
    },
    created(){
      this.getParams()
    },
    mounted () {
      this.previewFile();

      this.getData();
    },
    methods: {
      setPath(path) {
        this.goPath = path.split("/")[1];
      },
      //返回键
      back() {
        this.$router.push({
          name: this.goPath,
          params: {
            id: this.id
          }
        })
      },
      getParams() {
       // 取到路由带过来的参数
       let routerParams = this.$route.params.id
       // 将数据放在当前组件的数据内
       this.id = routerParams
       this.url = this.$route.params.url
      },
      previewFile() {
        let _this=this;
        try {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", this.url);
          xhr.responseType = "arraybuffer";
          xhr.onload = function(e) {
            var arrayBuffer = xhr.response; //arrayBuffer

            mammoth
              .convertToHtml({ arrayBuffer: arrayBuffer })
              .then(displayResult)
              .done();

            function displayResult(result) {
              _this.$refs.docPreview.innerHTML = result.value || "";
            }
          };
          xhr.send();
        } catch (e) {
          console.log(e);
          _this.$emit("errorPreview");
        }
      },
      getData() {
        let that = this;
        let element = that.$refs.docPreview;
        Transform(element);
        var initScale = 1;
        this.af = new AlloyFinger(element, {
          // rotate: function (evt) {  //实现旋转
          //   element.rotateZ += evt.angle;
          // },
          multipointStart: function () {
              initScale = element.scaleX;
          },
          pinch: function (evt) {   //实现缩放
            element.scaleX = element.scaleY = initScale * evt.zoom;
          },
          pressMove: function (evt) {   //实现移动
            element.translateX += evt.deltaX;
            element.translateY += evt.deltaY;
            evt.preventDefault();
          },
        });
      },
    }
  }
</script>

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue2中实现在线预览Word文档的方法如下: 1. 首先,你需要调取接口获取后端传回的Word文档流。这可以通过调用接口的方法来完成,接口返回的文档流通常存储在res.data.data中。你可以使用axios或其他HTTP请求库来发送请求并接收响应。 2. 在Vue模板中,你可以创建一个按钮,通过点击按钮来触发预览Word文档的操作。按钮可以使用Element UI库的el-button组件或其他自定义的按钮组件。在按钮的点击事件处理函数中,调用接口方法并将返回的文档流作为参数传递给渲染函数。 3. 在Vue组件中引入docx-preview库,并使用其提供的renderAsync方法来渲染Word文档。你可以在组件的script标签中通过require语法引入docx-preview库,并在方法中使用docxx.renderAsync方法来渲染文档。渲染函数需要传递两个参数,第一个参数是接口返回的文档流,第二个参数是一个DOM元素的引用,用于指定渲染文档的位置。 下面是一个示例代码,演示了如何在Vue2中实现在线预览Word文档: ```html <template> <div> <el-button @click="previewWord">预览Word文档</el-button> <div ref="wordContainer"></div> </div> </template> <script> import { getWordDocument } from "@/api/documents"; var docxx = require("docx-preview"); export default { methods: { previewWord() { getWordDocument() // 调用接口获取文档流 .then((res) => { docxx.renderAsync(res.data.data, this.$refs.wordContainer); }) .catch((error) => { this.$message.error(error); }); }, }, }; </script> ``` 请注意,上述示例代码中的getWordDocument方法是一个示例接口调用方法,你需要根据实际情况替换为适用于你的项目的接口调用方法。此外,你还需要根据实际情况对代码进行调整和修改。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [vue实现预览word文档(处理文档流)](https://blog.csdn.net/weixin_45294459/article/details/126997364)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [vue实现pdf文档在线预览功能](https://download.csdn.net/download/weixin_38590784/13681693)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暴怒的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值