Preserve QWord paragraph spacing in DOCX

This commit is contained in:
Курнат Андрей
2026-06-02 08:03:03 +03:00
parent f5ab0448c7
commit f15467b8a1
4 changed files with 118 additions and 8 deletions
+74 -6
View File
@@ -41,11 +41,34 @@ export interface WordParagraphIndent {
hanging?: number;
}
export interface WordParagraphSpacing {
before?: number;
after?: number;
}
export type WordHeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
export type WordBlock =
| { type: "heading"; level: WordHeadingLevel; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; indent?: WordParagraphIndent; bookmark?: string }
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; indent?: WordParagraphIndent; bookmark?: string; quote?: boolean }
| {
type: "heading";
level: WordHeadingLevel;
text: string;
runs: WordInlineRun[];
alignment?: WordParagraphAlignment;
indent?: WordParagraphIndent;
spacing?: WordParagraphSpacing;
bookmark?: string;
}
| {
type: "paragraph";
text: string;
runs: WordInlineRun[];
alignment?: WordParagraphAlignment;
indent?: WordParagraphIndent;
spacing?: WordParagraphSpacing;
bookmark?: string;
quote?: boolean;
}
| { type: "list"; ordered: boolean; items: WordListItem[] }
| { type: "table"; rows: string[][] }
| WordImageBlock;
@@ -104,6 +127,8 @@ type DocxModule = {
ImageRun?: new (options: Record<string, unknown>) => unknown;
};
const defaultParagraphSpacingAfterTwips = 160;
type InlineFormat = Omit<WordInlineRun, "text">;
type InlineSegment = { type: "runs"; runs: WordInlineRun[] } | { type: "image"; image: WordImageBlock };
type DocxInlineRecord = { run: unknown; text: string; href?: string };
@@ -251,6 +276,7 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
const text = inlineRunsText(runs);
const alignment = paragraphAlignmentFromElement(node);
const indent = paragraphIndentFromElement(node);
const spacing = paragraphSpacingFromElement(node);
const bookmark = bookmarkFromElement(node);
if (text) {
blocks.push({
@@ -260,6 +286,7 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
runs,
...(alignment ? { alignment } : {}),
...(indent ? { indent } : {}),
...(spacing ? { spacing } : {}),
...(bookmark ? { bookmark } : {})
});
}
@@ -308,7 +335,7 @@ function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
return [
new docx.Paragraph({
heading: docxHeadingLevel(block.level, docx),
spacing: { after: 160 },
spacing: docxParagraphSpacing(block.spacing, defaultParagraphSpacingAfterTwips),
...docxAlignmentOption(block.alignment, docx),
...docxIndentOption(block.indent),
children: bookmarkDocxChildren(block.bookmark, children, docx)
@@ -321,7 +348,7 @@ function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
return [
new docx.Paragraph({
...(block.quote ? { style: "Quote" } : {}),
spacing: { after: 160 },
spacing: docxParagraphSpacing(block.spacing, defaultParagraphSpacingAfterTwips),
...docxAlignmentOption(block.alignment, docx),
...docxIndentOption(block.indent),
children: bookmarkDocxChildren(block.bookmark, children, docx)
@@ -525,6 +552,23 @@ function docxIndentOption(indent: WordParagraphIndent | undefined) {
return Object.keys(normalized).length > 0 ? { indent: normalized } : {};
}
function docxParagraphSpacing(spacing: WordParagraphSpacing | undefined, defaultAfter: number) {
const normalized = normalizedParagraphSpacing(spacing);
return {
after: normalized.after ?? defaultAfter,
...(normalized.before ? { before: normalized.before } : {})
};
}
function normalizedParagraphSpacing(spacing: WordParagraphSpacing | undefined) {
const before = normalizedTwips(spacing?.before);
const after = normalizedTwips(spacing?.after);
return {
...(before ? { before } : {}),
...(after !== undefined ? { after } : {})
};
}
function normalizedParagraphIndent(indent: WordParagraphIndent | undefined) {
const left = normalizedTwips(indent?.left);
const firstLine = normalizedTwips(indent?.firstLine);
@@ -602,6 +646,7 @@ function paragraphElementToBlocks(element: Element, options: { quote?: boolean }
const segments = collectInlineSegments(Array.from(element.childNodes), {});
const alignment = paragraphAlignmentFromElement(element);
const indent = paragraphIndentFromElement(element);
const spacing = paragraphSpacingFromElement(element);
const bookmark = bookmarkFromElement(element);
const blocks: WordBlock[] = [];
let pendingRuns: WordInlineRun[] = [];
@@ -618,6 +663,7 @@ function paragraphElementToBlocks(element: Element, options: { quote?: boolean }
runs,
...(alignment ? { alignment } : {}),
...(indent ? { indent } : {}),
...(spacing ? { spacing } : {}),
...(bookmark && !bookmarkApplied ? { bookmark } : {}),
...(options.quote ? { quote: true } : {})
});
@@ -666,6 +712,17 @@ function paragraphIndentFromElement(element: Element): WordParagraphIndent | und
return Object.keys(indent).length > 0 ? indent : undefined;
}
function paragraphSpacingFromElement(element: Element): WordParagraphSpacing | undefined {
const style = element.getAttribute("style") ?? "";
const before = cssTwipsValue(style, "margin-top");
const after = cssTwipsValue(style, "margin-bottom");
const spacing = {
...(before && before > 0 ? { before } : {}),
...(after && after > 0 ? { after } : {})
};
return Object.keys(spacing).length > 0 ? spacing : undefined;
}
function bookmarkFromElement(element: Element) {
return normalizedDocxAnchor(element.getAttribute("id") || element.getAttribute("name"));
}
@@ -674,7 +731,7 @@ function cssTextAlignValue(style: string) {
return /(?:^|;)\s*text-align\s*:\s*([^;]+)/i.exec(style)?.[1] ?? "";
}
function cssTwipsValue(style: string, property: "margin-left" | "text-indent") {
function cssTwipsValue(style: string, property: "margin-left" | "margin-top" | "margin-bottom" | "text-indent") {
const raw = new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]+)`, "i").exec(style)?.[1]?.trim().toLowerCase() ?? "";
return cssLengthToTwips(raw);
}
@@ -1069,7 +1126,8 @@ function docxParagraphStyleAttribute(properties: XmlRecord) {
const htmlAlignment = alignment === "both" ? "justify" : alignment;
const styles = [
["left", "center", "right", "justify"].includes(htmlAlignment) ? `text-align: ${htmlAlignment};` : "",
...docxParagraphIndentStyles(properties)
...docxParagraphIndentStyles(properties),
...docxParagraphSpacingStyles(properties)
].filter(Boolean);
return styles.join(" ");
}
@@ -1086,6 +1144,16 @@ function docxParagraphIndentStyles(properties: XmlRecord) {
].filter(Boolean);
}
function docxParagraphSpacingStyles(properties: XmlRecord) {
const spacing = childRecord(properties, "w:spacing");
const before = docxTwipsAttribute(spacing, ["w:before"]);
const after = docxTwipsAttribute(spacing, ["w:after"]);
return [
before ? `margin-top: ${formatPointSize(before / 20)}pt;` : "",
after && after !== defaultParagraphSpacingAfterTwips ? `margin-bottom: ${formatPointSize(after / 20)}pt;` : ""
].filter(Boolean);
}
function docxParagraphListInfo(properties: XmlRecord, numberingDefinitions: DocxNumberingDefinitions): DocxListInfo | undefined {
const numbering = childRecord(properties, "w:numPr");
const numId = docxAttribute(childRecord(numbering, "w:numId"), "w:val");