vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue文件在线预览

Vue使用pdf.js和docx-preview实现docx和pdf的在线预览

作者:当new作码

这篇文章主要为大家详细介绍了在Vue中使用pdf.js和docx-preview实现docx和pdf的在线预览的相关知识,文中的示例代码讲解详细,需要的可以参考下

后端代码:

        SshConfig sshConfig = new SshConfig("ip", port, "username", "password");
        ChannelSftp channelSftp = sshConfig.getChannelSftp();
 
        String downUrl = "/**/**/";//服务器相对路径
        String pathname1 = downUrl + fileId + ".docx";
        String pathname2 = downUrl + fileId + ".pdf";
 
        InputStream inputStream1 = null;
        InputStream inputStream2 = null;
 
       //文件可能是docx或者pdf,因此需要分别尝试获取文件输入流
        try {
            inputStream1 = channelSftp.get(pathname1);
        } catch (SftpException e) {
            inputStream2 = channelSftp.get(pathname2);
        }
 
        byte[] buffer = new byte[1024];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        if (inputStream1 != null) {
            while ((bytesRead = inputStream1.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            byte[] fileBytes1 = output.toByteArray();
            // 现在fileBytes中包含了远程文件的字节流
            if (fileBytes1 != null) {
                channelSftp.disconnect();
                sshConfig.disconnect();
                // Convert the file to base64
                String base64 = Base64.getEncoder().encodeToString(fileBytes1);
                map.put("fileUrl", pathname1);
                map.put("base64", base64);
                return map;
            }
        } else {
            while ((bytesRead = inputStream2.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            byte[] fileBytes1 = output.toByteArray();
            // 现在fileBytes中包含了远程文件的字节流
            if (fileBytes1 != null) {
                channelSftp.disconnect();
                sshConfig.disconnect();
                // Convert the file to base64
                String base64 = Base64.getEncoder().encodeToString(fileBytes1);
                map.put("fileUrl", pathname2);
                map.put("base64", base64);
                return map;
            }
        }
 
        return map;

前端代码:

mounted方法中判断使用哪一个插件 

  mounted() {
    let fileUrl = sessionStorage.getItem("fileUrl");
    if (fileUrl.indexOf('.docx') !== -1) {
      let bstr = sessionStorage.getItem("bstr");
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      console.log("docx");
      //u8arr.buffer 转成arrayBuffer类型
      this.docxRender(u8arr.buffer, this.title);
    } else {
      let bstr = sessionStorage.getItem("bstr");
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      this.pdfData = u8arr;
      console.log("pdf");
      this.pdfReader(u8arr);
    }
 
  },

docx文件的渲染

    //渲染docx
    docxRender(buffer, fileName) {
      let box = document.createElement('div')  // 创建一个div
      let docx = require("docx-preview")
      docx.renderAsync(buffer, box).then(() => {  // 渲染文件
        let zhengwen = document.getElementById('zhengwen');
        zhengwen.appendChild(box);
        //document.write(box.outerHTML);
        //渲染文件后将div添加到新窗口中,div不能提前添加,否则新窗口中不能渲染出文件
        //注意这里不能直接用box
        document.title = fileName // 窗口标题
        document.getElementsByClassName('docx')[0].style.width = 'auto'
        // 如果文件显示正常,不用设置宽度
      }).catch(function () {
        Message({
          type: "error",
          message: "该文档可能已损坏,请尝试下载查阅"
        })
      })
    },

渲染效果图:

pfd文件渲染:

    //渲染pdf
    pdfReader(u8arr) {
      // 获取PDF容器元素
      let container = this.$refs.pdfContainer;
 
      // 配置PDFJS worker路径
      pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js';
      // 加载PDF文件流
      pdfjsLib.getDocument(u8arr).promise.then((pdf) => {
        // 获取页面数量
        const numPages = pdf.numPages;
        // 循环遍历所有页面
        for (let i = 1; i <= numPages; i++) {
          pdf.getPage(i).then((page) => {
            // 设置缩放比例
            const scale = 1.7;
            // 获取渲染上下文
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            // 计算画布大小
            const viewport = page.getViewport({scale});
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            // 将PDF页面渲染到画布上
            const renderContext = {
              canvasContext: ctx,
              viewport: viewport
            };
            page.render(renderContext);
            // 添加画布到容器中
            container.appendChild(canvas);
          });
        }
      }).catch(function () {
        Message({
          type: "error",
          message: "该文档可能已损坏,请尝试下载查阅"
        })
      });
    },

注意,使用前需要下载相应的库,docx-preview工具不适用于渲染doc文件,需要自己去转换文件类型(比如直接修改文件后缀名)

npm install pdfjs-dist
npm install docx-preview

以上就是Vue使用pdf.js和docx-preview实现docx和pdf的在线预览的详细内容,更多关于Vue文件在线预览的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文