docx-html-converter
v0.5.13
Published
Convert DOCX to HTML with styles, tables, lists. WASM + Rust. Includes calculate_html for contentEditable page recalculation. Works in Node.js, React, Next.js, Vite.
Maintainers
Readme
docx-html-converter
Конвертер DOCX в HTML на Rust с поддержкой WASM. Преобразует документы Word в HTML с сохранением стилей, таблиц, списков, заголовков и колонтитулов. Верхний padding основного контента равен высоте зоны header (вычисляется после рендера колонтитулов).
Работает в Node.js, React, Next.js, Vite, Webpack.
Установка
npm install docx-html-converterИспользование
React / Next.js / Vite
import { convert_docx_embed, calculate_html } from "docx-html-converter";
function DocxViewer({ docxBuffer }) {
const embed = convert_docx_embed(docxBuffer);
return <div dangerouslySetInnerHTML={{ __html: embed }} />;
}
function DocxEditor({ docxBuffer }) {
const [html, setHtml] = useState(() => convert_docx_embed(docxBuffer));
const handleInput = (e) => {
const recalculated = calculate_html(e.currentTarget.innerHTML);
setHtml(recalculated);
};
return (
<div
contentEditable
onInput={handleInput}
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}Node.js
import { convert_docx, convert_docx_embed } from "docx-html-converter";
import fs from "fs";
const buffer = new Uint8Array(fs.readFileSync("document.docx"));
const html = convert_docx(buffer);
fs.writeFileSync("output.html", html);Express.js API
import express from "express";
import { convert_docx_embed } from "docx-html-converter";
const app = express();
app.post(
"/api/docx-to-html",
express.raw({
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
limit: "50mb",
}),
(req, res) => {
const html = convert_docx_embed(new Uint8Array(req.body));
res.type("text/html").send(html);
},
);const container = document.getElementById('editor'); container.innerHTML = embed;
// Для пересчёта страниц нужен полный HTML: обёртка docx-html-embed + стили + страницы container.addEventListener('input', () => { const htmlForRecalc = getHtmlForRecalculate(container); const recalculated = calculate_html(htmlForRecalc); container.innerHTML = recalculated; });
/**
- Возвращает HTML, готовый для calculate_html.
- Нужен полный фрагмент: div.docx-html-embed + + страницы.
- container — либо сам embed, либо родитель (например #editor). */ function getHtmlForRecalculate(container: HTMLElement): string { const embed = container.closest?.('.docx-html-embed') ?? container.querySelector?.('.docx-html-embed') ?? container; return embed.outerHTML; }
## Сборка и запуск
### DOCX → HTML (Rust)
```bash
cargo run # выбор .docx из src/files/
cargo run -- file.docx # указать файлHTML → DOCX
# Сначала: npm install в packages/html-docx-converter
cd packages/html-docx-converter && npm install && cd ../..
cargo run -- to-docx # выбор .html из списка
cargo run -- to-docx output-embed.html # указать файлРезультат сохраняется в packages/html-docx-converter/files/docx_results/.
npm (Node.js)
# Для bundler (webpack, vite и т.д.)
npm run build
# Для Node.js
npm run build:nodeRust
Библиотека также доступна как Rust crate:
use docx_html_converter::{convert_docx_from_bytes, convert_docx_embed_from_bytes, calculate_html};
let html = convert_docx_from_bytes(&docx_bytes, false, false)?;
let embed = convert_docx_embed_from_bytes(&docx_bytes, false, false)?;
// With debug layout (bright borders: red=page, green=content, blue=header, orange=footer, magenta=table):
let embed_debug = convert_docx_embed_from_bytes(&docx_bytes, false, true)?;
let recalculated = calculate_html(&embed)?;Changelog
0.4.4
- Исправлена вёрстка embed: BOM (U+FEFF) в header/footer больше не создаёт пустые span и не вызывает наезд header на page-content.
