前端通过docx-preview和pdfjs插件实现docx、pdf文件在线预览

docx文件格式在线预览

插件:docx-preview

安装:

npm i docx-preview

使用:

创建一个容器标签

引入并创建渲染函数

import { renderAsync } from "docx-preview";
renderDocx() {
      renderAsync(this.fileData, this.$refs.file, null, {
        className: "docx", //默认和文档样式类的类名/前缀
        inWrapper: true, //启用围绕文档内容呈现包装器
        ignoreWidth: false, //禁用页面的渲染宽度
        ignoreHeight: false, //禁用页面的渲染高度
        ignoreFonts: false, //禁用字体渲染
        breakPages: true, //在分页符上启用分页
        ignoreLastRenderedPageBreak: true, //在lastRenderedPageBreak元素上禁用分页
        experimental: false, //启用实验功能(制表符停止计算)
        trimXmlDeclaration: true, //如果为true,则在解析之前将从xml文档中删除xml声明
        useBase64URL: false, //如果为true,图像、字体等将转换为base 64 URL,否则使用URL.createObjectURL
        useMathMLPolyfill: false, //包括用于铬、边等的MathML多填充。
        showChanges: false, //启用文档更改的实验渲染(插入/删除)
        debug: false, //启用额外的日志记录
      });
    }

PDF文件格式在线预览

插件:pdfjs

安装:

npm i pdfjs-dist

使用:

async renderPdf(num = 1) {
      this.fileData.getPage(num).then(page => {
        // 设置canvas相关的属性
        const canvas = document.getElementById("canvas_" + num);
        const ctx = canvas.getContext("2d");
        const dpr = window.devicePixelRatio || 1;
        const bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1;
        const ratio = dpr / bsr;
        const viewport = page.getViewport({ scale: this.pdfScale }); // 设置放缩比率
        canvas.width = viewport.width * ratio;
        canvas.height = viewport.height * ratio;
        canvas.style.width = viewport.width + "px";
        canvas.style.height = viewport.height + "px";
        ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
        const renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        };
        // 数据渲染到canvas画布上
        page.render(renderContext);
        if (this.numPages > num) {
          setTimeout(() => {
            return this.renderPdf(num + 1);
          });
        }
      });
    },

此处pdf的渲染数据this.fileData必须是一个ArrayBuffer格式的数据,如果请求的的数据是Blob格式必须要先使用Blob.arrayBuffer()转换

pdf的放大和缩小

// pdf放大
setPdfZoomin() {
  const max = 2;
  if (this.pdfScale >= max) {
    return;
  }
  this.pdfScale = this.pdfScale + 0.2;
  this.renderPdf();
},
// pdf缩小
setPdfZoomout() {
  const min = 0.6;
  if (this.pdfScale <= min) {
    return;
  }
  this.pdfScale = this.pdfScale - 0.1;
  this.renderPdf();
},

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