Preserve QWord quote style in DOCX

This commit is contained in:
Курнат Андрей
2026-06-02 06:49:30 +03:00
parent c75efaa766
commit 68e0678ca6
4 changed files with 60 additions and 9 deletions
+23
View File
@@ -46,6 +46,20 @@ describe("wordOffice helpers", () => {
]);
});
it("разбирает HTML blockquote как цитату QWord", () => {
const blocks = htmlToWordBlocks('<blockquote id="Quote1">Цитата <strong>важная</strong></blockquote>');
expect(blocks).toEqual([
{
type: "paragraph",
text: "Цитата важная",
runs: [{ text: "Цитата " }, { text: "важная", bold: true }],
bookmark: "Quote1",
quote: true
}
]);
});
it("сохраняет базовое inline-форматирование текста для DOCX", () => {
const blocks = htmlToWordBlocks(`
<p>Обычный <strong>полужирный</strong> <em>курсив</em> <u>подчеркнутый</u> <span style="font-weight: 700; font-style: italic; text-decoration-line: underline; color: #0f5fae; background-color: rgb(255, 242, 204);">все стили</span></p>
@@ -198,6 +212,15 @@ describe("wordOffice helpers", () => {
expect(documentXml).toMatch(/<w:pStyle\b[^>]*w:val="Heading6"[^>]*\/>/);
});
it("записывает blockquote как стиль Quote в XML экспортированного DOCX", async () => {
const blob = await exportDocxBlob("Цитата.docx", "<blockquote>Важная цитата</blockquote>");
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
const documentXml = await zip.file("word/document.xml")?.async("string");
expect(documentXml).toMatch(/<w:pStyle\b[^>]*w:val="Quote"[^>]*\/>/);
expect(documentXml).toContain("Важная цитата");
});
it("записывает HTML-разрывы страниц как w:br w:type page в XML экспортированного DOCX", async () => {
const blob = await exportDocxBlob("Разрыв.docx", '<p>Before<span data-qoffice-page-break="true"></span>After</p>');
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
+20 -8
View File
@@ -43,7 +43,7 @@ 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 }
| { type: "paragraph"; text: string; runs: WordInlineRun[]; alignment?: WordParagraphAlignment; indent?: WordParagraphIndent; bookmark?: string; quote?: boolean }
| { type: "list"; ordered: boolean; items: WordListItem[] }
| { type: "table"; rows: string[][] }
| WordImageBlock;
@@ -264,8 +264,8 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
return;
}
if (tagName === "p" || tagName === "div") {
blocks.push(...paragraphElementToBlocks(node));
if (tagName === "p" || tagName === "div" || tagName === "blockquote") {
blocks.push(...paragraphElementToBlocks(node, { quote: tagName === "blockquote" }));
return;
}
@@ -318,6 +318,7 @@ function wordBlockToDocxChildren(block: WordBlock, docx: DocxModule) {
const children = wordInlineRunsToTextRuns(block.runs, docx);
return [
new docx.Paragraph({
...(block.quote ? { style: "Quote" } : {}),
spacing: { after: 160 },
...docxAlignmentOption(block.alignment, docx),
...docxIndentOption(block.indent),
@@ -590,7 +591,7 @@ function tableRows(table: Element) {
.filter((row) => row.length > 0);
}
function paragraphElementToBlocks(element: Element): WordBlock[] {
function paragraphElementToBlocks(element: Element, options: { quote?: boolean } = {}): WordBlock[] {
const segments = collectInlineSegments(Array.from(element.childNodes), {});
const alignment = paragraphAlignmentFromElement(element);
const indent = paragraphIndentFromElement(element);
@@ -610,7 +611,8 @@ function paragraphElementToBlocks(element: Element): WordBlock[] {
runs,
...(alignment ? { alignment } : {}),
...(indent ? { indent } : {}),
...(bookmark && !bookmarkApplied ? { bookmark } : {})
...(bookmark && !bookmarkApplied ? { bookmark } : {}),
...(options.quote ? { quote: true } : {})
});
bookmarkApplied = true;
}
@@ -805,7 +807,8 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
result.hasLineBreak ||
result.hasPageBreak ||
result.hasTab ||
result.hasList
result.hasList ||
result.hasQuote
? result.html
: "";
} catch {
@@ -834,6 +837,7 @@ function orderedDocxDocumentToHtml(
let hasPageBreak = false;
let hasTab = false;
let hasList = false;
let hasQuote = false;
const blocks: string[] = [];
let openList: DocxListInfo | null = null;
let listItems: string[] = [];
@@ -863,6 +867,7 @@ function orderedDocxDocumentToHtml(
hasPageBreak = hasPageBreak || result.hasPageBreak;
hasTab = hasTab || result.hasTab;
hasList = hasList || Boolean(result.list);
hasQuote = hasQuote || result.hasQuote;
if (!result.html) {
return;
@@ -907,7 +912,8 @@ function orderedDocxDocumentToHtml(
hasLineBreak,
hasPageBreak,
hasTab,
hasList
hasList,
hasQuote
};
}
@@ -924,6 +930,7 @@ function orderedDocxParagraphToHtml(
const list = docxParagraphListInfo(properties, numberingDefinitions);
const hasParagraphAlignment = Boolean(style);
const hasBookmark = Boolean(bookmark);
const hasQuote = tagName === "blockquote";
let hasInlineColorOrHighlight = false;
let hasImage = false;
let hasLineBreak = false;
@@ -941,7 +948,7 @@ function orderedDocxParagraphToHtml(
const content = runs.join("");
if (!content.trim()) {
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasBookmark, hasImage, hasLineBreak, hasPageBreak, hasTab, list };
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasBookmark, hasImage, hasLineBreak, hasPageBreak, hasTab, hasQuote, list };
}
const attributes = [style ? `style="${style}"` : "", bookmark ? `id="${escapeHtml(bookmark)}"` : ""].filter(Boolean).join(" ");
@@ -955,6 +962,7 @@ function orderedDocxParagraphToHtml(
hasLineBreak,
hasPageBreak,
hasTab,
hasQuote,
list
};
}
@@ -968,6 +976,7 @@ function orderedDocxParagraphToHtml(
hasLineBreak,
hasPageBreak,
hasTab,
hasQuote,
list
};
}
@@ -1036,6 +1045,9 @@ function docxParagraphTagName(properties: XmlRecord) {
if (["heading6", "heading 6"].includes(styleValue)) {
return "h6";
}
if (styleValue === "quote") {
return "blockquote";
}
return "p";
}
+16
View File
@@ -22,6 +22,22 @@ describe("wordOffice DOCX import", () => {
]);
});
it("imports DOCX Quote style as blockquote", async () => {
const blob = await exportDocxBlob("Quote.docx", "<blockquote>Quoted fragment</blockquote>");
const file = new File([blob], "Quote.docx", { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
const imported = await importDocxFile(file);
expect(imported.html).toContain("<blockquote>Quoted fragment</blockquote>");
expect(htmlToWordBlocks(imported.html)).toEqual([
{
type: "paragraph",
text: "Quoted fragment",
runs: [{ text: "Quoted fragment" }],
quote: true
}
]);
});
it("imports DOCX text color and highlight from OOXML", async () => {
const blob = await exportDocxBlob(
"Color.docx",