Preserve QWord page breaks in DOCX

This commit is contained in:
Курнат Андрей
2026-06-01 19:35:11 +03:00
parent a2de721fc4
commit 6204d59418
6 changed files with 134 additions and 17 deletions
+21
View File
@@ -64,6 +64,18 @@ describe("wordOffice helpers", () => {
]);
});
it("сохраняет служебные HTML-разрывы страниц как inline runs для DOCX", () => {
const blocks = htmlToWordBlocks('<p>Before<span data-qoffice-page-break="true"></span>After</p>');
expect(blocks).toEqual([
{
type: "paragraph",
text: "Before After",
runs: [{ text: "Before\fAfter" }]
}
]);
});
it("сохраняет служебные HTML-табы как inline runs для DOCX", () => {
const blocks = htmlToWordBlocks('<p>Before<span data-qoffice-tab="true" style="white-space: pre;">\t</span>After</p>');
@@ -156,6 +168,15 @@ describe("wordOffice helpers", () => {
expect(documentXml).toMatch(/<w:t[^>]*>Line 1<\/w:t>[\s\S]*<w:br\/>[\s\S]*<w:t[^>]*>Line 2<\/w:t>/);
});
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());
const documentXml = await zip.file("word/document.xml")?.async("string");
expect(documentXml).toMatch(/<w:br\b[^>]*w:type="page"[^>]*\/>/);
expect(documentXml).toMatch(/<w:t[^>]*>Before<\/w:t>[\s\S]*<w:br\b[^>]*w:type="page"[^>]*\/>[\s\S]*<w:t[^>]*>After<\/w:t>/);
});
it("записывает служебные HTML-табы как w:tab в XML экспортированного DOCX", async () => {
const blob = await exportDocxBlob("Табуляция.docx", '<p>Before<span data-qoffice-tab="true" style="white-space: pre;">\t</span>After</p>');
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
+61 -15
View File
@@ -81,6 +81,7 @@ type DocxModule = {
toBuffer?: (document: unknown) => Promise<ArrayBuffer | Uint8Array>;
};
Paragraph: new (options: Record<string, unknown>) => unknown;
PageBreak?: new () => unknown;
Table: new (options: Record<string, unknown>) => unknown;
TableCell: new (options: Record<string, unknown>) => unknown;
TableRow: new (options: Record<string, unknown>) => unknown;
@@ -112,6 +113,8 @@ const xmlParserOptions = {
const wordHyperlinkRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink";
const wordImageRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
const emptyDocxRelationshipTargets = { hyperlinks: {}, images: {} };
const pageBreakMarker = "\f";
const pageBreakHtml = '<span data-qoffice-page-break="true"></span>';
export async function importDocxFile(file: File): Promise<ImportedWordDocument> {
if (!file.name.toLowerCase().endsWith(".docx")) {
@@ -220,6 +223,11 @@ export function htmlToWordBlocks(html: string): WordBlock[] {
return;
}
if (isQOfficePageBreakElement(node)) {
blocks.push({ type: "paragraph", text: "", runs: [{ text: pageBreakMarker }] });
return;
}
if (tagName === "h1" || tagName === "h2") {
const runs = elementInlineRuns(node);
const text = inlineRunsText(runs);
@@ -402,15 +410,22 @@ function wordInlineRunToTextRunsForRun(run: WordInlineRun, docx: DocxModule, opt
const text = String(option.text ?? "");
const baseOption = { ...option };
delete baseOption.text;
const lines = text.split("\n");
const segments = text.split(/(\n|\f)/);
const textRuns: unknown[] = [];
lines.forEach((line, index) => {
if (index > 0) {
segments.forEach((segment) => {
if (segment === "\n") {
textRuns.push(new docx.TextRun({ ...baseOption, break: 1 }));
return;
}
if (line || lines.length === 1) {
textRuns.push(wordInlineTextRunForSegment(line, docx, baseOption));
if (segment === pageBreakMarker) {
textRuns.push(docx.PageBreak ? new docx.PageBreak() : new docx.TextRun({ ...baseOption, break: 1 }));
return;
}
if (segment || segments.length === 1) {
textRuns.push(wordInlineTextRunForSegment(segment, docx, baseOption));
}
});
@@ -511,7 +526,8 @@ function paragraphElementToBlocks(element: Element): WordBlock[] {
const flushParagraph = () => {
const runs = normalizeInlineRuns(pendingRuns);
const text = inlineRunsText(runs);
if (text) {
const hasPageBreak = runs.some((run) => run.text.includes(pageBreakMarker));
if (text || hasPageBreak) {
blocks.push({ type: "paragraph", text, runs, ...(alignment ? { alignment } : {}) });
}
pendingRuns = [];
@@ -650,6 +666,7 @@ async function styledDocxHtmlFromArrayBuffer(arrayBuffer: ArrayBuffer) {
result.hasTable ||
result.hasImage ||
result.hasLineBreak ||
result.hasPageBreak ||
result.hasTab
? result.html
: "";
@@ -674,6 +691,7 @@ function orderedDocxDocumentToHtml(
let hasTable = false;
let hasImage = false;
let hasLineBreak = false;
let hasPageBreak = false;
let hasTab = false;
const blocks = orderedElementChildren(body)
.flatMap((block) => {
@@ -684,6 +702,7 @@ function orderedDocxDocumentToHtml(
hasParagraphAlignment = hasParagraphAlignment || result.hasParagraphAlignment;
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasPageBreak = hasPageBreak || result.hasPageBreak;
hasTab = hasTab || result.hasTab;
return result.html ? [result.html] : [];
}
@@ -692,6 +711,7 @@ function orderedDocxDocumentToHtml(
hasTable = hasTable || Boolean(result.html);
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasPageBreak = hasPageBreak || result.hasPageBreak;
hasTab = hasTab || result.hasTab;
return result.html ? [result.html] : [];
}
@@ -706,6 +726,7 @@ function orderedDocxDocumentToHtml(
hasTable,
hasImage,
hasLineBreak,
hasPageBreak,
hasTab
};
}
@@ -722,19 +743,21 @@ function orderedDocxParagraphToHtml(
let hasInlineColorOrHighlight = false;
let hasImage = false;
let hasLineBreak = false;
let hasPageBreak = false;
let hasTab = false;
const runs = orderedDocxParagraphInlineRecords(paragraph, hyperlinkTargets).map((inline) => {
const result = docxRunToHtml(inline.run, imageDataByRelationshipId, inline.text);
hasInlineColorOrHighlight = hasInlineColorOrHighlight || result.hasInlineColorOrHighlight || Boolean(inline.href);
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasPageBreak = hasPageBreak || result.hasPageBreak;
hasTab = hasTab || result.hasTab;
return inline.href && result.html ? `<a href="${escapeHtml(inline.href)}">${result.html}</a>` : result.html;
});
const content = runs.join("");
if (!content.trim()) {
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak, hasTab };
return { html: "", hasInlineColorOrHighlight, hasParagraphAlignment, hasImage, hasLineBreak, hasPageBreak, hasTab };
}
return {
@@ -743,6 +766,7 @@ function orderedDocxParagraphToHtml(
hasParagraphAlignment,
hasImage,
hasLineBreak,
hasPageBreak,
hasTab
};
}
@@ -754,6 +778,7 @@ function orderedDocxTableToHtml(
) {
let hasImage = false;
let hasLineBreak = false;
let hasPageBreak = false;
let hasTab = false;
const rows = orderedDirectElements(table, "w:tr")
.map((row) => {
@@ -764,6 +789,7 @@ function orderedDocxTableToHtml(
const result = orderedDocxParagraphToHtml(paragraph, hyperlinkTargets, imageDataByRelationshipId);
hasImage = hasImage || result.hasImage;
hasLineBreak = hasLineBreak || result.hasLineBreak;
hasPageBreak = hasPageBreak || result.hasPageBreak;
hasTab = hasTab || result.hasTab;
return result.html;
})
@@ -777,7 +803,7 @@ function orderedDocxTableToHtml(
})
.filter(Boolean);
return { html: rows.length > 0 ? `<table><tbody>${rows.join("")}</tbody></table>` : "", hasImage, hasLineBreak, hasTab };
return { html: rows.length > 0 ? `<table><tbody>${rows.join("")}</tbody></table>` : "", hasImage, hasLineBreak, hasPageBreak, hasTab };
}
function orderedDocxCellText(cell: unknown) {
@@ -837,7 +863,7 @@ function orderedDocxRunText(run: unknown) {
return "\t";
}
if (name === "w:br") {
return "\n";
return isDocxPageBreakAttributes(orderedElementAttributes(child)) ? pageBreakMarker : "\n";
}
return "";
@@ -994,11 +1020,12 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR
const hasStrike = hasDocxBoolean(properties, "w:strike") || hasDocxBoolean(properties, "w:dstrike");
const hasInlineColorOrHighlight = Boolean(color || highlightColor || fontSize || fontFamily || hasStrike);
const hasLineBreak = text.includes("\n");
const hasPageBreak = text.includes(pageBreakMarker);
const hasTab = text.includes("\t");
let html = escapeHtmlDocxText(text);
if (!text && !imageHtml) {
return { html: "", hasInlineColorOrHighlight, hasImage: false, hasLineBreak, hasTab };
return { html: "", hasInlineColorOrHighlight, hasImage: false, hasLineBreak, hasPageBreak, hasTab };
}
if (text) {
@@ -1027,7 +1054,7 @@ function docxRunToHtml(run: unknown, imageDataByRelationshipId: DocxImageDataByR
}
}
return { html: `${imageHtml}${text ? html : ""}`, hasInlineColorOrHighlight, hasImage: Boolean(imageHtml), hasLineBreak, hasTab };
return { html: `${imageHtml}${text ? html : ""}`, hasInlineColorOrHighlight, hasImage: Boolean(imageHtml), hasLineBreak, hasPageBreak, hasTab };
}
function docxRunImageHtml(run: XmlRecord, imageDataByRelationshipId: DocxImageDataByRelationshipId) {
@@ -1139,7 +1166,9 @@ function emuToPixels(value: number) {
function docxRunText(run: XmlRecord) {
const text = toArray(run["w:t"]).map(xmlNodeText).join("");
const tabs = toArray(run["w:tab"]).map(() => "\t").join("");
const breaks = toArray(run["w:br"]).map(() => "\n").join("");
const breaks = toArray(run["w:br"])
.map((breakRecord) => (isDocxPageBreakAttributes(asRecord(breakRecord)) ? pageBreakMarker : "\n"))
.join("");
return `${text}${tabs}${breaks}`;
}
@@ -1254,7 +1283,11 @@ function escapeHtml(value: string) {
}
function escapeHtmlDocxText(value: string) {
return escapeHtml(value).replace(/\t/g, '<span data-qoffice-tab="true" style="white-space: pre;">\t</span>').replace(/\n/g, "<br>");
return escapeHtml(value)
.split(pageBreakMarker)
.join(pageBreakHtml)
.replace(/\t/g, '<span data-qoffice-tab="true" style="white-space: pre;">\t</span>')
.replace(/\n/g, "<br>");
}
function collectInlineRuns(nodes: ChildNode[], format: InlineFormat): WordInlineRun[] {
@@ -1272,6 +1305,10 @@ function collectInlineSegments(nodes: ChildNode[], format: InlineFormat): Inline
return [];
}
if (isQOfficePageBreakElement(node)) {
return [{ type: "runs", runs: [{ text: pageBreakMarker, ...format }] }];
}
if (node.tagName.toLowerCase() === "br") {
return [{ type: "runs", runs: [{ text: "\n", ...format }] }];
}
@@ -1586,9 +1623,18 @@ function normalizeInlineWhitespace(value: string) {
function normalizeInlineRunText(value: string) {
return value
.replace(/\u00a0/g, " ")
.replace(/[^\S\n\t]+/g, " ")
.replace(/[^\S\n\t\f]+/g, " ")
.replace(/ *\n */g, "\n")
.replace(/ *\t */g, "\t");
.replace(/ *\t */g, "\t")
.replace(/ *\f */g, pageBreakMarker);
}
function isQOfficePageBreakElement(element: Element) {
return element.getAttribute("data-qoffice-page-break") === "true";
}
function isDocxPageBreakAttributes(attributes: XmlRecord) {
return docxAttribute(attributes, "w:type").toLowerCase() === "page";
}
async function loadMammoth() {
+17
View File
@@ -112,6 +112,23 @@ describe("wordOffice DOCX import", () => {
]);
});
it("imports DOCX page breaks from OOXML", async () => {
const blob = await exportDocxBlob("PageBreak.docx", '<p>Before<span data-qoffice-page-break="true"></span>After</p>');
const file = new File([blob], "PageBreak.docx", {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
const imported = await importDocxFile(file);
expect(imported.html).toContain('data-qoffice-page-break="true"');
expect(htmlToWordBlocks(imported.html)).toEqual([
{
type: "paragraph",
text: "Before After",
runs: [{ text: "Before\fAfter" }]
}
]);
});
it("imports DOCX tabs from OOXML", async () => {
const blob = await exportDocxBlob("Tab.docx", '<p>Before<span data-qoffice-tab="true" style="white-space: pre;">\t</span>After</p>');
const file = new File([blob], "Tab.docx", {