前端预览docx格式文档

运用docx-preview.js(去网上下载https://github.com/VolodymyrBaydalka/docxjs/blob/master/dist/docx-preview.js)

引入脚本

<script
      type="text/javascript"
      src="https://unpkg.com/promise-polyfill/dist/polyfill.min.js"
    ></script>
    <!--lib uses jszip-->
    <script
      type="text/javascript"
      src="https://unpkg.com/jszip/dist/jszip.min.js"
    ></script>
    <script type="text/javascript" src="docx-preview.js"></script>

以流预览方法,动态创建

const docxOptions = Object.assign(docx.defaultOptions, {
        debug: true,
        experimental: true,
      });
            
var ajax = function (option) {
        var xhr = new XMLHttpRequest();
        xhr.open(option.type, option.url, option.async);
        xhr.responseType = option.dataType;
        xhr.onload = function (e) {
          if (this.status == 200) {
            option.success(this);
          }
        };
        xhr.onerror = function (ex) {
          option.error(ex);
        };
        xhr.send();
      };

function loadocx(url) { ajax({ type: "get", url: url, async: true, dataType: "blob", success: function (data) { data = data.response; var docEle = document.createElement("div"); docEle.id = "your-container"; document.body.append(docEle); var container = document.querySelector("#your-container"); docx.renderAsync(data, container, null, docxOptions).then((x) => { }); }, error: function (ex) { alert("error"); }, }); }

销毁的方法可以自己结合业务,remove节点就好了

 

posted @ 2023-06-02 11:01  你风致  阅读(1228)  评论(2编辑  收藏  举报