vue 在线预览word

1 mammoth
先找的是mammoth这个插件yarn add mammoth,版本是1,7.0
参考网上的示例使用如下:

import mammoth from "mammoth";
const vHtml = ref("")
const readExcelFromRemoteFile = (url) =>{
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "arraybuffer";
    xhr.onload = function () {
    if (xhr.status == 200) {
        mammoth.convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) })
        .then(function (resultObject) {
            nextTick(() => {
            // document.querySelector("#wordView").innerHTML =
            //   resultObject.value;
            vHtml.value = resultObject.value;
            });
        });
    }
    };
    xhr.send();
}

在word中设置的样式是
1
因为这个图片是做了文字环绕,因此他识别不了.
1

在网页端显示的如下面:
1
2 docx-preview
docx-preview使用就不是很顺利

index:1 Uncaught (in promise) SyntaxError: The requested module '/psi/node_modules/.vite/deps/docx-preview.js?v=d111f2a1' does not provide an export named 'default'
jszip.min.js:13 Uncaught (in promise) Error: Can't read the data of 'the loaded zip file'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?
    at jszip.min.js:13
    at async Function.load (open-xml-package.ts:26)
    at async Function.load (word-document.ts:52)
    at async renderAsync (docx-preview.ts:56)

使用这个组件,要装两个依赖包

yarn add docx-preview

参考了vue3+typescript 预览docx文件,这是我的版本用的0.3.0,并不支持doc格式
1
但是docx则可以显示,文件上传的同时,直接就可以渲染出来。这个我喜欢。
参考代码如下

<template>
    <el-container>
        <el-aside width="250px">
            <el-header height="45px">
                <div class="nav">
                    <el-button type="primary">保存</el-button>
                </div>
            </el-header>
            <el-main>
                <el-form :model="dataForm"  label-suffix=":" label-position="top" style="margin-top: 10px;">
                    <el-form-item label="合同名称" prop="name">
                        <el-input v-model="dataForm.name" placeholder="请输入合同名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="合同模板" prop="tpl">
                       <sc-upload-file v-model="dataForm.tpl" :limit="1" drag :on-change="handleChange" :auto-upload="false">
                            <el-icon class="el-icon--upload"><el-icon-upload-filled /></el-icon>
                                <div class="el-upload__text">
                                拖拽到这 或<em>点击上传</em>
                                </div>
                        </sc-upload-file>
                    </el-form-item>
                    <el-form-item label="电子签章" prop="dzqz">
                       <sc-upload v-model="dataForm.dzqz" title="电子签章"></sc-upload>
                    </el-form-item>
                </el-form>
            </el-main>
        </el-aside>
        <el-main >
            <div ref="container" class="docx"></div>
        </el-main>
        <el-aside width="250px">
            <div class="header">可用的合同参数</div>
            <el-table :data="params" style="width: 100%;" border size="small" stripe highlightCurrentRow>
                <el-table-column prop="name" label="参数名称" align="left" ></el-table-column>
                <el-table-column prop="param" label="参数" align="left" ></el-table-column>
            </el-table>
        </el-aside>
    </el-container>
</template>
let container = ref();
const handleChange: UploadProps['onChange'] = (file: any) => {
    fileViews.value = file
    renderAsync(fileViews.value.raw, container.value, undefined, {
        className: "docx", // 默认和文档样式类的类名/前缀
        inWrapper: true, // 启用围绕文档内容渲染包装器
        ignoreWidth: false, // 禁止页面渲染宽度
        ignoreHeight: false, // 禁止页面渲染高度
        ignoreFonts: false, // 禁止字体渲染
        breakPages: true, // 在分页符上启用分页
        ignoreLastRenderedPageBreak: true, //禁用lastRenderedPageBreak元素的分页
        experimental: false, //启用实验性功能(制表符停止计算)
        trimXmlDeclaration: true, //如果为真,xml声明将在解析之前从xml文档中删除
        debug: false, // 启用额外的日志记录
    })
}

这个效果就比较好
1
接下来的问题,上面的代码是在文件上传的时候,直接预览word,保存之后,通过再打开这个合同模板,又是怎么加载出来呢?从下图可以看到word那部分是空白的。
1

const preview = (url) => {
    let xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status === 200) {
            renderAsync(xhr.response, dzhtRef.value);
        }
    };
    xhr.send();
}

async function load(val:string){
    const res = await proxy.$api.contract.psiContractTpl.load({id:val,asId:userInfo.value.currentAsId});
    if (res.success) {
        if (res.data){
            dataForm.value = res.data;
            nextTick(()=>{
                preview(dataForm.value.htFilePath);
            })
        }
    } else {
        proxy.$message.error(res.msg);
    }
}

这样就出来了
1

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现Vue在线预览Word远程文件,可以使用第三方库`docxtemplater`和`jszip`来处理Word文档,然后使用`FileSaver.js`库将处理后的文件下载到本地,最后使用`vue-doc-preview`插件进行在线预览。 具体步骤如下: 1. 安装依赖:`npm install docxtemplater jszip file-saver vue-doc-preview` 2. 在Vue组件中引入依赖: ```javascript import Docxtemplater from 'docxtemplater'; import JSZip from 'jszip'; import FileSaver from 'file-saver'; import VueDocPreview from 'vue-doc-preview'; ``` 3. 创建Vue组件,包含一个按钮和一个用于预览的`<doc-preview>`标签: ```html <template> <div> <button @click="previewDoc">预览Word文档</button> <doc-preview :file="previewFile" v-if="previewFile" /> </div> </template> ``` 4. 在Vue组件中定义`previewDoc`方法,该方法使用`axios`库获取远程Word文件,然后使用`docxtemplater`和`jszip`处理Word文档,并将处理后的文件下载到本地: ```javascript methods: { previewDoc() { axios.get('https://example.com/remote.docx', { responseType: 'arraybuffer' }).then(response => { const content = response.data; const zip = new JSZip(content); const doc = new Docxtemplater().loadZip(zip); doc.setData({...}); // 设置Word文档中的变量 doc.render(); const output = doc.getZip().generate({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); FileSaver.saveAs(output, 'preview.docx'); this.previewFile = 'preview.docx'; }); } } ``` 5. 在Vue组件中注册`VueDocPreview`插件: ```javascript export default { components: { DocPreview: VueDocPreview }, data() { return { previewFile: null } }, ... } ``` 6. 在Vue组件中引入CSS样式: ```javascript import 'vue-doc-preview/dist/style.css'; ``` 这样,当用户点击预览按钮时,会先获取远程Word文件,然后使用`docxtemplater`和`jszip`处理Word文档并下载到本地,最后使用`vue-doc-preview`插件进行在线预览

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

warrah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值