vue框架下前端实现docx、pdf、xlsx和pptx文件预览和下载

docx文件和xlsx文件 使用 VueOfficeDocx和VueOfficeExcel插件
pptx文件使用pptxjs
pdf文件使用iframe

a 首先安装插件

npm install @vue-office/docx vue-demi@0.14.6
npm install @vue-office/excel vue-demi@0.14.6

pptx预览需要引入pptxjs包:
官网下载包:
https://pptx.js.org/
将解压好的包放进项目public文件中,将index.html中body块文件修改为下面代码:

<body>
  <div id="result">div>
  <script>
    // 创建一个URL对象  
    const urlObj = new URL(window.location.href);
    // 获取查询参数对象  
    const params = new URLSearchParams(urlObj.search);
    // 获取pptUrl参数  
    const pptUrl = params.get('pptUrl');
    $("#result").pptxToHtml({
      pptxFileUrl: pptUrl,
      slidesScale: "100%",
      slideMode: false,
      keyBoardShortCut: false
    })
script>
body>

b 引入和使用

 <span @click="openFile(props.row, 0)">预览span>
 <span @click="openFile(props.row, 1)">下载span>
 <VueOfficeDocx :src="previewUrl" v-if="fileType === 'docx'"/>
 <VueOfficeExcel :src="previewUrl" v-else-if="fileType == 'xlsx'" />
 <iframe width="100%" height="100%" frameborder="0" :src="previewUrl" v-else-if="fileType == 'pdf'">iframe>
 <iframe id="iframe" :src="`/pptx/index.html?pptUrl=${previewUrl}`" width="100%" height="100%" frameborder="0"  v-else-if="fileType == 'pptx'">iframe>
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
export default {
  components: { VueOfficeDocx, VueOfficeExcel },
  data () {
    return {
      fileType: '',
      previewUrl: ''
    }
  },
  methods: {
    async openFile (row, type) {
      const result = await this.$$api.bis.get(`你的获取二进制文件的地址`, { responseType: 'blob' })
      this.fileType = row.name.split('.')[1]
      const blob = new Blob([result.data], { type: 'application/pdf' })
      const url = window.URL.createObjectURL(blob)
      if (type) {
        const link = document.createElement('a')
        link.href = url
        link.download = `${row.name}`
        link.click()
      } else {
        if (this.fileType === 'docx' || this.fileType === 'xlsx') {
          this.previewUrl = result.data
        } else {
          this.previewUrl = url
        }
        this.dialogs.preview.show = true
      }
    },
}

你可能感兴趣的:(vue,前端,vue.js,pdf)