主要用到了mammoth这个插件,mammoth.js‌是一个JavaScript库,主要用于将Microsoft Word文档(.docx格式)转换为HTML。它可以通过Node.js环境使用,也可以直接在浏览器中使用。

关键代码:

import mammoth from 'mammoth';
import { useEffect, useState, useRef } from 'react';
import { Slider, Spin, Space } from 'antd';
import './index.global.less';
import { type } from 'os';
import { parse } from 'path';interface Props {filePath: string;type: string;screenFlag: string;isReadingMode: boolean;
}
// react中封装一个预览.doc和.docx文件的组件
const DocView: (props: Props) => JSX.Element = (props: Props) => {const [docDom, setDocDom] = useState(<Space size="large" className="icon-loading"><Spin size="large" /></Space>);const [textDom, setTextDom] = useState('');const [scale, setScale] = useState(180);const [warpClassName, setWarpclassName] = useState(['view-warper']);const textInput = useRef(null);const { filePath, type, screenFlag, isReadingMode } = props;const mOptions = {includeDefaultStyleMap: true,convertImage: mammoth.images.imgElement(function (image) {return image.read('base64').then(function (imageBuffer) {if (image.contentType === 'image/x-wmf') {return {}}return {src: 'data' + image.contentType + ';base64,' + imageBuffer,}});}),};useEffect(() => {return () => {setDocDom('');<Space size="large" className="icon-loading"><Spin size="large" /></Space>}}, []);// 引入全局样式类名(具体样式我就不展示了)useEffect(() => {const name = ['view-warper'];if (type === 'doc' || type === 'docx') {name.push('docx-warp');} else {name.push('text-warp');}if (screenFlag) {name.push('big-screen');}else {name.push('small-screen');}if (isReadingMode) {name.push('reading-mode');}else {name.push('normal-mode');}setWarpclassName(name);if (!screenFlag) {setScale(100);}}, [screenFlag, type, isReadingMode]);useEffect(() => {if (type === 'txt' && !textDom) {return false;}if (scale / 100 < 1) {textInput.current.style.transformOrigin = 'top center';} else {textInput.current.style.transformOrigin = 'left top';}}, [scale]);const handleScale = value => {setScale(value);};useEffect(() => {setDocDom(<Space size="large" className="icon-loading"><Spin size="large" /></Space>);if (!filePath) {return}if (type === 'txt') {// 以自己项目实际接口为准api.getDocumentDetailAfter(filePath).then((res: any) => {if (res) {setTextDom(res);}else {setTextDom('该文档没有任何内容');}textInput.current.style.transformOrigin = 'left top';}).catch((error: any) => {throw new Error(error);})}if (type === 'doc' || type === 'docx') {const jsonFile = new XMLHttpRequest();jsonFile.open('POST', '/xxx/xxx', true);jsonFile.setRequestHeader('Content-Type', 'application/json');jsonFile.send(filePath);jsonFile.responseType = 'arraybuffer';jsonFile.onreadystatechange = () => {if (jsonFile.readyState === 4 && jsonFile.status === 200) {mammoth.convertToHtml({ arrayBuffer: jsonFile.response },mOptions).then((result: any) => {setDocDom(parse(result.value));textInput.current.style.transformOrigin = 'left top';}).catch(a => {throw new Error(a);setDocDom(<div className="res-error"><p>无法查看此文档</p><p>请检查重新上传docx文件</p></div>);})} else if (jsonFile.status !== 200) {setDocDom(<div className="res-error"><p>网络超时,请稍后再试</p></div>);}}}}, [filePath]);return (<div className={warpClassName.join(' ')}>{(type === 'doc' || type === 'docx')&& <divid="docx"style={{ transform: `scale(${scale / 100})` }}className='docx-content'ref={textInput}>{docDom}</div>}{(type === 'txt')&& (textDom ? <textareaid="txt"className="txt-content"style={{ transform: `scale(${scale / 100})` }}ref={textInput}value={textDom}></textarea> : docDom)}{(type !== 'txt' && screenFlag)&& <div className="docx-footer"><div className="slider-warp"><aclassName="slider-icon more-icon"onClick={() => setScale(setScale(~~scale + 5))}/><SliderclassName="slider"min={0}max={100}defaultValue={100}onChange={handleScale}value={scale}tooltipVisible={false}/><a className="slider-icon less-icon" onClick={() => setScale(setScale(~~scale - 5))}></a></div></div>}</div>)}

index.global.less代码如下:

.view-warper {.icon-loading {align-items: center;justify-content: center;width: 100%;height: 100%;}.docx-warp {height: calc(100% - 40px);width: 100%;overflow: auto;}.res-error {padding: 108px 32px;height: 250px;transform: translate(0, 100%);position: relative;text-align-last: center;background: url(./error.png) top center no-repeat; // 注意项目图片路径p {text-indent: 0;margin-bottom: 0;}}#docx {height: 100%;padding: 10px;flex: 1;.res-error {padding: 108px 32px;height: 250px;transform: translate(0, 100%);position: relative;text-align-last: center;background: url(./error.png) top center no-repeat; // 注意项目图片路径p {text-indent: 0;margin-bottom: 0;}}img {max-width: 80%;display: flex;margin: 0 auto;}html {overflow-y: scroll;font-family: helvetica, arial, sans-serif;}body {margin: 0;padding: 0;}h3+p {margin-left: 40px;}h3+p+ul,h3+ol {margin-left: 40px;}h2+ul {margin-left: 60px;}h3+ol {margin-left: 60px;}.container {overflow: auto;max-width: 940px;margin: 0 auto;}.banner {overflow: auto;margin-bottom: 20px;background-color: #555;color: #fff;}.banner a {color: #fff;}.banner h1 {font-size: 20px;line-height: 2;margin: .5em 0;}.span8,.span4 {float: left;}.span8 {width: 620px;}.span4 {margin: 0 0 0 20px;}.well {background-color: #f2f2f2;border: 1px solid #ccc;padding: 1em;min-height: 200px;}.messages .warning {color: #c60;}li {list-style: decimal;margin-bottom: 10px;}p {margin-bottom: 10px;line-height: 25;text-indent: 60px;}p+ol {margin-left: 50px;}h1 {text-align: center;font-weight: bolder;font-size: 26px;margin: 20px 0;}::marker {color: blue;font-size: 1.2em;display: none;content: '';}ul {list-style: none;}strong {font-size: 24px;}h2 {padding-left: 30px;}table {border-collapse: collapse;margin: 24px auto;font-size: 0.9em;font-family: sans-serif;box-shadow: 0 0 20px rgba(0, 0, 0, .15);table-layout: fixed;width: 90%;strong {font-size: 12px;}}table td p {border-bottom: none;}table thead tr {background-color: #1ab394;color: #fff;text-align: left;}table li,table p {margin-bottom: 10px;margin-left: 0;border-bottom: 1px solid #e7e7e7;padding-bottom: 10px;padding-top: 15px;}table th,.styled-table td {padding: 12px 15px;}table tbody tr {border-bottom: 1px solid #ddd;}table tbody tr:last-of-type {border-bottom: 2px solid #1ab394;}table tbody tr.active-row {font-weight: bolder;color: #1ab394;}}.docx-footer {height: 40px;border-top: 1px solid gray;position: fixed;width: inherit;right: 424px;background: #fff;bottom: 0;.slider-warp {display: flex;align-items: center;margin-right: 25px;height: 40px;flex-direction: row-reverse;.slider {width: 80px;}.slider-icon {display: inline-block;width: 18px;height: 18px;background-position: top center;background-size: 100%;cursor: pointer;}.more-icon {background-image: url('./more.png');}.less-icon {background-image: url('./less.png');}}}.ant-slider-handle,.ant-slider-handle.ant-tooltip-open {border: 1px solid #2468f2;}.ant-slider-track {background-color: #2468f2;border-radius: 5px;z-index: 111;}.ant-slider-handle {z-index: 112;}.ant-slider-step {background-color: #91d5ff;z-index: 1;border-radius: 5px;}
}.text-warp {height: calc(100% - 60px);margin: 12px auto;text-align: center;.txt-content {padding: 10px;}textarea {width: 90%;height: 100%;border: none;resize: none;outline: none !important;overflow: auto;&:focus {border: none;outline: none !important;}}
}.docx-warp {height: calc(~'100% - 45px');background: #fff;margin: 12px auto 13px;overflow: auto;width: 93%;#docx {&>p:nth-child(2)>strong {font-size: 18px;}&>p:nth-child(3) {margin-top: 100px;text-align: center;}&>p:nth-child(4) {margin-bottom: 100px;text-align: center;}&>p:nth-child(5) {margin-bottom: 100px;text-align: center;}&>p>a {color: #333;text-align: center;}&>ul {li {margin-left: 0;}}&>h3 {margin: 20px 60px 20px;}}
}.normal-mode {width: 93%;.docx-footer {width: inherit;right: 424px;}
}.reading-mode {width: 98%;.docx-footer {left: 0;right: 0;width: 100%;}
}

基本上实现了查看word文档内容要求的展示内容,图片+文字说明的形式,代码可鞥有些冗余,还有需要优化的地方.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/903680.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/903680.shtml
英文地址,请注明出处:http://en.pswp.cn/news/903680.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

c#WebsocketSever

这是一个winFrom的小工具&#xff0c;用于再本机创建一个c#服务的项目。 1、将本机ip地址改为左上角Ip&#xff0c;注意没有“&#xff1a;”后的部分&#xff0c;那是端口号。 2、点击中间按钮&#xff0c;启动服务器 3、如果启动成功&#xff0c;会在下面显示启动成功&…

顶会招牌idea:机器学习+组合优化 优秀论文合集

2025深度学习发论文&模型涨点之——机器学习组合优化 机器学习&#xff08;ML&#xff09;与组合优化&#xff08;CO&#xff09;的交叉研究已成为运筹学与人工智能领域的前沿方向。传统组合优化方法&#xff08;如分支定界、动态规划&#xff09;虽在理论上有严格的性能保…

服务器硬件老化导致性能下降的排查与优化

随着企业数字化转型的深入&#xff0c;服务器作为IT基础设施的核心载体&#xff0c;其稳定性与性能直接影响业务连续性。然而&#xff0c;硬件老化导致的性能衰减问题普遍存在且易被忽视。本报告通过系统性分析服务器硬件老化现象&#xff0c;提出多维度排查方法与优化方案&…

删除k8s某命名空间,一直卡住了怎么办?

以 kubectl delete ns cert-manager 命令卡住为例&#xff0c;并且命名空间一直处于 Terminating 状态&#xff0c;说明 Kubernetes 无法完成删除操作&#xff0c;通常是因为 Finalizers 阻塞或某些资源无法正常清理。 解决方法 1. 检查命名空间状态 kubectl get ns cert-man…

【分享】变声器大师[特殊字符]乔碧萝同款变声[特殊字符]游戏变声[特殊字符]

多种变声器效果可选&#xff1a;爷爷、大叔、小孩、机器人...... 使用变声器时只需轻轻一点&#xff0c;让你成为潮人 【应用名称】&#xff1a;变声器大师 【应用版本】&#xff1a;6.1.35 【应用大小】&#xff1a;116M 【测试机型】&#xff1a;小米14 【下载链接】:https:…

【Part 2安卓原生360°VR播放器开发实战】第二节|基于等距圆柱投影方式实现全景视频渲染

《VR 360全景视频开发》专栏 将带你深入探索从全景视频制作到Unity眼镜端应用开发的全流程技术。专栏内容涵盖安卓原生VR播放器开发、Unity VR视频渲染与手势交互、360全景视频制作与优化&#xff0c;以及高分辨率视频性能优化等实战技巧。 &#x1f4dd; 希望通过这个专栏&am…

【JavaScript】相等运算符、条件运算符

1、相等运算符 &#xff08;1&#xff09;&#xff08;相等&#xff09; 相等运算符用来比较两个值是否相等&#xff0c;如果相等会返回true&#xff0c;否则返回false <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"…

OceanBase数据库-学习笔记5-用户

用户相关命令 命令描述CREATE USER ‘username’‘host’ IDENTIFIED BY ‘password’;创建用户。GRANT ALL PRIVILEGES ON database_name.* TO ‘test_user’‘%’;给用户授权所有权限。GRANT SELECT, INSERT, UPDATE ON database_name.* TO ‘test_user’‘%’;给用户授权指…

K8S Secret 快速开始

一、什么是 Secret&#xff1f; Kubernetes&#xff08;K8s&#xff09;中的 Secret 是一种用于存储和管理敏感信息&#xff08;如密码、令牌、证书、API 密钥等&#xff09;的资源对象。它避免了将敏感数据明文写入配置文件、镜像或代码中&#xff0c;提供了一种更安全的方式…

【分享】音频音乐剪辑[特殊字符]人声分离伴奏提取[特殊字符]拼接合并

音频音乐剪辑是一款专业的剪辑软件。在剪辑过程中&#xff0c;它可以对音频进行拼接合成、音乐裁剪、变调变速、格式转换&#xff0c;同时音频音乐剪辑还是一款支持高清录音、音频降噪等众多功能于一体的音频制作软件。 【应用名称】&#xff1a;音频剪辑 【应用版本】&#xf…

力扣-数据结构-二叉树

94. 二叉树的中序遍历 给定一个二叉树的根节点 root &#xff0c;返回 它的 中序 遍历 。 示例 1&#xff1a; 输入&#xff1a;root [1,null,2,3] 输出&#xff1a;[1,3,2]示例 2&#xff1a; 输入&#xff1a;root [] 输出&#xff1a;[]示例 3&#xff1a; 输入&#x…

oracle怎样通过固化较优执行计划来优化慢sql

一 问题描述 有次生产环境cpu使用率增高&#xff0c;ADDM报告提示某条sql比较耗费cpu&#xff1a; 提示&#xff1a; 在分析期间, 此 SQL 语句至少利用了 6 个不同的执行计划 #查看该sql都有哪些执行计划 SELECT * FROM table(DBMS_XPLAN.DISPLAY_AWR(sqlid值)); 我手动执…

基于c#,asp.net webform, sql server数据库,在线档案管理系统

详细视频: 【基于c#,asp.net webform, sql server数据库&#xff0c;在线档案管理系统包部署。-哔哩哔哩】 https://b23.tv/c1RsdRO

WebRTC SDK是什么?

​语音环境每年都在变&#xff0c;OKCC以前代理商的客群都是简单高效外呼为主&#xff0c;今年发现变化很大。很多代理商做的终端客户都是给其他业务系统赋能为主了。主流的还是以API对接为主&#xff0c;但是对接中发现webrtc SDK使用频率很高。 ​ ​那么什么是WebRTC SDK…

Vue3源码学习3-结合vitetest来实现mini-vue

文章目录 前言✅ 当前已实现模块汇总&#xff08;mini-vue&#xff09;✅ 每个模块简要源码摘要1. reactive.ts2. effect.ts3. computed.ts4. ref.ts5. toRef.ts6. toRefs.ts ✅ 下一阶段推荐目标所有核心模块对应的 __tests__ 测试文件&#xff0c;**带完整注释**✅ reactive.…

PH热榜 | 2025-04-30

1. Daytona 标语&#xff1a;安全且灵活的基础设施&#xff0c;用于运行你的人工智能生成的代码。 介绍&#xff1a;Daytona Cloud 为 AI 智能体重塑了基础设施&#xff0c;具备不到 90 毫秒的启动时间、原生性能以及有状态执行的能力&#xff0c;这些是传统云计算所无法实现…

Android compileSdkVersion、minSdkVersion、targetSdkVersion的关系以及和Unity的关系

compileSdkVersion、minSdkVersion、targetSdkVersion的关系 参考&#xff1a;https://mp.weixin.qq.com/s?__bizMzg5MzYxNTI5Mg&mid2247494238&idx1&sn06285667d3ac1339f6d2daae840cedc8&chksmc125565280f1ad3aa127774c2d1e59eb2818f89f0cb3ed4d72145faf619…

数据库的死锁相关(一)

目录 前言 一、什么死锁 二、产生死锁的必要条件 三、死锁发生的具体位置和场景 1. 数据行级别死锁&#xff08;最常见&#xff09; 2. 表级别死锁 3. 索引间隙锁死锁&#xff08;InnoDB特有&#xff09; 4. 外键约束死锁 5. 元数据锁死锁 6. 内存中的锁结构死锁 7.…

Three.js + React 实战系列-3D 个人主页:构建 Hero 场景组件(项目核心)✨

在本节中&#xff0c;我们将完成整个 3D 主业项目中最核心的组件 —— Hero.jsx。 这个组件作为首页的主视觉部分&#xff0c;整合了 3D 模型、动画相机、交互按钮与自适应布局&#xff0c;构建出一个立体、酷炫、可交互的主场景。 前置准备&#xff1a; ✅安装依赖&#xff…

Electron Forge【实战】桌面应用 —— 将项目配置保存到本地

最终效果 定义默认配置 src/initData.ts export const DEFAULT_CONFIG: AppConfig {language: "zh",fontSize: 14,providerConfigs: {}, };src/types.ts export interface AppConfig {language: zh | enfontSize: numberproviderConfigs: Record<string, Recor…