前端使用 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("下载完成");
    };
}
相关推荐
IT_陈寒2 分钟前
SpringBoot 3.0实战:这套配置让我轻松扛住百万并发,性能提升300%
前端·人工智能·后端
♡喜欢做梦3 分钟前
Spring Web MVC 入门秘籍:从概念到实践的快速通道(上)
前端·spring·mvc
Dragon Wu10 分钟前
Taro 自定义tab栏和自定义导航栏
前端·javascript·小程序·typescript·前端框架·taro
艾小码17 分钟前
2025年前端菜鸟自救指南:从零搭建专业开发环境
前端·javascript
namekong85 小时前
清理谷歌浏览器垃圾文件 Chrome “User Data”
前端·chrome
开发者小天6 小时前
调整为 dart-sass 支持的语法,将深度选择器/deep/调整为::v-deep
开发语言·前端·javascript·vue.js·uni-app·sass·1024程序员节
李少兄9 小时前
HTML 表单控件
前端·microsoft·html
学习笔记10110 小时前
第十五章认识Ajax(六)
前端·javascript·ajax
消失的旧时光-194310 小时前
Flutter 异步编程:Future 与 Stream 深度解析
android·前端·flutter
曹牧10 小时前
C# 中的 DateTime.Now.ToString() 方法支持多种预定义的格式字符
前端·c#