vue 页面实现 本地预览 pdf png docx txt excel pptx等文件预览

  <iframe v-show="pdfbollean" id="iframe" :src="url2"   style="height: 570px" width="100%" frameborder="0"></iframe>
  <!-- png -->
  <div v-show="pngbollean" ><img :src="url" style="width:200px"/></div>
  <!-- txt -->
  <div v-show="txtbollean"><el-input type="textarea" :rows="10" v-model="txtPre" readonly></el-input></div>
  <!-- docx -->
  <div v-show="docxbollean" id="container" /> 
  <!-- xlsx -->
  <div v-show="xlsxbollean" ref="output" />
  <!-- pptx -->
 <iframe v-show="pptxbollean" id="iframe" :src="url3"   style="height: 570px" width="100%" frameborder="0"></iframe>

pdfbollean: false,
pngbollean: false,
txtbollean: false,
docxbollean: false,
xlsxbollean: false,
pptxbollean: false,
excelView:“”,
tableau:“”,
txtPre:“”,
url2: “http://localhost:8081/wendang/aaa.pdf”,
url3: “http://localhost:8081/wendang/aa.pptx”,
url: “http://localhost:8081/wendang/aa.png”,

handlepreview(row) {
this.dialogVisible = true
if (row.extendName == “pdf”) {
this.pdfbollean = true;
this.pngbollean = false;
this.txtbollean = false;
this.docxbollean = false;
this.xlsxbollean = false;
this.pptxbollean = false;
this.url2 = ‘http://localhost:8081’ + row.filePath;
}
if (row.extendName == “png”) {
this.pdfbollean = false;
this.pngbollean = true;
this.txtbollean = false;
this.docxbollean = false;
this.xlsxbollean = false;
this.pptxbollean = false;
this.url = ‘http://localhost:8081’ + row.filePath;
}
if (row.extendName == “txt”) {
this.pdfbollean = false;
this.pngbollean = false;
this.txtbollean = true;
this.docxbollean = false;
this.xlsxbollean = false;
this.pptxbollean = false;
//txt
let xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘http://localhost:8081’+row.filePath, false);// 文件路径
xhr.overrideMimeType(“text/html;charset=utf-8”);//默认为utf-8
xhr.send(null);
this.txtPre = xhr.responseText
//console.log(xhr.responseText); //打印文件信息
}
if (row.extendName == “docx”) {
this.pdfbollean = false;
this.pngbollean = false;
this.txtbollean = false;
this.docxbollean = true;
this.xlsxbollean = false;
this.pptxbollean = false;
this.docxPreview(‘http://localhost:8081’ + row.filePath);
}
if (row.extendName == “xlsx”) {
this.pdfbollean = false;
this.pngbollean = false;
this.txtbollean = false;
this.docxbollean = false;
this.xlsxbollean = true;
this.pptxbollean = false;
this.xlsxPreview(‘http://localhost:8081’ + row.filePath);
}
if (row.extendName == “pptx”) {

    //"D:\\202302\\301\\aa.pptx"
    var newPPT = row.filePath.split('.')[0]+".pdf"
    getFileBase64({
      pptPath: row.filePath,
      pdfPath: newPPT
      }).then((res) => {
        this.url3 = 'http://localhost:8081/wendang/202302/301/' + newPPT;

      })
      this.pdfbollean = false;
      this.pngbollean = false;
      this.txtbollean = false;
      this.docxbollean = false;
      this.xlsxbollean = false;
      this.pptxbollean = true;
  }

},
// 渲染docx
docxPreview(url) {
  // 获取文件流
  const xhr = new XMLHttpRequest()
  xhr.open('get', url, true)
  xhr.responseType = 'blob'
  xhr.onload = () => {
    if (xhr.status === 200) {
      console.log(xhr.response)
      let fr = new FileReader();
      fr.readAsArrayBuffer(xhr.response);
      fr.addEventListener("loadend",(e) => {
          console.log("loadend---->", e)
          let buffer = e.target.result;
          this.docxRender(buffer);
      }, false);
    }
  }
  xhr.send()
},
docxRender(buffer) {
    let bodyContainer = document.getElementById("container");
    renderAsync(
        buffer, // Blob | ArrayBuffer | Uint8Array, 可以是 JSZip.loadAsync 支持的任何类型
        bodyContainer, // HTMLElement 渲染文档内容的元素,
        null, // HTMLElement, 用于呈现文档样式、数字、字体的元素。如果为 null,则将使用 bodyContainer。
        this.docxOptions // 配置
    ).then(res => {
        console.log("res---->", res)
    })
},
// 渲染docx
xlsxPreview(url) {
  // 获取文件流
  const xhr = new XMLHttpRequest()
  xhr.open('get', url, true)
  xhr.responseType = 'blob'
  xhr.onload = () => {
    if (xhr.status === 200) {
      console.log(xhr.response)
      let fr = new FileReader();
      fr.readAsArrayBuffer(xhr.response);
      fr.addEventListener("loadend",(e) => {
          console.log("loadend---->", e)
          let buffer = e.target.result;
          this.displayResult(buffer);
      }, false);
    }
  }
  xhr.send()
},
// 嵌入式预览excel
displayResult(buffer) {
  // 生成新的dom
  const node = document.createElement('div')
  // 添加孩子,防止vue实例替换dom元素
  if (this.last) {
    this.$refs.output.removeChild(this.last.$el)
    this.last.$destroy()
  }
  const child = this.$refs.output.appendChild(node)
  // 调用渲染方法进行渲染
  return new Promise((resolve, reject) =>
    renderSheet(buffer, child).then(resolve).catch(reject)
  )
},

后台:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfig implements WebMvcConfigurer {
/*
*addResourceHandler:访问映射路径
*addResourceLocations:资源绝对路径
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/wendang/**”).addResourceLocations(“file:D:/”);
}
}

@RestController
@Slf4j
@RequestMapping(“/file2”)
public class base64 {

@GetMapping("/getFileBase64")
public String getFileBase64(@RequestParam("pptPath") String pptPath,
                            @RequestParam("pdfPath") String pdfPath){
    System.out.println(pptPath);
    System.out.println(pdfPath);
    ConvertUtil.ppt2Pdf("D:\\202302\\301\\"+pptPath, "D:\\202302\\301\\"+pdfPath);
    return pdfPath;
}

}

package com.bysj.backend.util;

import com.aspose.slides.License;
import com.aspose.slides.Presentation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ConvertUtil {

public static boolean getLicense() {
    boolean result = false;
    try {

        InputStream license = ConvertUtil.class.getClassLoader().getResourceAsStream("license.xml");
        com.aspose.slides.License aposeLic = new License();
        aposeLic.setLicense(license);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

// public static void main(String[] args){
// ppt2Pdf(“D:\202302\301\22.pptx”,“D:\202302\301\22.pdf”);
// }

public static boolean ppt2Pdf(String pptPath, String pdfPath) {
    /*
    Locale locale = new Locale("zh", "cn");
    Locale.setDefault(locale);
    */
    // 验证License
    if (!getLicense()) {
        return false;
    }
    FileOutputStream fileOS = null;
    try {
        File file = new File(pdfPath);
        Presentation pres = new Presentation(pptPath);
        fileOS = new FileOutputStream(file);
        pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        fileOS.close();
    } catch (Exception e) {
        if(fileOS != null) {
            try {
                fileOS.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        e.printStackTrace();
    }
    return true;
}

}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue应用中实现本地预览Word(.docx)、Excel(.xlsx)和PDF文件,你可以使用一些现有的库和插件。以下是一种常见的方法,使用`vue-pdf`、`xlsx`和`mammoth.js`库来实现此功能: 1. 首先,安装所需的库: ```bash npm install vue-pdf xlsx mammoth ``` 2. 创建一个Vue组件,并导入所需的库: ```vue <template> <div> <div v-if="fileType === 'pdf'"> <pdf :src="fileUrl" /> </div> <div v-else-if="fileType === 'xlsx'"> <div>{{ excelData }}</div> </div> <div v-else-if="fileType === 'docx'"> <div v-html="wordContent"></div> </div> </div> </template> <script> import { read, utils } from 'xlsx'; import mammoth from 'mammoth'; import { pdf } from 'vue-pdf'; export default { components: { pdf, }, data() { return { fileType: '', fileUrl: '', excelData: [], wordContent: '', }; }, mounted() { this.loadFile(); }, methods: { loadFile() { const file = 'path/to/your/file'; const extension = file.split('.').pop(); if (extension === 'pdf') { this.fileType = 'pdf'; this.fileUrl = file; } else if (extension === 'xlsx') { this.fileType = 'xlsx'; this.loadExcelFile(file); } else if (extension === 'docx') { this.fileType = 'docx'; this.loadWordFile(file); } }, loadExcelFile(file) { const reader = new FileReader(); reader.onload = (e) => { const data = new Uint8Array(e.target.result); const workbook = read(data, { type: 'array' }); const worksheet = workbook.Sheets[workbook.SheetNames[0]]; this.excelData = utils.sheet_to_json(worksheet, { header: 1 }); }; reader.readAsArrayBuffer(file); }, loadWordFile(file) { const reader = new FileReader(); reader.onload = (e) => { const arrayBuffer = e.target.result; const options = {}; mammoth.extractRawText({ arrayBuffer }, options) .then((result) => { this.wordContent = result.value; }) .catch((error) => { console.error(error); }); }; reader.readAsArrayBuffer(file); }, }, }; </script> ``` 在上面的代码中,你需要将`path/to/your/file`替换为实际文件的路径。根据文件的扩展名,组件将显示不同的预览方式。 请注意,该示例仅提供了一种基本实现方法。你可以根据自己的需求进行修改和调整。 希望这可以帮助到你!如果你有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值