Preserve QWord line spacing in DOCX
This commit is contained in:
@@ -477,6 +477,18 @@ describe("wordOffice helpers", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("сохраняет HTML-межстрочный интервал абзацев для DOCX", () => {
|
||||
const blocks = htmlToWordBlocks(`
|
||||
<p style="line-height: 1.5;">Auto line height</p>
|
||||
<p style="line-height: 24pt;">Exact line height</p>
|
||||
`);
|
||||
|
||||
expect(blocks).toEqual([
|
||||
{ type: "paragraph", text: "Auto line height", runs: [{ text: "Auto line height" }], spacing: { line: 360, lineRule: "auto" } },
|
||||
{ type: "paragraph", text: "Exact line height", runs: [{ text: "Exact line height" }], spacing: { line: 480, lineRule: "exact" } }
|
||||
]);
|
||||
});
|
||||
|
||||
it("записывает отступы абзацев в w:ind экспортированного DOCX", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"Indent.docx",
|
||||
@@ -501,6 +513,18 @@ describe("wordOffice helpers", () => {
|
||||
expect(documentXml).toMatch(/<w:spacing\b(?=[^>]*w:before="240")(?=[^>]*w:after="360")[^>]*\/>/);
|
||||
});
|
||||
|
||||
it("записывает межстрочный интервал абзацев в w:spacing экспортированного DOCX", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"LineSpacing.docx",
|
||||
'<p style="line-height: 1.5;">Auto line height</p><p style="line-height: 24pt;">Exact line height</p>'
|
||||
);
|
||||
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
|
||||
const documentXml = await zip.file("word/document.xml")?.async("string");
|
||||
|
||||
expect(documentXml).toMatch(/<w:spacing\b(?=[^>]*w:line="360")(?=[^>]*w:lineRule="auto")[^>]*\/>/);
|
||||
expect(documentXml).toMatch(/<w:spacing\b(?=[^>]*w:line="480")(?=[^>]*w:lineRule="exact")[^>]*\/>/);
|
||||
});
|
||||
|
||||
it("нормализует HTML после импорта DOCX", () => {
|
||||
expect(normalizeImportedDocxHtml(" <p>Готово</p>\n")).toBe("<p>Готово</p>");
|
||||
});
|
||||
|
||||
+61
-4
@@ -44,8 +44,12 @@ export interface WordParagraphIndent {
|
||||
export interface WordParagraphSpacing {
|
||||
before?: number;
|
||||
after?: number;
|
||||
line?: number;
|
||||
lineRule?: WordParagraphLineRule;
|
||||
}
|
||||
|
||||
export type WordParagraphLineRule = "auto" | "exact" | "atLeast";
|
||||
|
||||
export type WordHeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
|
||||
|
||||
export type WordBlock =
|
||||
@@ -109,6 +113,7 @@ type DocxModule = {
|
||||
AlignmentType?: Record<string, string>;
|
||||
Document: new (options: Record<string, unknown>) => unknown;
|
||||
HeadingLevel: Record<string, string>;
|
||||
LineRuleType?: Record<string, string>;
|
||||
Packer: {
|
||||
toBlob?: (document: unknown) => Promise<Blob>;
|
||||
toBuffer?: (document: unknown) => Promise<ArrayBuffer | Uint8Array>;
|
||||
@@ -556,19 +561,27 @@ function docxParagraphSpacing(spacing: WordParagraphSpacing | undefined, default
|
||||
const normalized = normalizedParagraphSpacing(spacing);
|
||||
return {
|
||||
after: normalized.after ?? defaultAfter,
|
||||
...(normalized.before ? { before: normalized.before } : {})
|
||||
...(normalized.before ? { before: normalized.before } : {}),
|
||||
...(normalized.line ? { line: normalized.line, lineRule: normalized.lineRule } : {})
|
||||
};
|
||||
}
|
||||
|
||||
function normalizedParagraphSpacing(spacing: WordParagraphSpacing | undefined) {
|
||||
const before = normalizedTwips(spacing?.before);
|
||||
const after = normalizedTwips(spacing?.after);
|
||||
const line = normalizedTwips(spacing?.line);
|
||||
const lineRule = normalizedParagraphLineRule(spacing?.lineRule);
|
||||
return {
|
||||
...(before ? { before } : {}),
|
||||
...(after !== undefined ? { after } : {})
|
||||
...(after !== undefined ? { after } : {}),
|
||||
...(line ? { line, lineRule } : {})
|
||||
};
|
||||
}
|
||||
|
||||
function normalizedParagraphLineRule(lineRule: WordParagraphLineRule | undefined) {
|
||||
return lineRule === "exact" || lineRule === "atLeast" ? lineRule : "auto";
|
||||
}
|
||||
|
||||
function normalizedParagraphIndent(indent: WordParagraphIndent | undefined) {
|
||||
const left = normalizedTwips(indent?.left);
|
||||
const firstLine = normalizedTwips(indent?.firstLine);
|
||||
@@ -716,9 +729,11 @@ function paragraphSpacingFromElement(element: Element): WordParagraphSpacing | u
|
||||
const style = element.getAttribute("style") ?? "";
|
||||
const before = cssTwipsValue(style, "margin-top");
|
||||
const after = cssTwipsValue(style, "margin-bottom");
|
||||
const lineHeight = cssLineHeightValue(style);
|
||||
const spacing = {
|
||||
...(before && before > 0 ? { before } : {}),
|
||||
...(after && after > 0 ? { after } : {})
|
||||
...(after && after > 0 ? { after } : {}),
|
||||
...(lineHeight ? lineHeight : {})
|
||||
};
|
||||
return Object.keys(spacing).length > 0 ? spacing : undefined;
|
||||
}
|
||||
@@ -736,6 +751,28 @@ function cssTwipsValue(style: string, property: "margin-left" | "margin-top" | "
|
||||
return cssLengthToTwips(raw);
|
||||
}
|
||||
|
||||
function cssLineHeightValue(style: string): WordParagraphSpacing | undefined {
|
||||
const raw = /(?:^|;)\s*line-height\s*:\s*([^;]+)/i.exec(style)?.[1]?.trim().toLowerCase() ?? "";
|
||||
if (!raw || ["inherit", "initial", "unset", "revert", "normal"].includes(raw)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ratioMatch = /^([0-9]+(?:\.[0-9]+)?)$/.exec(raw);
|
||||
if (ratioMatch) {
|
||||
const ratio = Number.parseFloat(ratioMatch[1]);
|
||||
return Number.isFinite(ratio) && ratio > 0 ? { line: Math.round(ratio * 240), lineRule: "auto" } : undefined;
|
||||
}
|
||||
|
||||
const percentMatch = /^([0-9]+(?:\.[0-9]+)?)%$/.exec(raw);
|
||||
if (percentMatch) {
|
||||
const ratio = Number.parseFloat(percentMatch[1]) / 100;
|
||||
return Number.isFinite(ratio) && ratio > 0 ? { line: Math.round(ratio * 240), lineRule: "auto" } : undefined;
|
||||
}
|
||||
|
||||
const line = cssLengthToTwips(raw);
|
||||
return line && line > 0 ? { line, lineRule: "exact" } : undefined;
|
||||
}
|
||||
|
||||
function cssLengthToTwips(raw: string) {
|
||||
if (!raw || ["inherit", "initial", "unset", "revert", "auto"].includes(raw)) {
|
||||
return undefined;
|
||||
@@ -1148,12 +1185,32 @@ function docxParagraphSpacingStyles(properties: XmlRecord) {
|
||||
const spacing = childRecord(properties, "w:spacing");
|
||||
const before = docxTwipsAttribute(spacing, ["w:before"]);
|
||||
const after = docxTwipsAttribute(spacing, ["w:after"]);
|
||||
const line = docxTwipsAttribute(spacing, ["w:line"]);
|
||||
const lineRule = docxAttribute(spacing, "w:lineRule");
|
||||
return [
|
||||
before ? `margin-top: ${formatPointSize(before / 20)}pt;` : "",
|
||||
after && after !== defaultParagraphSpacingAfterTwips ? `margin-bottom: ${formatPointSize(after / 20)}pt;` : ""
|
||||
after && after !== defaultParagraphSpacingAfterTwips ? `margin-bottom: ${formatPointSize(after / 20)}pt;` : "",
|
||||
docxLineHeightStyle(line, lineRule)
|
||||
].filter(Boolean);
|
||||
}
|
||||
|
||||
function docxLineHeightStyle(line: number | undefined, lineRule: string) {
|
||||
if (!line || line <= 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const normalizedRule = lineRule.trim().toLowerCase();
|
||||
if (!normalizedRule || normalizedRule === "auto") {
|
||||
return `line-height: ${formatLineHeightRatio(line / 240)};`;
|
||||
}
|
||||
|
||||
return `line-height: ${formatPointSize(line / 20)}pt;`;
|
||||
}
|
||||
|
||||
function formatLineHeightRatio(value: number) {
|
||||
return Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/0+$/, "").replace(/\.$/, "");
|
||||
}
|
||||
|
||||
function docxParagraphListInfo(properties: XmlRecord, numberingDefinitions: DocxNumberingDefinitions): DocxListInfo | undefined {
|
||||
const numbering = childRecord(properties, "w:numPr");
|
||||
const numId = docxAttribute(childRecord(numbering, "w:numId"), "w:val");
|
||||
|
||||
@@ -381,4 +381,22 @@ describe("wordOffice DOCX import", () => {
|
||||
{ type: "paragraph", text: "Paragraph spacing", runs: [{ text: "Paragraph spacing" }], spacing: { before: 240, after: 360 } }
|
||||
]);
|
||||
});
|
||||
|
||||
it("imports DOCX paragraph line spacing from OOXML", async () => {
|
||||
const blob = await exportDocxBlob(
|
||||
"LineSpacing.docx",
|
||||
'<p style="line-height: 1.5;">Auto line height</p><p style="line-height: 24pt;">Exact line height</p>'
|
||||
);
|
||||
const file = new File([blob], "LineSpacing.docx", {
|
||||
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
});
|
||||
const imported = await importDocxFile(file);
|
||||
|
||||
expect(imported.html).toContain("line-height: 1.5;");
|
||||
expect(imported.html).toContain("line-height: 24pt;");
|
||||
expect(htmlToWordBlocks(imported.html)).toEqual([
|
||||
{ type: "paragraph", text: "Auto line height", runs: [{ text: "Auto line height" }], spacing: { line: 360, lineRule: "auto" } },
|
||||
{ type: "paragraph", text: "Exact line height", runs: [{ text: "Exact line height" }], spacing: { line: 480, lineRule: "exact" } }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user