前端使用 preview 插件预览docx文件

目录

    • 前言
      • [一 引入插件](#一 引入插件)
      • [二 JS 处理](#二 JS 处理)

前言

前端使用 preview 插件预览docx文件

一 引入插件

建议下载至本地,静态引入,核心的文件已打包(前端使用 preview 插件预览docx文件),在文章目录处下载至本地,复制在项目静态资源处,在使用的地方直接本地静态资源引入;

javascript 复制代码
<script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
<script src="https://unpkg.com/docx-preview/dist/docx-preview.min.js"></script>
<!-- 建议下载至本地,静态引入 -->
<script  src='/js/PreViewDoc/jszip.min.js'></script>
<script  src='/js/PreViewDoc/docx-preview.min.js'></script>

二 JS 处理

javascript 复制代码
var api = {
    init: function () {
        var that = this;
        laydate.render({
            elem: $('[name=StatisDate]').get(0)
            , type: 'month'
            , value: getLastMonth()
            , done: function (value, date, endDate) {
                if (date.year < new Date().getFullYear()) {
                    console.log(new Date().getFullYear());
                    RendergetZone(date.year);
                } else {
                    GetCurrZone();
                }
            }
        });
        $('#ReportNam').text(reportNam);
        form.render();
        that.event();
    },
    event: function () {
        var that = this;
        form.on('submit(report_query)', function (input) {
            // 禁用 "生成" 按钮
            const generateButton = $('[lay-submit]'); // 通过lay-submit获取按钮
            generateButton.addClass('layui-btn-disabled').attr('disabled', true); // 禁用按钮
            generateButton.html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop">' +
                '</i> 生成中'); // 修改按钮内容为 loading 动画
            const container = document.getElementById('doc-content'); // 渲染文档的容器
            //清空提示信息
            container.innerHTML = '';
            $.ajax({
                url: interface2021.ReportManagement.QueryWorkSimpleReport,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                data: JSON.stringify({
                    statisDate: input.field.StatisDate,
                    zoneCode: input.field.ZoneCd,
                    issuingUnit: input.field.IssuingUnit,
                    stageNumber: input.field.StageNumber,
                }),
                // xhrFields: {
                //     responseType: 'blob', // 接收文件流
                // },
                success: function (response) {
                    if (response.code === -1) {
                        container.innerHTML = "<p style='color: red;'>文档请求失败</p>";
                        relieveDisable(false,generateButton, '生成', response.message);
                    } else {
                        var fileProxyUrl = response.data;
                        fetch(fileProxyUrl)
                            .then((response) => response.blob())
                            .then((blob) => {
                                docx.renderAsync(blob, container)
                                    .then(() => {
                                        console.log('文档渲染成功');
                                        //恢复按钮
                                        relieveDisable(true,generateButton, '生成', response.message);
                                        // 获取下载按钮并设置属性
                                        const downloadButton = document.getElementById('download-btn');
                                        downloadButton.style.display = 'inline-block'; // 显示下载按钮
                                        downloadFile(downloadButton, response.data);
                                    })
                                    .catch((err) => {
                                        console.log('文档渲染失败', err);
                                        container.innerHTML = "<p style='color: red;'>文档请求失败</p>";
                                        relieveDisable(false,generateButton, '生成', err.message);
                                    });
                            })
                            .catch((error) => {
                                console.log('文件加载失败:', error);
                                relieveDisable(false,generateButton, '生成', error.message);
                            });
                    }

                },
                error: function (xhr, type, errorThrown) {
                    console.log('文档请求失败: ', errorThrown);
                    $('#doc-content').html('<p style="color: red;">文档请求失败</p>');
                    relieveDisable(false,generateButton, '生成', '生成失败!');
                },
            });

        });
    },
}

function downloadFile(downloadButton, downloadUrl) {
    // 启用 "下载" 按钮
    downloadButton.onclick = function () {
        console.log("开始下载...");
        const link = document.createElement('a');
        link.href = downloadUrl;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        console.log("下载完成");
    };
}
相关推荐
环境栈笔记2 分钟前
指纹浏览器安卓怎么用?从运行位置到功能验收,先把三种方案分清
前端·人工智能·后端·自动化
计算机魔术师20 分钟前
Anthropic IPO 招股文件披露近 9000 亿美元隐性债务
前端
Hello.Reader34 分钟前
Three.js / Cesium 卡顿怎么办?把三维渲染搬到 GPU 服务器
服务器·开发语言·javascript
chi113035 分钟前
【无标题】
前端·javascript·python
萝卜兔0081 小时前
PIKACHU_UnsafeFileUpload
javascript·php
IT_陈寒1 小时前
JavaScript实战技巧总结:深挖数组遍历的性能陷阱与实战解法
前端·人工智能·后端
步行cgn2 小时前
为什么既要 web.xml 又要 springmvc.xml?能不能只配一个?
xml·前端·hive
风骏时光牛马2 小时前
大模型综合能力评测:多维度性能与对齐效果对比
前端
winfredzhang2 小时前
从零手写一个毛玻璃风格的页面搭建台:单文件 HTML 实现组件放置、面板磁吸与图层管理
前端·html
葡萄城技术团队10 小时前
1000 人协同压测的环境瓶颈排查:CPU 争用与 Wi\-Fi
前端