UNPKG

react-mammoth

Version:

mammoth for React

123 lines (105 loc) 3.85 kB
<h1 align="center">react-mammoth</h1> <div> react-mammoth是为了更方便的在react组件中在线预览docx文档, 它基于mammoth.js,可以直接在react组件中使用。在内部下载了mammoth.browser.min.js,并且为mammoth库做了修改,添加了基础的字体颜色,大小,段落背景颜色等样式,以及对word中的图片,表格做了默认配置。 </div> ## Installation ```bash yarn add react-mammoth npm i react-mammoth ``` ## Using in React ```js import React, { useState } from "react"; import { createRoot } from "react-dom/client"; import Mammoth,{mammoth} from "react-mammoth"; const App = () => { const [file, setFile] = useState(null); const onChange = (e) => { const file = e.target.files[0]; setFile(file); }; return ( <div> <Mammoth file={file} //接收File类型文件或者Blob类型文件,组件内部会自动处理word文件 /> <input type="file" onChange={onChange}></input> </div> ); }; const container = document.getElementById("root"); const root = createRoot(container); root.render(<App />); ``` ## Properties 所有的props参数. - `file` 接收File类型文件或者Blob类型文件,组件内部会自动处理word文件,限制.doc或docx文件其他文件会保错 - `html` 直接传递给dangerouslySetInnerHTML._html属性,可以通过组件内部export的mammoth,手动去控制每一个细节.优先级高于file参数 - `options` mammoth.convertToHtml({ arrayBuffer: file }, options)方法的options配置项,默认为 ```js let transformParagraph = function (element) { // 单行占位,不分页时换行占位其实意义不大 if (element.children.length === 0) { element.children.push({ type: "run", children: [{ type: "text", value: "[占位符]" }], }); element.styleName = "blank-line"; return element; } return element; }; let options = { transformDocument: mammoth.transforms.paragraph(transformParagraph), styleMap: ["p[style-name='blank-line'] => p.blank-line:fresh"], convertImage: mammoth.images.imgElement(function (image) { // web支持显示的图片类型 let imgTypeAll = { "image/png": true, "image/gif": true, "image/jpeg": true, "image/svg+xml": true, "image/tiff": true, }; return image.read("base64").then(function (imageBuffer) { if (!imgTypeAll[image.contentType]) { // image.style += 'border:1px solid #eee;'; return ""; } return { src: "data:" + image.contentType + ";base64," + imageBuffer, }; }); }), includeEmbeddedStyleMap: true, includeDefaultStyleMap: true, }; ``` 设置options会在后面追加属性 ## Export - `Component` export default <Mammoth/>,你可以通过一下方式来使用 ```js import Mammoth from "react-mammoth"; ``` - `mammoth` export default <Mammoth/>,他提供了mammoth中所有属性, 你可以通过一下方式来使用,详情可以参考mammoth文档 ```js import {mammoth} from "react-mammoth"; export default ()=>{ const [html,useHtml] = useState('') useEffect(()=>{ mammoth .convertToHtml({ arrayBuffer: file }, options) .then(function (result) { useHtml(result.value); }) },[]) return <Mammoth html = {html} /> } ``` ## How to custom mammoth 作者目前也正在看,学习详情可以看以下文档[Custom Mammoth](https://blog.csdn.net/Jioho_chen/article/details/124699665). ## Suggestions for updates or feedback on issues email 603387530@qq.com