Skip to content

Repository files navigation

@tauchun/docx-html-preview

一个可复用的 DOCX -> HTML 预览包,适用于 JavaScriptTypeScriptVue 工程。

@tauchun/docx-html-previewSuperHermes 项目中抽离了 DOCX XML 预览能力,对外提供与框架无关的 API,方便在工程化项目中直接通过 npm install 安装使用。

功能特性

  • 支持通过 npm install 直接安装
  • 支持 JavaScriptTypeScriptVue 项目复用
  • 支持 BlobFileArrayBufferUint8Array 作为输入
  • 同时提供“解析文档模型”和“直接挂载预览”两类 API
  • 内置基础样式文件 styles.css

安装

npm install @tauchun/docx-html-preview

API

parseDocx(input)

将 DOCX 二进制内容解析为标准文档模型:

import { parseDocx } from "@tauchun/docx-html-preview";

const parsed = await parseDocx(file);
console.log(parsed.document.blocks);
parsed.dispose();

renderToHtml(document, options?)

将解析后的文档模型渲染为 HTML 字符串:

import { parseDocx, renderToHtml } from "@tauchun/docx-html-preview";

const parsed = await parseDocx(file);
const html = renderToHtml(parsed.document);
parsed.dispose();

mountDocxPreview(container, input, options?)

直接把预览内容挂载到 DOM 容器:

import { mountDocxPreview } from "@tauchun/docx-html-preview";
import "@tauchun/docx-html-preview/styles.css";

const mounted = await mountDocxPreview(document.getElementById("preview")!, file);

// later
mounted.destroy();

使用示例

原生 JavaScript

<div id="preview"></div>
<script type="module">
  import { mountDocxPreview } from "@tauchun/docx-html-preview";
  import "@tauchun/docx-html-preview/styles.css";

  const input = document.querySelector("#docx");
  input.addEventListener("change", async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    await mountDocxPreview(document.getElementById("preview"), file);
  });
</script>

TypeScript

import { mountDocxPreview } from "@tauchun/docx-html-preview";
import "@tauchun/docx-html-preview/styles.css";

const container = document.querySelector<HTMLDivElement>("#preview");
if (container) {
  await mountDocxPreview(container, file);
}

Vue

<script setup lang="ts">
import { onBeforeUnmount, ref } from "vue";
import { mountDocxPreview, type MountedDocxPreview } from "@tauchun/docx-html-preview";
import "@tauchun/docx-html-preview/styles.css";

const host = ref<HTMLDivElement | null>(null);
let mounted: MountedDocxPreview | null = null;

async function preview(file: File) {
  if (!host.value) return;
  mounted?.destroy();
  mounted = await mountDocxPreview(host.value, file);
}

onBeforeUnmount(() => mounted?.destroy());
</script>

<template>
  <div ref="host" />
</template>

适用场景

  • 前端浏览器侧 DOCX 预览
  • 工程化项目中的附件预览、知识库文档预览、后台管理系统文档查看
  • 需要自定义外层交互,但不希望自己处理 DOCX XML 解析细节的场景

注意事项

  • 当前主要面向浏览器端预览场景
  • 复杂 VMLWPS 专有布局、部分高级浮动对象场景可能会降级展示,暂不承诺与 Word 完全像素级一致
  • 预览完成后,建议在合适时机调用返回对象上的 destroy()dispose(),以释放内部生成的对象 URL

License

MIT

About

Reusable DOCX to HTML preview package for JavaScript, TypeScript, and Vue projects.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages