Preserve QWord bookmarks in DOCX

This commit is contained in:
Курнат Андрей
2026-06-01 19:43:35 +03:00
parent fd2e03a44c
commit f22c7af88b
4 changed files with 86 additions and 10 deletions
+50 -8
View File
@@ -34,8 +34,8 @@ export interface WordImageBlock {
export type WordParagraphAlignment = "left" | "center" | "right" | "both";
export type WordBlock =
| { type: "heading"; level: 1 | 2; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment }
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment }
| { type: "heading"; level: 1 | 2; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; bookmark?: string }
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; bookmark?: string }
| { type: "list"; ordered: boolean; items: WordListItem[] }
| { type: "table"; rows: string[][] }
| WordImageBlock;
@@ -82,6 +82,7 @@ type DocxModule = {
};
Paragraph: new (options: Record<string, unknown>) => unknown;
PageBreak?: new () => unknown;
Bookmark?: new (options: { id: string; children: unknown[] }) => unknown;
Table: new (options: Record<string, unknown>) => unknown;
TableCell: new (options: Record<string, unknown>) => unknown;
TableRow: new (options: Record<string, unknown>) => unknown;
@@ -233,8 +234,16 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
const runs = elementInlineRuns(node);
const text = inlineRunsText(runs);
const alignment = paragraphAlignmentFromElement(node);
const bookmark = bookmarkFromElement(node);
if (text) {
blocks.push({ type: "heading", level: tagName === "h1" ? 1 : 2, text, runs, ...(alignment ? { alignment } : {}) });
blocks.push({
type: "heading",
level: tagName === "h1" ? 1 : 2,
text,
runs,
...(alignment ? { alignment } : {}),
...(bookmark ? { bookmark } : {})
});
}
return;
}
@@ -277,22 +286,24 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
if (block.type === "heading") {
const children = wordInlineRunsToTextRuns(block.runs, docx);
return [
new docx.Paragraph({
heading: block.level === 1 ? docx.HeadingLevel.HEADING_1 : docx.HeadingLevel.HEADING_2,
spacing: { after: 160 },
...docxAlignmentOption(block.alignment, docx),
children: wordInlineRunsToTextRuns(block.runs, docx)
children: bookmarkDocxChildren(block.bookmark, children, docx)
})
];
}
if (block.type === "paragraph") {
const children = wordInlineRunsToTextRuns(block.runs, docx);
return [
new docx.Paragraph({
spacing: { after: 160 },
...docxAlignmentOption(block.alignment, docx),
children: wordInlineRunsToTextRuns(block.runs, docx)
children: bookmarkDocxChildren(block.bookmark, children, docx)
})
];
}
@@ -416,6 +427,10 @@ function wordInlineRunsToTextRuns(runs: WordInlineRun[], docx: DocxModule) {
});
}
function bookmarkDocxChildren(bookmark: string | undefined, children: unknown[], docx: DocxModule) {
return bookmark && docx.Bookmark ? [new docx.Bookmark({ id: bookmark, children })] : children;
}
function wordInlineRunToTextRunsForRun(run: WordInlineRun, docx: DocxModule, optionOverrides: Record<string, unknown> = {}) {
const option = { ...wordInlineRunToTextRunOption(run), ...optionOverrides };
const text = String(option.text ?? "");
@@ -531,15 +546,24 @@ function tableRows(table: Element) {
function paragraphElementToBlocks(element: Element): WordBlock[] {
const segments = collectInlineSegments(Array.from(element.childNodes), {});
const alignment = paragraphAlignmentFromElement(element);
const bookmark = bookmarkFromElement(element);
const blocks: WordBlock[] = [];
let pendingRuns: WordInlineRun[] = [];
let bookmarkApplied = false;
const flushParagraph = () => {
const runs = normalizeInlineRuns(pendingRuns);
const text = inlineRunsText(runs);
const hasPageBreak = runs.some((run) => run.text.includes(pageBreakMarker));
if (text || hasPageBreak) {
blocks.push({ type: "paragraph", text, runs, ...(alignment ? { alignment } : {}) });
blocks.push({
type: "paragraph",
text,
runs,
...(alignment ? { alignment } : {}),
...(bookmark && !bookmarkApplied ? { bookmark } : {})
});
bookmarkApplied = true;
}
pendingRuns = [];
};
@@ -572,6 +596,10 @@ function paragraphAlignmentFromElement(element: Element): WordParagraphAlignment
return normalized === "justify" ? "both" : undefined;
}
function bookmarkFromElement(element: Element) {
return normalizedDocxAnchor(element.getAttribute("id") || element.getAttribute("name"));
}
function cssTextAlignValue(style: string) {
return /(?:^|;)\s*text-align\s*:\s*([^;]+)/i.exec(style)?.[1] ?? "";
}
@@ -674,6 +702,7 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
const result = orderedDocxDocumentToHtml(orderedParser.parse(documentXml), relationshipTargets.hyperlinks, imageDataByRelationshipId);
return result.hasInlineColorOrHighlight ||
result.hasParagraphAlignment ||
result.hasBookmark ||
result.hasTable ||
result.hasImage ||
result.hasLineBreak ||
@@ -699,6 +728,7 @@ function orderedDocxDocumentToHtml(
const body = firstOrderedElement(orderedElementChildren(document), "w:body");
let hasInlineColorOrHighlight = false;
let hasParagraphAlignment = false;
let hasBookmark = false;
let hasTable = false;
let hasImage = false;
let hasLineBreak = false;
@@ -711,6 +741,7 @@ function orderedDocxDocumentToHtml(
const result = orderedDocxParagraphToHtml(block, hyperlinkTargets, imageDataByRelationshipId);
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight;
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
hasBookmark = hasBookmark || result.hasBookmark;
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasPageBreak = hasPageBreak || result.hasPageBreak;
@@ -734,6 +765,7 @@ function orderedDocxDocumentToHtml(
html: blocks.join(""),
hasInlineColorOrHighlight,
hasParagraphAlignment,
hasBookmark,
hasTable,
hasImage,
hasLineBreak,
@@ -750,7 +782,9 @@ function orderedDocxParagraphToHtml(
const properties = orderedElementToRecord(firstOrderedElement(orderedElementChildren(paragraph), "w:pPr"));
const tagName = docxParagraphTagName(properties);
const style = docxParagraphStyleAttribute(properties);
const bookmark = orderedDocxParagraphBookmark(paragraph);
const hasParagraphAlignment = Boolean(style);
const hasBookmark = Boolean(bookmark);
let hasInlineColorOrHighlight = false;
let hasImage = false;
let hasLineBreak = false;
@@ -768,13 +802,16 @@ function orderedDocxParagraphToHtml(
const content = runs.join("");
if (!content.trim()) {
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak, hasPageBreak, hasTab };
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasBookmark, hasImage, hasLineBreak, hasPageBreak, hasTab };
}
const attributes = [style ? `style="${style}"` : "", bookmark ? `id="${escapeHtml(bookmark)}"` : ""].filter(Boolean).join(" ");
return {
html: `<${tagName}${style ? ` style="${style}"` : ""}>${content}</${tagName}>`,
html: `<${tagName}${attributes ? ` ${attributes}` : ""}>${content}</${tagName}>`,
hasInlineColorOrHighlight,
hasParagraphAlignment,
hasBookmark,
hasImage,
hasLineBreak,
hasPageBreak,
@@ -843,6 +880,11 @@ function docxParagraphStyleAttribute(properties: XmlRecord) {
return ["left", "center", "right", "justify"].includes(htmlAlignment) ? `text-align: ${htmlAlignment};` : "";
}
function orderedDocxParagraphBookmark(paragraph: unknown) {
const bookmarkStart = firstOrderedElement(orderedElementChildren(paragraph), "w:bookmarkStart");
return normalizedDocxAnchor(docxAttribute(orderedElementAttributes(bookmarkStart), "w:name") || docxAttribute(orderedElementAttributes(bookmarkStart), "name"));
}
function orderedDocxParagraphInlineRecords(paragraph: unknown, hyperlinkTargets: Record<string, string>) {
return orderedElementChildren(paragraph).flatMap<DocxInlineRecord>((child) => {
const name = orderedElementName(child);