UNPKG

react-mammoth

Version:

mammoth for React

74 lines 2.97 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; /** * doc文件预览 */ import * as React from "react"; import * as mammoth from "../../public/mammoth.browser.min.js"; import "./index.css"; var DocViewer = function (props) { var _a = props.html, html = _a === void 0 ? "" : _a, file = props.file, _b = props.options, options = _b === void 0 ? {} : _b; var _c = React.useState(""), code = _c[0], setCode = _c[1]; var readFile = function (file) { var 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; }; var option = __assign({ transformDocument: mammoth.transforms.paragraph(transformParagraph), styleMap: ["p[style-name='blank-line'] => p.blank-line:fresh"], convertImage: mammoth.images.imgElement(function (image) { // web支持显示的图片类型 var 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); mammoth .convertToHtml({ arrayBuffer: file }, option) .then(function (result) { setCode(result.value); }) .catch(function (err) { console.error("文件损坏,或包含不支持的内容格式!"); console.error(err); }) .done(); }; React.useEffect(function () { if (file) { readFile(file); } }, [file]); return (React.createElement("div", { className: "react-mammoth-box", dangerouslySetInnerHTML: { __html: html || code, } })); }; export default DocViewer; //# sourceMappingURL=index.js.map