From 1bc7d2c6e8d8ee20d5829bee9288a8053babec01 Mon Sep 17 00:00:00 2001 From: DemchaAV Date: Tue, 20 Oct 2026 10:47:06 +0100 Subject: [PATCH 1/2] fix(docx): keep the space above a stack of one layer opening a page A stack of one layer is written in the flow, and Word drops its first paragraph's space above at the top of a page as any other's, but the line holding that space was written only outside every stack. Measured in Word and LibreOffice, a paragraph or a picture with a 20pt margin opening such a stack on a new page stood 20pt high, and one in a stack with a 14pt margin 14pt high. A paragraph or a picture opening one is now held as in the flow, with the stack's own edges. A layer's offset in its stack, which is named and not written, is not held either. --- CHANGELOG.md | 13 + .../architecture/backend-capability-matrix.md | 2 +- docs/recipes/docx-export.md | 4 +- .../semantic/docx/DocxSemanticBackend.java | 46 +++- .../DocxStackOfOneLayerOnANewPageTest.java | 248 ++++++++++++++++++ 5 files changed, 302 insertions(+), 11 deletions(-) create mode 100644 render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 48da56314..47503d293 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,19 @@ follow semantic versioning; release dates are ISO 8601. ### Public API +- **A DOCX export keeps the space above the first paragraph or picture of a stack of one layer the + layout moves to a new page.** A stack of one layer is written in the flow, and Word drops its + first paragraph's space above at the top of a page as any other's. That space was held only for + a paragraph or a picture in the flow outside any stack. Measured in Word and LibreOffice on + Windows, opening such a stack on a new page, in both: + - a paragraph with a 20pt margin stood 20pt high; + - a picture with a 20pt margin stood 20pt high; + - a paragraph in a stack with a 14pt margin stood 14pt high. + + Nothing was named. + - The space is now held in a line kept with the first block, as in the flow, the stack's own + edges with it. Each stands where the page sets it, and the page breaks where it did. + - A layer's offset in its stack, up or down, is named as before, and not held. - **A picture, a shape or a barcode composed in a table cell keeps its own size.** The layout gave a node composed in a table cell (`DocumentTableCell.node`) the cell's inner width, and the height it measured. In a 120pt column padded 4pt, the page drew: diff --git a/docs/architecture/backend-capability-matrix.md b/docs/architecture/backend-capability-matrix.md index a5cb426eb..f1b8351de 100644 --- a/docs/architecture/backend-capability-matrix.md +++ b/docs/architecture/backend-capability-matrix.md @@ -81,7 +81,7 @@ Payload records live in `core` under | Linear gradient fill (`DocumentPaint`) | ✅ `PdfShadingSupport` | ✅ `PptxGradientFill` (native `gradFill`; explicit-axis endpoints approximate to the angle) | ❌ | | Radial gradient fill (`DocumentPaint`) | ✅ `PdfShadingSupport` | ⚠️ `PptxGradientFill` (`circle` path shade — DrawingML cannot express radius-to-farthest-corner exactly) | ❌ | | Gradient strokes | ✅ `PdfPathPainter` (pattern stroking colour) | ✅ `PptxGradientFill` (native `ln`/`gradFill`) | ❌ | -| Image — STRETCH / CONTAIN / COVER fit (`ImageFragmentPayload`) | ✅ `PdfImageFragmentRenderHandler` | ✅ `PptxImageFragmentRenderHandler` (COVER via the picture source crop) | ✅ `DocxSemanticBackend.writeImage` (the box comes from `NodeDefinitionSupport.resolveImageDimensions`, the same rule layout applies to `width` / `height` / `scale` and the content-width clamp; CONTAIN is embedded at its fitted size, the room it leaves in its box held round it as the page centres it — half above and below as its paragraph's space, half at its side as its indent — COVER via the picture source crop as in PPTX, and the picture type is read from the bytes; a picture in the flow the layout moves to a new page keeps the space above it there, in a line kept with it, as a paragraph's is; its left margin and padding are not written, and a picture drawn beside its text is fitted to its box with its padding in it — each named in the report) | +| Image — STRETCH / CONTAIN / COVER fit (`ImageFragmentPayload`) | ✅ `PdfImageFragmentRenderHandler` | ✅ `PptxImageFragmentRenderHandler` (COVER via the picture source crop) | ✅ `DocxSemanticBackend.writeImage` (the box comes from `NodeDefinitionSupport.resolveImageDimensions`, the same rule layout applies to `width` / `height` / `scale` and the content-width clamp; CONTAIN is embedded at its fitted size, the room it leaves in its box held round it as the page centres it — half above and below as its paragraph's space, half at its side as its indent — COVER via the picture source crop as in PPTX, and the picture type is read from the bytes; a picture in the flow, a stack of one layer's included, that the layout moves to a new page keeps the space above it there, in a line kept with it, as a paragraph's is; its left margin and padding are not written, and a picture drawn beside its text is fitted to its box with its padding in it — each named in the report) | | Barcode / QR (`BarcodeFragmentPayload`) | ✅ `PdfBarcodeFragmentRenderHandler` (vector: the ZXing bit matrix filled as merged rectangles) | ✅ `PptxBarcodeFragmentRenderHandler` (native freeforms: the same ZXing bit matrix as merged rectangles) | ⚠️ `DocxSemanticBackend.writeBarcode` (a PNG picture of the same ZXing bit matrix through `BarcodeMatrices`, one pixel a cell, in the symbol's two colours with their alpha and at the node's size, its data as the picture's description; it scans, but its data is part of the picture rather than editable, reported `APPROXIMATED`, which also names a link, a transform or its left margin and padding as not carried; an `anchor` is a bookmark on its paragraph; in a page zone it is skipped) | | Table rows — resolved cells, row/col spans, two-pass fill/border paint (`TableRowFragmentPayload`) | ✅ `PdfTableRowFragmentRenderHandler` + row grouping in `PdfFixedLayoutBackend` | ✅ `PptxTableRowFragmentRenderHandler` + row grouping in `PptxFixedLayoutBackend` (positioned rectangles, edge lines, and text frames — never native PPTX tables, which re-lay-out content) | ⚠️ `DocxSemanticBackend.writeTable` (a real Word table on the grid `TableGrid` resolves, its columns the layout's widths — where one is `auto` and the layout does not show them, composed in a table cell or with a column edge no row shows, the editor's, and reported (`TableNode`): `colSpan` maps to `w:gridSpan`, `rowSpan` to `w:vMerge`, and the cascaded `DocumentTableStyle` text style reaches the cell's runs; the cell's fill maps to `w:shd` and its stroke to `w:tcBorders` — the engine's default 1pt black rule where the table states none, not Word's thinner grid — its padding to `w:tcMar`, less above and below the room Word makes for the horizontal rules (half of a rule between two rows, the lower row's, to each; the rules above and below the table whole to their row) — a row where a cell of text its padding then leaves short of that room needs more than the page's height stands taller in Word, reported (`cell rule`) — each as wide as Word draws it, in eighths of a point (one outside Word's range reported, `border width`), and counted as both editors count it, two and a half twips an eighth rounded down (a rule between two rows shared in whole twips, the row above it taking half rounded down; a cell's top and bottom margins rounded to the twip together), a row held at the page's height less the most any of its cells takes, its margins and the rules it holds — between two others, the rest of its own above and half that of the cell under it; LibreOffice makes room at the edge between two rows for the heavier of their rules, where Word makes it for the lower row's, and under a row ruled heavier than it a row stands the difference lower there; a row of text cells moved by its top and bottom margins together, from Word's seat four fifths of the way down an exact line onto the page's baselines, by the least its cells' lines call for and no further than the margins hold — not a row holding a composed cell, one the layout did not measure, one in a vertical merge or whose cells call for opposite ways, nor a least call under a tenth of a point — and what the margins leave of a cell's call, half a point and more, moved by its text's position, and less, from a tenth of a point, by the height of its lines, each written shorter and the space after it taller, or the other way as far as that space holds, which keeps the cell's content as tall — where every paragraph of the cell is one line, in a face whose letters the export reads, and its letters stay clear of the line's top and foot; a row's cells at the row's smallest top and bottom margins, since both editors give every cell the row's largest, the rest of each cell's padding as space above its first paragraph and below its last, down to the largest margin a cell opening with a table or in a vertical merge keeps; the cascaded `textAnchor` maps to `w:vAlign` on every cell and to `w:jc` on a text cell's paragraph, with the engine's default — the vertical middle, on the left, or on the right for a right-to-left cell — and `DEFAULT` at the bottom left, as the renderer draws it; a composed cell is written by the same writers that write its node anywhere, so one built from an image, a list or a table carries it — a nested table is a real `w:tbl` taking the width of the column it sits in, less its own margins and padding, which is the column's rather than the one the page gives it, since the layout reports a composed cell's content under the owner's path; the paragraph Word requires after a nested table is hidden where it ends its cell holding nothing and no space; a translucent fill is flattened against the colour the page paints under the cell, and a translucent rule against the cell's fill where it has one, since `w:shd` and `w:tcBorders` are opaque, and the table's report note names it (`translucency`); Word re-paginates, so the export states where the layout breaks: every row the layout placed is `w:cantSplit`, `repeatHeader(n)` rows are `w:tblHeader` and keep with the row under them, and a row of blocks is kept whole the same way; the paragraph Word requires after a document's closing table is an ordinary one where the last page has room for two lines below it, so a reader can type below the table, and otherwise a point tall with its mark hidden, so it opens no blank page, reported `APPROXIMATED` since text typed at the end then goes into the table's last cell) | | Clip region open/close (`ShapeClipBegin/EndPayload`) | ✅ `PdfShapeClipBegin/EndRenderHandler` (CLIP_BOUNDS + CLIP_PATH) | ✅ `PptxClipSafety` + raster fallback in `PptxFixedLayoutBackend` — a provably no-op clip (padded content that cannot be cut) skips the fallback entirely and stays native, editable shapes; a clip that can cut ink renders through the PDF backend into one transparent picture on the clip bounds (pixel-exact, not editable as shapes; run-level link hotspots are not emitted and custom fragment handlers do not apply inside the picture; `Builder.clipRasterFallback(false)` restores unclipped vectors + warning; the raster targets a 2048px long edge, clamped to between native size and 4x, so a region larger than that is rendered at native resolution rather than downscaled — which also means its transient memory grows with the clip instead of stopping at the target (a 3370pt A0-landscape region costs ~45MB while rendering, against ~17MB for anything up to 2048pt); a true vector clip is tracked in [#413](https://github.com/DemchaAV/GraphCompose/issues/413)) | ⚠️ inline fallback + one-time capability warning; the report names a clip that cuts what its layers paint, measured from the layout's fragments by `DocxClipInk` — a clip that cuts nothing (an icon inside its box, a disc's initials, a photo filling its circle) is not named; a picture that fills a container clipped to an ellipse takes the ellipse as its geometry, which both editors crop it to; a badge's glyph — a smaller picture in a painted container that clips it to its outline (`CLIP_PATH`) and holds nothing else but drawing — is drawn by `DocxDrawings` as a floating picture over the outline, where the layout places it, reported `APPROXIMATED` — inside a filled panel the badge and its glyph are drawn in front of the shading; an icon picture beside its text in an unpainted container or a layer stack is drawn the same way; a filled or outlined rectangle or rounded rectangle holding text, composed in a table cell, which has no place in the layout to be drawn at, is written as a panel — a one-cell table in its fill and outline, its corners squared and reported, its row held at least the outline's height less its borders and margins, which keep inside it, and a one-line label the shape centres top to bottom on a line taller than the room Word leaves its content cut alike on both sides to that room, no closer to its letters than three quarters of a point, and seated where the page sets it, from the shape's top where the line is taller than its outline and Word sets it on the shape's middle, and a label it holds whole written at the line height that stands its text on the page's baseline, as far as its letters and the room allow, by a tenth of a point or more and not in a standard face the export does not embed — its row held and its label cut in whole twips rounded down, as the row the cell is in holds the page's height rounded once, and what its letters keep the label past that room taken out of the margins of the cell it is in, where it is all that cell holds and the cell all its row holds; the rest of what a composed cell draws (an icon, a tile, a disc) is the table's own drawing and is drawn by `drawCellDrawing` where the layout puts it, anchored as a rectangle is | diff --git a/docs/recipes/docx-export.md b/docs/recipes/docx-export.md index 7493f6b03..c89f5be46 100644 --- a/docs/recipes/docx-export.md +++ b/docs/recipes/docx-export.md @@ -67,12 +67,12 @@ creation date is real metadata. | Document node | DOCX output | |---|---| -| Paragraphs | Word paragraphs with alignment, font, size, colour (a translucent one with its transparency, as Word's text fill — see "Translucent colours"), bold/italic/underline; inline runs preserved; a `\n` in the text is a line break (`w:br`), which Word would otherwise read as a space; a table cell's `text("a\nb")` stays one line, as the page sets it; a character the page draws nothing for — a control such as a tab or a bell, a soft hyphen, a zero-width space, one of private use — is not written either, where the file held a question mark for most controls, the direction marks and joiners kept; a margin below zero on a paragraph, a list or a block round them sets its text out past that side in the flow as far as the page does — in a table cell, a panel's included, as far as the cell's text and no further, and the report names what is held back; a row's first child the page sets out past the row's left edge starts at it, named; a `bulletOffset` of spaces is an indent — the wrapped lines (`FROM_SECOND_LINE`), the first (`FIRST_LINE`) or all of them start that far in, measured in the paragraph's style as the page measures it; a prefix with letters in it is not written, but the wrapped lines still start after the spaces the page covers it with; no prefix is applied to a paragraph written over the flow, as one of an overlay's left-and-right pair, as a badge's initials, or in a header or footer; the report names a prefix's letters, and the room a prefix sets lines in by where a path that writes none leaves it out and it moves a line — on the paragraph, or in a header or footer on the zone's note. A session reads markdown unless told not to (`markdown(false)`): it sets a paragraph of plain text's emphasis marks as the style of the text they mark, a heading line bold (the first three levels larger), and drops its marks; the export writes the text as the page sets it — read line by line through the page's own parser, one run a piece in the face, family, colour, tracking and size the page sets it in, `**Java**` a bold run reading `Java`, a linked paragraph's pieces in one link, Word's outline listing a heading by the text written — wherever it writes a paragraph, a page zone's and a badge's included (a badge's initials counted as the page sets them, and written in the flow where they stand in two faces or as a heading, as initials in two runs' faces are). The page's laid-out lines decide it: the pieces are written where those lines hold their letters in their faces, families, colours and tracking, at their sizes — an auto-sized paragraph's read at the size the page fits it to, a heading at its multiple of it; a session that reads no markdown has its marks written as they stand, and text the parser changes nothing of, an underscore inside a word, is written as it stands too. A paragraph composed in a table cell takes only lines that set its pieces so. The page sets a markdown heading in a line as tall as the paragraph's own and draws its letters past it; written in that exact line, Word cuts their tops on screen, and the report names a heading written taller than its line. The faces are the page's: where the session reads markdown its parser sets every piece in a face of its own, the paragraph's left aside, so a bold paragraph's `Senior_Engineer` is written regular, as the page sets it. A paragraph whose lines are not read — with no layout, composed in a table cell whose text, as authored or as the page reads it, no line of its table carries, or a page zone's the layout shows none of — or that the page sets in other letters than its text, as Arabic, which the page shapes before it reads the marks, or that the parser reads into nothing — a lone `*`, an empty list item; `***`, a rule; a line set four spaces in, a block of code — which the page sets as nothing, is written as authored, marks and all, and the report names it, saying where the lines are not read that whether the page reads its marks is not measured, where the page's parser drops one. An auto-sized paragraph (`autoSize`) is written at the size the page fits its text to, read off the layout's lines, on every path that writes a paragraph: a run with a style of its own keeps it, as on the page, and a prefix is measured at the fitted size. Where the lines do not tell it — none are read, they are in sizes that do not say which is the paragraph's, or the paragraph is added at more than one place, which the page fits at each apart — the text is written at its style's size, and the report says the fitted size is not measured, on the paragraph or, in a header or footer, on the zone's note. LibreOffice breaks a badge's initials wider than the square inscribed in its disc, at any size, and hides what wraps; an auto-sized badge, which fills its disc, meets this too. A body paragraph the layout moves to a new page keeps the space the layout leaves above its text there — its own top edge, the edges of the containers opening with it, and the gap before it where the gap did not fit at the foot of the page above — as an empty line that tall before it, kept with it, since Word drops a paragraph's space above at the top of a page and keeps a line's height; the rest of the space owed stays above that line, so Word breaks the page where it did, and the gap between the paragraph's lines comes off the line as it would off its space above. A paragraph in a table cell, an overlay or a list is left to its container | +| Paragraphs | Word paragraphs with alignment, font, size, colour (a translucent one with its transparency, as Word's text fill — see "Translucent colours"), bold/italic/underline; inline runs preserved; a `\n` in the text is a line break (`w:br`), which Word would otherwise read as a space; a table cell's `text("a\nb")` stays one line, as the page sets it; a character the page draws nothing for — a control such as a tab or a bell, a soft hyphen, a zero-width space, one of private use — is not written either, where the file held a question mark for most controls, the direction marks and joiners kept; a margin below zero on a paragraph, a list or a block round them sets its text out past that side in the flow as far as the page does — in a table cell, a panel's included, as far as the cell's text and no further, and the report names what is held back; a row's first child the page sets out past the row's left edge starts at it, named; a `bulletOffset` of spaces is an indent — the wrapped lines (`FROM_SECOND_LINE`), the first (`FIRST_LINE`) or all of them start that far in, measured in the paragraph's style as the page measures it; a prefix with letters in it is not written, but the wrapped lines still start after the spaces the page covers it with; no prefix is applied to a paragraph written over the flow, as one of an overlay's left-and-right pair, as a badge's initials, or in a header or footer; the report names a prefix's letters, and the room a prefix sets lines in by where a path that writes none leaves it out and it moves a line — on the paragraph, or in a header or footer on the zone's note. A session reads markdown unless told not to (`markdown(false)`): it sets a paragraph of plain text's emphasis marks as the style of the text they mark, a heading line bold (the first three levels larger), and drops its marks; the export writes the text as the page sets it — read line by line through the page's own parser, one run a piece in the face, family, colour, tracking and size the page sets it in, `**Java**` a bold run reading `Java`, a linked paragraph's pieces in one link, Word's outline listing a heading by the text written — wherever it writes a paragraph, a page zone's and a badge's included (a badge's initials counted as the page sets them, and written in the flow where they stand in two faces or as a heading, as initials in two runs' faces are). The page's laid-out lines decide it: the pieces are written where those lines hold their letters in their faces, families, colours and tracking, at their sizes — an auto-sized paragraph's read at the size the page fits it to, a heading at its multiple of it; a session that reads no markdown has its marks written as they stand, and text the parser changes nothing of, an underscore inside a word, is written as it stands too. A paragraph composed in a table cell takes only lines that set its pieces so. The page sets a markdown heading in a line as tall as the paragraph's own and draws its letters past it; written in that exact line, Word cuts their tops on screen, and the report names a heading written taller than its line. The faces are the page's: where the session reads markdown its parser sets every piece in a face of its own, the paragraph's left aside, so a bold paragraph's `Senior_Engineer` is written regular, as the page sets it. A paragraph whose lines are not read — with no layout, composed in a table cell whose text, as authored or as the page reads it, no line of its table carries, or a page zone's the layout shows none of — or that the page sets in other letters than its text, as Arabic, which the page shapes before it reads the marks, or that the parser reads into nothing — a lone `*`, an empty list item; `***`, a rule; a line set four spaces in, a block of code — which the page sets as nothing, is written as authored, marks and all, and the report names it, saying where the lines are not read that whether the page reads its marks is not measured, where the page's parser drops one. An auto-sized paragraph (`autoSize`) is written at the size the page fits its text to, read off the layout's lines, on every path that writes a paragraph: a run with a style of its own keeps it, as on the page, and a prefix is measured at the fitted size. Where the lines do not tell it — none are read, they are in sizes that do not say which is the paragraph's, or the paragraph is added at more than one place, which the page fits at each apart — the text is written at its style's size, and the report says the fitted size is not measured, on the paragraph or, in a header or footer, on the zone's note. LibreOffice breaks a badge's initials wider than the square inscribed in its disc, at any size, and hides what wraps; an auto-sized badge, which fills its disc, meets this too. A body paragraph the layout moves to a new page keeps the space the layout leaves above its text there — its own top edge, the edges of the containers opening with it, and the gap before it where the gap did not fit at the foot of the page above — as an empty line that tall before it, kept with it, since Word drops a paragraph's space above at the top of a page and keeps a line's height; the rest of the space owed stays above that line, so Word breaks the page where it did, and the gap between the paragraph's lines comes off the line as it would off its space above. A stack of one layer is in the flow: the paragraph opening one does the same, with the stack's own edges, though not the layer's offset in the stack, up or down, which is named and not written. A paragraph in a table cell, any other overlay or a list is left to its container | | Lists | Real Word lists: a `numbering.xml` definition per list, `w:numPr` on each item, and the authored marker as the level's text. Nesting is a list level, so Enter continues the list and Tab demotes an item. An item the page reads as markdown is written as the page sets it, as a paragraph is. See "What a list becomes" below for the kinds that stay plain paragraphs | | Tables | Word tables, one cell per cell. Each cell states its own padding, on all four sides, so a row is as tall as the page draws it: as `w:tcMar`, and above and below partly in its paragraphs. Word and LibreOffice give every cell of a row the largest top and bottom margin of any cell in it, so a row's cells are written with its smallest, and the rest of a cell's padding above and below is space above its first paragraph and below its last (measured: a row whose day cells were padded 5.5pt above and 10.25pt below beside a label padded 0.75pt stood 60.3pt tall in both editors, where its tallest cell came to 46). A cell opening with a table has no paragraph above it to hold its padding, and a cell in a vertical merge has its bottom edge in another row: these keep their margins, and the row's comes down no lower than the largest of them. Its padding above and below gives up the room Word makes for the table's horizontal rules — half of a rule between two rows to each, the lower row's rule where the two differ, the rule above the table and the one below it whole to their row — which the page does not (measured: a 0.75pt rule made each row 0.75pt taller). Padding thinner than its share gives what it has; Word sets each cell at its content and, on each side, its padding or its share where that is more, and the row at its tallest cell, so a row stands taller where a cell of text then needs more than the page's height — by that much, which the report names, added up for the table (`cell rule`; measured in Word and LibreOffice on Windows against the same table unruled, to a tenth of a point: four rows with no padding, 3pt rules 15pt and 1pt rules 5pt; a two-line cell with no padding beside a padded one-line cell, each counted on its own). Cells built from a node, cells spanning rows and empty cells in rows held at the page's height are not counted; where the layout does not tell a row's height — a table composed in a cell, or no layout — the report names the most it can be. Each rule comes off as wide as Word draws it, in eighths of a point: a 0.7pt hairline is drawn 0.75pt wide (measured: taken off at 0.7, `EditorialProposal`'s tables and all under them stood a step of Word's grid lower). A cell's rule is written from two to ninety-six eighths of a point, the range of a line border's width. A rule is counted as both editors count it, two and a half twips an eighth rounded down (measured: one of 12.5 twips takes 12, one of 17.5 takes 17), and a rule between two rows is shared in whole twips, the row above it taking half rounded down and the row under it the rest; a cell's top and bottom margins are rounded to the twip together. Tables of one, two, three and six rows ruled at five, six, seven and nine eighths then take the page's height to within a step of Word's grid and to the twip in LibreOffice (measured). A row held at the page's height is written less its margins and those rules too — a rule and a half in the first row and the last, two in a table of one row — since both editors read a row's written height as its cells' content (measured: held less one rule, a table ruled at 0.75pt stood 0.46pt taller in its first row and 0.36pt in its last). A row between two others is written less the rest of its own rule above it and half that of the cell under it, one rule where the two are ruled alike, and any row less the most one of its cells takes, its margins and those rules together (measured: held less its own rule alone, a row ruled at 0.5pt over one ruled at 1.5pt stood half a point taller in Word, and all under it half a point lower). LibreOffice makes room at the edge between two rows for the heavier of their rules, where Word makes it for the lower row's: under a row ruled heavier than it, a row and all under it stand the difference lower there (measured: under a 1.5pt row, 0.5pt rows stood 1pt lower in LibreOffice on Windows and LibreOffice 24.2, and where the page sets them in Word). A cell that holds nothing but an empty line — a row that is only a rule, its thickness the empty cell's font — has that line cut to the room its row leaves it, the page's row less the cell's own margins and border: the page draws the rule's borders across the line, and Word and LibreOffice keep them outside it and grow the row (measured: `CobaltRota`'s two rules under a 0.9pt border stood 0.9pt taller each). A line with letters, a picture or a paragraph border of its own keeps its height. A table that states no rule is written with the engine's default 1pt black rule, as the page draws it, not left on Word's thinner grid. Its `textAnchor` becomes `w:vAlign` and the paragraph's `w:jc`, with the engine's default — the vertical middle, on the left — where Word's is the top, so a line beside a taller neighbour sits where the page puts it and an amount column stays right-aligned. A row of text cells is moved by its margins to stand its text where the page sets it: the page sets a cell's line its face's ascent below the line's top, Word an exact line's baseline four fifths of the way down it, so every cell's top margin is made smaller and its bottom one as much larger — or the other way — by the least any of its cells calls for, no further than the margin holds, and each cell's text moves with its room, set at the top, the middle or the bottom, while the row keeps its height (measured: a line of 8pt Poppins stood 0.58pt low in Word and 0.55pt in LibreOffice, of Lato 0.24 and 0.25pt high; moved, within 0.04pt and 0.09pt). Not a row holding a composed cell, whose paragraphs their own writers seat where they can, nor a row the layout did not measure, nor one in a vertical merge or whose cells call for opposite ways; a least call under a tenth of a point is left. What the margins leave of a cell's call is moved by its text's position where that is half a point or more, as a paragraph's is: LibreOffice moves raised text further than it is raised, by up to half as much again, which from half a point up is less than what is left. Less, from a tenth of a point, is moved by the height of the cell's lines: each written shorter and the space after it taller by as much, or the other way as far as that space holds, which keeps the cell's content as tall and each line's top where it was, and moves the text four fifths of the difference in both editors — where every paragraph of the cell is one line, in a face whose letters the export reads (not a standard face it does not embed), and its letters stay clear of the line's top and foot, where Word cuts them on screen (measured: `CobaltRota`'s staff names, beside the day cells its chips are composed in, stood 0.25pt low in Word, 0.2pt in LibreOffice on Windows and 0.19pt in LibreOffice 24.2; so, within 0.08pt in all three, every row its height; the line alone written shorter shortened a row whose tallest content it was by as much in LibreOffice 24.2, which holds a row to its cells' content). LibreOffice sets a vertically centred cell's content as if its first paragraph had no space above it, so a cell padded more above than its row's smallest stands its text up to half that difference higher there (measured: 3pt above it stood the line 1.5pt high). A cell with no style of its own is set in the engine's default cell face rather than the document's Normal. A cell's lines are one paragraph with line breaks; when its style's `lineSpacing(...)` is above zero and it has more than one line, they are a paragraph each, with the spacing after every line but the last, since Word has no space between the lines of one paragraph but a taller line. A column sized to its content gets a point more than the page gives it, so the editor's font substitute cannot wrap its widest cell. The width is written when the document states one or every column is fixed; otherwise Word sizes the table — see "What falls back". A table breaks across pages where the layout breaks it: every row the layout placed is kept whole (`w:cantSplit`) — but the row of a one-row table of paragraphs kept with what follows (see Sections / containers) — `repeatHeader(n)` rows repeat on each page (`w:tblHeader`) and stay with the row under them. Two tables in a row — rows included, since a row is carried as a table — are kept apart by a paragraph a tenth of a point tall, holding the rest of the gap between them: an editor joins two tables with nothing between them into one. A table or a row the layout moves to a new page keeps its own top edge there, as the page does — written as a line that tall, kept with it, since Word drops a paragraph's space above at the top of a page — while the gap between it and the block before stays at the foot of the page above, where it fits there; a gap the layout carries onto the new page, because it did not fit at the foot of the page above, is not yet held above a table (body paragraphs, spacers and pictures: see their rows). A table's margin is its indent and the space round it, and its padding on the sides holds its rows in as the page draws them: its left side is in the indent too, and both are out of the room its columns are given | | Composed cells (`DocumentTableCell.node(...)`) | Written by the same writers that write that node anywhere else, so a cell built from an image, a list or a table carries it. A nested table is a real `w:tbl` followed by the paragraph Word requires a cell to end with — a hairline, which the paragraph written next in the cell takes over, so no empty line opens under the table, and whose mark is hidden where it is left at the cell's end holding nothing and no space, since LibreOffice lays it out — and takes the width of the column it sits in, less its own margins and padding — the column's, not the one the page gives it, because the layout reports a composed cell's content under the owner's path. Its fixed columns are written where every column is fixed; where one is `auto`, the editor divides the width among them (measured: Word and LibreOffice on Windows alike, half the cell each for two), and the report names it (`TableNode`) | | Inline chips (`inlineCode(...)`, `inlineChip(...)`, `highlight(...)`) | The chip's fill becomes the run's own `w:shd`, in a paragraph and in a list item alike. Its shape does not travel — see "What a chip keeps and loses" below | -| Images | Embedded pictures at the node's declared size. One contained in its box (`fitToBounds`, `CONTAIN`) is embedded at its fitted size, half the room it leaves above and below written as the space round its paragraph and half at its side as its indent; in a band the room below is its paragraph's own, as the band measures what it owes below from the box. In the flow, in a row's cell and held in by an alignment it stands in the box's middle, as the page draws it. In the flow, the margin and padding above and below are the space round the picture's paragraph; on the left they are not written, and the report names them, as it does a barcode's and a page reference's sides. A picture in the flow the layout moves to a new page keeps the space the layout leaves above it there — its margin, its padding, the room above it in its box, the edges of the containers opening with it and the gap before it where the gap did not fit at the foot of the page above — as an empty line that tall before it, kept with it, as a body paragraph does. A picture drawn beside its text is fitted to its box with its padding in it, which the report names too | +| Images | Embedded pictures at the node's declared size. One contained in its box (`fitToBounds`, `CONTAIN`) is embedded at its fitted size, half the room it leaves above and below written as the space round its paragraph and half at its side as its indent; in a band the room below is its paragraph's own, as the band measures what it owes below from the box. In the flow, in a row's cell and held in by an alignment it stands in the box's middle, as the page draws it. In the flow, the margin and padding above and below are the space round the picture's paragraph; on the left they are not written, and the report names them, as it does a barcode's and a page reference's sides. A picture in the flow, a stack of one layer's included, that the layout moves to a new page keeps the space the layout leaves above it there — its margin, its padding, the room above it in its box, the edges of the containers opening with it and the gap before it where the gap did not fit at the foot of the page above — as an empty line that tall before it, kept with it, as a body paragraph does. A picture drawn beside its text is fitted to its box with its padding in it, which the report names too | | Links and anchors | A `linkTarget` becomes a `w:hyperlink` — a relationship for an address, `w:anchor` for one of the document's own anchors — and a run's own link wins over the paragraph's — in a list item as much as in a paragraph. An `anchor(...)` becomes a bookmark wrapping that paragraph's text, named as Word requires; on a section, container, table or image it wraps everything the block wrote, from the start of its first paragraph to the end of its last, so a link to a block lands on its first line. Two anchors that clean to one name, or to a name a suffix gave another, stay two bookmarks; one anchor two nodes declare is one bookmark, the last the file writes one for — the node the page sends a link to and reads a page reference's page from, where that node writes a paragraph to mark — and the report names the anchor, the nodes counted off the document, two cells of one table two of them, and a node of a kind of the caller's own counted where the layout registers it. An anchor in a table's header row the page repeats is drawn again on each page it repeats on, and the page sends a link to the last of them; the file holds the row once, where the table starts, which a link goes to and a page reference reads once Word updates it (measured: the bookmark on page 1, a reference written as 5 reading 1), and the report names it. A `bookmark(...)` outline level becomes Word's own `HeadingN` style, which is what puts the paragraph in the Navigation Pane, the outline view and a generated table of contents. The style states the outline level and nothing else, so the paragraph keeps its own formatting. The role comes from what the document declared, never from how big the text is | | Rows | A one-row table spanning the content width — or only its columns, where fixed columns leave part of the row empty — so editors keep the side-by-side layout. The row's slots become the column grid when they are weights, an even split or fixed columns; fixed columns that add up to less than the row leave the rest of it empty, the last one at its own width and the table no wider than its columns, so its text wraps where the page wraps it; the gap and the row's padding ride in the neighbouring column and come back out as that cell's margin; a cell holds whatever its child is, written as it is anywhere else. The row's `verticalAlign` is every cell's `w:vAlign`, so a child shorter than the row sits at its middle or bottom as on the page — a table of contents' leader on its entry's baseline. A row composed in a table cell (`DocumentTableCell.node(...)`), which the layout places nowhere, that the page divides by what its children measure — an arrangement other than `START`, a spacer that grows, an auto column — takes its columns from where its paragraphs' lines start, the table having laid them out, a spacer where the page spreads the room between them; one holding a child those lines do not place — a picture, a shape, or a spacer in a row of stated columns, which gives it a slot of its own — or written inside a panel or another table in its cell has its columns sized by Word to their text, and the report names it. The row is kept whole across a page break, as the layout keeps it. A row is held at least as tall as the page makes it inside a painted panel, and anywhere its tallest child is a drawing Word holds nothing of in its cell — a badge beside a heading. A section or other container in any cell — a row's, a table's, a panel's — that pulls its first line up with a negative top edge writes that one-line paragraph as much shorter, its text seated where the page sets it — no more than the room above its letters, as Word draws an exact line's text only inside the line. A row that paints its box — `fillColor`, `stroke`, `borders` — is a panel holding its columns (see "What a panel keeps and loses" below): a table of one cell carrying the fill and borders, its margins the row's padding as a panel's are, and in it the columns as a table of their own, without the padding; a corner radius squares, and is named (`corner radius`), and what of its borders above and below Word draws past its box is taken, or named, as a panel's is. A row composed in a table cell, in a page zone's line, in a band of overlapping layers or where a stack's column measures the space round it to its text, with a padding below zero or a column hanging into it, or with a margin below zero above or below it or at a side in a cell, is written as its columns alone, its paint in the report (`row paint`); in the body a row bleeding past the margin is its panel | | Sections / containers | Children written in order. A timeline with its markers on the rail (`markerOnRail()`) lays each entry's body out in the header row's content column, below the row; the body is written in the flow, indented to that column where the page puts it. A container with a fill, per-side borders or a uniform stroke is a one-cell table carrying them, its padding as the cell's margins, so a card keeps its panel — see "What a panel keeps and loses" below. A `keepTogether()` or `keepWithNext()` block the layout placed on one page stays on one page in Word too (`w:keepLines` + `w:keepNext`, and a row that may not split for a panel). A table of one row in the body kept with what follows — a row of columns — whose cells hold paragraphs alone is written with a row that may break: LibreOffice reads a one-row table whose row may not break as a table that may not split, and keeps such a table with nothing (measured: `EditorialProposal`'s page-two masthead stood at the foot of page one in LibreOffice, and all of page two 45 to 47pt high; freed, it opens page two in LibreOffice, Word set it there either way, and moved down to straddle the foot of page one it went to page two whole in both). A row holding a table keeps `w:cantSplit`: the keep chains a cell's own paragraphs, not the rows of a table in it. A box with no paint is only its contents, so a `fixedWidth` narrower than the column is not written: its paragraphs and lists run the column's width, as a panel's in a table cell do, and the report names it. Under an alignment wrapper, or as a layer of a band, the box is held in to where the page placed it. A painted section's bleed is not written: its fill and borders stop at its box, and where the page bleeds it — in the flow it lays out page by page, the body and the panels in it — the report names it. A line drawn as a shape holds no keep: its drawing is anchored in a paragraph near it, a page can end between it and the next block, and in that same flow the report names the keep it loses | diff --git a/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxSemanticBackend.java b/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxSemanticBackend.java index 1ee72708a..5cbba8b90 100644 --- a/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxSemanticBackend.java +++ b/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxSemanticBackend.java @@ -287,6 +287,9 @@ public final class DocxSemanticBackend implements SemanticBackend { private int overTheFlowDepth; // How many of those overlays are layer stacks of one layer, which lay nothing over anything. private int oneLayerDepth; + // How far down the stacks of one layer being written the page sets their layers, which Word + // does not write (layerOffsetDown): a block opening a page in one holds none of it. + private double layerOffsetNotWritten; // How many of the nodes the writer is inside are stacks or shape containers of drawings held // whole (holdTheSpaceOf), whose room holds all they hold. A canvas inside one that only draws // holds no room of its own (writeCanvas). @@ -1093,6 +1096,7 @@ private byte[] write(List sections, Path outputFile) throws Exc bandDepth = 0; overTheFlowDepth = 0; oneLayerDepth = 0; + layerOffsetNotWritten = 0; roomHeldAround = 0; openOverlays.clear(); // An earlier export's lowerings are its own document's. @@ -7436,11 +7440,16 @@ private void writeContainerBody(XWPFDocument document, DocumentNode node) throws } reportTheLayerMoved(node); } + double outerOffset = layerOffsetNotWritten; + if (isOneLayer(node)) { + layerOffsetNotWritten += layerOffsetDown(node); + } try { writeChildren(document, node.children(), spacingOf(node), followedInFlow.remove(node)); } finally { insetLeft = outerLeft; insetRight = outerRight; + layerOffsetNotWritten = outerOffset; } owePendingSpacingAfter(node.margin().bottom() + node.padding().bottom()); // A container that wrote something has had its top edge taken — by its first @@ -10277,8 +10286,10 @@ private void writeParagraph(XWPFDocument document, ParagraphNode node) { // first paragraph opens that page as one in the flow does, and its line is not moved // into the space above it there either. A band's first, where the band opens its page, // is not either (paragraphOpeningABandsPage); in any other overlay it is not moved anyway. - // Its top edge is held in the flow only, as before: in a stack it is not measured. - if (overlayDepth == 0) { + // Its top edge is held in the flow, a stack of one layer's included: there Word dropped + // it as at the top of any page, and a paragraph with a 20pt margin, or the first in a + // stack with a 14pt margin, stood that much high in Word and LibreOffice. + if (overlayDepth == oneLayerDepth) { holdAParagraphsTopEdgeOnItsPage(document, node, 0); } paragraphOpeningItsPage = node; @@ -13222,8 +13233,9 @@ private void writeImage(XWPFDocument document, ImageNode node) throws Exception } double[] room = fitMode == DocumentImageFitMode.CONTAIN ? roomRound(resolved, box) : new double[2]; - if (currentCell == null && overlayDepth == 0 && startsAPageOfItsOwn(node)) { - // Its top edge is held on the page the layout moves it to, as a text paragraph's is. + if (currentCell == null && overlayDepth == oneLayerDepth && startsAPageOfItsOwn(node)) { + // Its top edge is held on the page the layout moves it to, as a text paragraph's is, in + // the flow and in a stack of one layer. holdAParagraphsTopEdgeOnItsPage(document, node, room[0]); } XWPFParagraph para = newBodyParagraph(document); @@ -16769,9 +16781,8 @@ private void reportTheLayerMoved(DocumentNode stack) { moved.add(pointsOf(Math.abs(across)) + "pt " + (across > 0 ? "right" : "left") + " of the stack's edge, in a table cell, whose text Word holds inside it"); } - double lower = box.placementY() + box.placementHeight() - stack.padding().top() - layer.margin().top() - - (placed.placementY() + placed.placementHeight()); - if (Double.isNaN(resumeSpacing) && Math.abs(lower) > 0.5) { + double lower = layerOffsetDown(stack); + if (Math.abs(lower) > 0.5) { moved.add(pointsOf(Math.abs(lower)) + "pt " + (lower > 0 ? "lower" : "higher") + " than its stack starts, without making room for it"); } @@ -16781,6 +16792,23 @@ private void reportTheLayerMoved(DocumentNode stack) { } } + /** + * How far lower than its stack of one layer starts the page sets the layer, in points, higher + * below zero: what Word does not write, which writes the layer where the stack starts. None + * where a band or a column sets the page's distance to the next block written (resumeSpacing), + * which holds the offset, or where either has no place of its own in the layout. + */ + private double layerOffsetDown(DocumentNode stack) { + DocumentNode layer = stack.children().get(0); + com.demcha.compose.document.layout.PlacedNode box = layout.placement(stack); + com.demcha.compose.document.layout.PlacedNode placed = layout.placement(layer); + if (box == null || placed == null || !Double.isNaN(resumeSpacing)) { + return 0; + } + return box.placementY() + box.placementHeight() - stack.padding().top() - layer.margin().top() + - (placed.placementY() + placed.placementHeight()); + } + /** * Holds an alignment's child in across where the page puts it in a table's cell built from a * node, where neither has a place of its own in the layout. @@ -18602,7 +18630,9 @@ private void holdAParagraphsTopEdgeOnItsPage(XWPFDocument document, DocumentNode double inside = Math.max(0, node.padding().top() + room); double own = Math.max(0, node.margin().top() + node.padding().top() + room); double edges = Math.max(0, carriedSpacingBefore); - double above = spaceAboveOnItsPage(node); + // A layer's offset down its stack of one layer is named, not written (reportTheLayerMoved), + // and the line holds none of it either. + double above = spaceAboveOnItsPage(node) - layerOffsetNotWritten; double kept = Double.isNaN(above) ? own + edges : Math.max(0, above) + inside; // Text hanging below a band, a pull out of the block before and a card's border below // it stay on the page above with them, as at a table moved to a new page: the layout diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java new file mode 100644 index 000000000..f89391c9f --- /dev/null +++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java @@ -0,0 +1,248 @@ +package com.demcha.compose.document.backend.semantic.docx; + +import com.demcha.compose.GraphCompose; +import com.demcha.compose.document.api.DocumentSession; +import com.demcha.compose.document.dsl.ImageBuilder; +import com.demcha.compose.document.dsl.PageFlowBuilder; +import com.demcha.compose.document.dsl.ParagraphBuilder; +import com.demcha.compose.document.dsl.SectionBuilder; +import com.demcha.compose.document.image.DocumentImageData; +import com.demcha.compose.document.node.LayerAlign; +import com.demcha.compose.document.style.DocumentInsets; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.junit.jupiter.api.Test; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * The first paragraph or picture of a stack of one layer the layout moves to a new page keeps the + * space the layout leaves above it there, in Word. + * + *

A stack of one layer is written in the flow, and Word drops its first paragraph's space + * above at the top of a page as any other's. Measured in Word 16 and LibreOffice on Windows, the + * first line of a paragraph with a 20pt margin opening such a stack on a new page stood 20pt + * high in both, a picture with one 20pt high, and one in a stack with a 14pt margin 14pt high. + * Held in a line kept with it, as in the flow, each stood where the page sets it. A layer's + * offset in its stack is named and not written, and the line holds none of it.

+ * + * @author Artem Demchyshyn + */ +class DocxStackOfOneLayerOnANewPageTest { + + private static final double EDGE = 12; + + /** + * The page's content is 160pt tall: 300 x 200 with a 20pt margin. A spacer fills 150pt of it, + * and nothing taller than 10pt fits under it. + */ + private static final double CONTENT = 160; + + @Test + void aParagraphsMarginOpeningTheStackIsHeldInALineKeptWithIt() throws Exception { + Consumer content = movedToANewPage(stack -> stack.topLeft(new ParagraphBuilder() + .name("Opening").text("Opening").margin(DocumentInsets.top(EDGE)).build())); + assertThat(startPage(content, "Opening")).as("the premise: the stack opens the second page").isEqualTo(1); + try (XWPFDocument document = export(content)) { + XWPFParagraph opening = paragraphWith(document, "Opening"); + XWPFParagraph line = paragraphBefore(document, opening); + CTSpacing spacing = spacing(line); + + assertThat(line.getText()).isEmpty(); + assertThat(spacing.getLineRule()).isEqualTo(STLineSpacingRule.EXACT); + assertThat(DocxTwips.of(spacing.getLine())).as("the margin, a line's height").isEqualTo(Math.round(EDGE * 20)); + assertThat(line.getCTP().getPPr().isSetKeepNext()).as("kept with the paragraph").isTrue(); + assertThat(before(spacing)).as("the filler's height stays above the line").isEqualTo(owed(CONTENT - 10)); + assertThat(before(spacing(opening))).as("its edge is the line's").isZero(); + } + } + + @Test + void aPicturesMarginOpeningTheStackIsHeld() throws Exception { + try (XWPFDocument document = export(movedToANewPage(stack -> stack.topLeft(new ImageBuilder() + .source(picture()).size(60, 60).margin(DocumentInsets.top(EDGE)).build())))) { + XWPFParagraph picture = pictureIn(document); + + assertThat(lineBefore(document, picture)).isEqualTo(Math.round(EDGE * 20)); + assertThat(before(spacing(picture))).isZero(); + } + } + + @Test + void theStacksOwnMarginIsHeld() throws Exception { + try (XWPFDocument document = export(movedToANewPage(stack -> stack.margin(DocumentInsets.top(EDGE)) + .topLeft(new ParagraphBuilder().text("Opening").build())))) { + XWPFParagraph opening = paragraphWith(document, "Opening"); + + assertThat(lineBefore(document, opening)).as("the stack's margin").isEqualTo(Math.round(EDGE * 20)); + assertThat(before(spacing(opening))).isZero(); + } + } + + @Test + void theStacksPaddingIsHeldWithTheParagraphsMargin() throws Exception { + try (XWPFDocument document = export(movedToANewPage(stack -> stack.padding(DocumentInsets.top(9)) + .topLeft(new ParagraphBuilder().text("Opening").margin(DocumentInsets.top(6)).build())))) { + assertThat(lineBefore(document, paragraphWith(document, "Opening"))).as("9pt and 6pt").isEqualTo(300); + } + } + + @Test + void onlyTheFirstBlockOpensThePage() throws Exception { + Consumer content = movedToANewPage(stack -> stack.topLeft(new SectionBuilder() + .addParagraph(p -> p.name("Opening").text("Opening").margin(DocumentInsets.top(EDGE))) + .addParagraph(p -> p.text("Second").margin(DocumentInsets.top(EDGE))) + .build())); + assertThat(startPage(content, "Opening")).as("the premise: the stack opens the second page").isEqualTo(1); + try (XWPFDocument document = export(content)) { + XWPFParagraph second = paragraphWith(document, "Second"); + + assertThat(paragraphBefore(document, second).getText()).as("no line before the second") + .isEqualTo("Opening"); + } + } + + @Test + void anOffsetDownTheStackIsNotHeld() throws Exception { + // The layer stands 12pt down its stack, which is named, not written: the line holds the + // paragraph's 12pt margin and none of the offset, where the note says Word writes it. + Consumer content = movedToANewPage(stack -> stack.position(new ParagraphBuilder() + .name("Opening").text("Opening").margin(DocumentInsets.top(EDGE)).build(), 0, EDGE, LayerAlign.TOP_LEFT)); + assertThat(startPage(content, "Opening")).as("the premise: the stack opens the second page").isEqualTo(1); + try (XWPFDocument document = export(content)) { + assertThat(lineBefore(document, paragraphWith(document, "Opening"))).as("its margin alone") + .isEqualTo(Math.round(EDGE * 20)); + } + assertThat(DocxExports.report(300, 200, 20, content).bySubject().get("layer offset")) + .as("the offset named").singleElement() + .satisfies(note -> assertThat(note.detail()).contains("12pt lower than its stack starts")); + } + + @Test + void anOffsetUpTheStackLeavesTheStacksEdgeHeld() throws Exception { + // Set 6pt above where its stack's 12pt margin starts it, the layer is written where the + // stack starts, below the whole margin. + try (XWPFDocument document = export(movedToANewPage(stack -> stack.margin(DocumentInsets.top(EDGE)) + .position(new ParagraphBuilder().text("Opening").build(), 0, -6, LayerAlign.TOP_LEFT)))) { + assertThat(lineBefore(document, paragraphWith(document, "Opening"))).as("the stack's margin") + .isEqualTo(Math.round(EDGE * 20)); + } + } + + @Test + void anOffsetAloneLeavesNoLine() throws Exception { + Consumer content = movedToANewPage(stack -> stack.position(new ParagraphBuilder() + .name("Opening").text("Opening").build(), 0, EDGE, LayerAlign.TOP_LEFT)); + assertThat(startPage(content, "Opening")).as("the premise: the stack opens the second page").isEqualTo(1); + try (XWPFDocument document = export(content)) { + assertThat(document.getParagraphs()).extracting(XWPFParagraph::getText) + .as("the filler and the paragraph").containsExactly("", "Opening"); + } + } + + @Test + void anOffsetEndsWithItsStack() throws Exception { + // A stack with its layer set 12pt down opens the first page; the paragraph opening the + // second is in the flow, and its whole margin is held. + try (XWPFDocument document = export(page -> page + .addLayerStack(stack -> stack.position(new ParagraphBuilder().text("Moved").build(), + 0, EDGE, LayerAlign.TOP_LEFT)) + .spacer(0, CONTENT - 20) + .addParagraph(p -> p.text("Opening").margin(DocumentInsets.top(EDGE))))) { + assertThat(lineBefore(document, paragraphWith(document, "Opening"))) + .as("its margin, none of the stack's offset taken off it").isEqualTo(Math.round(EDGE * 20)); + } + } + + @Test + void aParagraphOpeningABandIsLeftToTheBand() throws Exception { + // A stack of two layers is a band, which sets its layers from its own top. + Consumer moved = movedToANewPage(stack -> stack + .topLeft(new ParagraphBuilder().name("Opening").text("Opening").margin(DocumentInsets.top(EDGE)).build()) + .bottomRight(new ParagraphBuilder().text("Caption").build())); + assertThat(startPage(moved, "Opening")).as("the premise: the band opens the second page").isEqualTo(1); + try (XWPFDocument document = export(moved); + XWPFDocument onOnePage = DocxExports.withLayout(300, 600, 20, moved)) { + assertThat(document.getParagraphs().indexOf(paragraphWith(document, "Opening"))) + .as("no line of the flow's held before it") + .isEqualTo(onOnePage.getParagraphs().indexOf(paragraphWith(onOnePage, "Opening"))); + } + } + + /** A stack under a 150pt filler, which the layout moves to the second page. */ + private static Consumer movedToANewPage( + java.util.function.UnaryOperator stack) { + return page -> page.spacer(0, CONTENT - 10).addLayerStack(builder -> stack.apply(builder)); + } + + private static XWPFDocument export(Consumer content) throws Exception { + return DocxExports.withLayout(300, 200, 20, content); + } + + private static int startPage(Consumer content, String name) { + try (DocumentSession session = GraphCompose.document().pageSize(300, 200).margin(DocumentInsets.of(20)).create()) { + session.pageFlow(content::accept); + return session.layoutGraph().nodes().stream() + .filter(node -> name.equals(node.semanticName())).findFirst().orElseThrow().startPage(); + } + } + + /** The height of the exact line holding a block's top edge, in twips. */ + private static long lineBefore(XWPFDocument document, XWPFParagraph paragraph) { + CTSpacing spacing = spacing(paragraphBefore(document, paragraph)); + assertThat(spacing.getLineRule()).as("a line holding its edge").isEqualTo(STLineSpacingRule.EXACT); + return DocxTwips.of(spacing.getLine()); + } + + /** A spacer's paragraph is a tenth of a point tall, in twips (see holdToHairline). */ + private static final long HAIRLINE = 2; + + /** + * The space owed above the block after the filler, in twips: {@code points} of it, less the + * filler's own hairline, which is part of its height. + */ + private static long owed(double points) { + return Math.round(points * 20) - HAIRLINE; + } + + private static XWPFParagraph paragraphWith(XWPFDocument document, String text) { + return document.getParagraphs().stream().filter(p -> p.getText().equals(text)).findFirst().orElseThrow(); + } + + private static XWPFParagraph pictureIn(XWPFDocument document) { + return document.getParagraphs().stream() + .filter(paragraph -> paragraph.getRuns().stream().anyMatch(run -> !run.getEmbeddedPictures().isEmpty())) + .findFirst().orElseThrow(); + } + + private static XWPFParagraph paragraphBefore(XWPFDocument document, XWPFParagraph paragraph) { + List paragraphs = document.getParagraphs(); + return paragraphs.get(paragraphs.indexOf(paragraph) - 1); + } + + private static CTSpacing spacing(XWPFParagraph paragraph) { + return paragraph.getCTP().getPPr().getSpacing(); + } + + private static long before(CTSpacing spacing) { + return spacing != null && spacing.isSetBefore() ? DocxTwips.of(spacing.getBefore()) : 0; + } + + private static DocumentImageData picture() { + BufferedImage image = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB); + ByteArrayOutputStream png = new ByteArrayOutputStream(); + try { + javax.imageio.ImageIO.write(image, "png", png); + } catch (java.io.IOException failure) { + throw new java.io.UncheckedIOException(failure); + } + return DocumentImageData.fromBytes(png.toByteArray()); + } +} From e3783e0db523b6470e580e4ddfe51abcb5045a5e Mon Sep 17 00:00:00 2001 From: DemchaAV Date: Tue, 20 Oct 2026 11:15:04 +0100 Subject: [PATCH 2/2] test(docx): keep a pull above on its page for a stack opening the next A plain paragraph opening a stack of one layer on a new page now leaves a pull out of the block above on that block's page, as one in the flow does: the report no longer names it as standing lower there. The test pins both sides: named on the paragraph's page, not on the next. --- CHANGELOG.md | 3 +++ .../DocxStackOfOneLayerOnANewPageTest.java | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47503d293..1045306a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ follow semantic versioning; release dates are ISO 8601. - The space is now held in a line kept with the first block, as in the flow, the stack's own edges with it. Each stands where the page sets it, and the page breaks where it did. - A layer's offset in its stack, up or down, is named as before, and not held. + - A pull out of the block on the page above stays on that page, as it does in the flow. The + report no longer says it stands the stack's first paragraph lower, which on the new page it + does not. - **A picture, a shape or a barcode composed in a table cell keeps its own size.** The layout gave a node composed in a table cell (`DocumentTableCell.node`) the cell's inner width, and the height it measured. In a 120pt column padded 4pt, the page drew: diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java index f89391c9f..ae65ac918 100644 --- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java +++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackOfOneLayerOnANewPageTest.java @@ -161,6 +161,24 @@ void anOffsetEndsWithItsStack() throws Exception { } } + @Test + void aPullOutOfTheBlockOnThePageAboveStaysThere() throws Exception { + // The paragraph above pulls what follows it 5pt up. On its page, Word sets no block over + // another, and the report says so; the stack the layout moves to the next page starts + // that page at its top, and nothing stands it lower. + Consumer content = page -> page + .spacer(0, CONTENT - 20) + .addParagraph(p -> p.text("Above").margin(new DocumentInsets(0, 0, -5, 0))) + .addLayerStack(stack -> stack.topLeft(new ParagraphBuilder().name("Opening").text("Opening") + .build())); + assertThat(startPage(content, "Opening")).as("the premise: the stack opens the second page").isEqualTo(1); + + assertThat(DocxExports.report(300, 600, 20, content).bySubject().get("space above")) + .as("on the page of the block above, the pull is named").isNotNull(); + assertThat(DocxExports.report(300, 200, 20, content).bySubject().get("space above")) + .as("on the next page, nothing is").isNull(); + } + @Test void aParagraphOpeningABandIsLeftToTheBand() throws Exception { // A stack of two layers is a band, which sets its layers from its own top.