From de4a35a269dfa5c825f66af8d32b670ea34e4ec3 Mon Sep 17 00:00:00 2001
From: DemchaAV
Date: Thu, 8 Oct 2026 20:42:08 +0100
Subject: [PATCH 1/3] fix(docx): raise a line Word sets low into the space
above it, where both editors keep it
- Word and LibreOffice stand an exact line's baseline four fifths of the
way down it whatever the face (measured on the fifteen template faces and
JetBrains Mono, 8 to 36pt, and in the corpus's lines from Word's own line
tops). The text was moved to the page's baseline by its position only:
half points, left alone under half a point, and scaled in LibreOffice by
the face's height over its em (Spectral 1.53, Poppins 1.49).
- raiseIntoTheSpaceAbove moves a line Word sets low by 0.1pt or more up
into its paragraph's w:before and owes as much below it, so what follows
stays; what the space cannot give stays on the position where the whole
difference calls for one. A line set high keeps its position.
- Not a paragraph that is not its Word paragraph's alone, a line in an
overlay, a line cut to fit, a paragraph the layout moves to a new page or
breaks over one. A column's later layer takes back the raise the line
above it still owes.
- Tests: the raise, what is owed, the floor, the exclusions and the column
resume; the space tests that write default text allow for its raise
(DocxExports.DEFAULT_LINE_RAISE, pinned from the layout's seat).
- Word and LibreOffice (Windows) fidelity baselines rewritten: Word 27
documents nearer, LibreOffice 21; the recipe's Line height row and the
CHANGELOG.
- assets/readme/examples/word-export-companion.docx re-rendered: its
spaces around raised lines move by the raise.
---
CHANGELOG.md | 30 +
.../examples/word-export-companion.docx | Bin 10199 -> 10223 bytes
docs/recipes/docx-export.md | 2 +-
.../libreoffice-windows-lines.tsv | 734 +++++++++---------
.../docx-fidelity/libreoffice-windows.tsv | 56 +-
.../docx-fidelity/word-windows-lines.tsv | 682 ++++++++--------
.../resources/docx-fidelity/word-windows.tsv | 62 +-
.../semantic/docx/DocxSemanticBackend.java | 121 ++-
.../backend/semantic/docx/DocxTextBands.java | 6 +-
.../semantic/docx/DocxAdjacentTablesTest.java | 7 +-
.../semantic/docx/DocxBaselineSeatTest.java | 244 +++++-
.../semantic/docx/DocxCanvasRoomTest.java | 28 +-
.../semantic/docx/DocxContainerPaintTest.java | 3 +-
.../docx/DocxContainerSpacingTest.java | 21 +-
.../semantic/docx/DocxDrawingsTest.java | 14 +-
.../backend/semantic/docx/DocxExports.java | 11 +
.../semantic/docx/DocxInlinePictureTest.java | 4 +-
.../semantic/docx/DocxLayerColumnsTest.java | 77 +-
.../semantic/docx/DocxLineHeightTest.java | 6 +-
.../semantic/docx/DocxLinePairTest.java | 6 +-
.../semantic/docx/DocxLineSurplusTest.java | 9 +-
.../semantic/docx/DocxOverTheFlowTest.java | 3 +-
.../semantic/docx/DocxOverlayBandTest.java | 12 +-
.../semantic/docx/DocxPanelTailTest.java | 10 +-
.../semantic/docx/DocxPortraitTest.java | 11 +-
.../semantic/docx/DocxRowOverhangTest.java | 10 +-
.../semantic/docx/DocxRowPaintTest.java | 3 +-
.../backend/semantic/docx/DocxRuleTest.java | 6 +-
.../docx/DocxSpaceAboveOnANewPageTest.java | 5 +-
.../docx/DocxSpaceOnANewPageTest.java | 8 +-
.../semantic/docx/DocxStackedLayersTest.java | 8 +-
.../docx/DocxVerticalSpacingTest.java | 41 +-
32 files changed, 1365 insertions(+), 875 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d0957a8e..0b209efce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,36 @@ follow semantic versioning; release dates are ISO 8601.
### Public API
+- **A DOCX export raises a line Word sets low into the space above it, where both editors keep
+ it.** Both editors stand an exact line's baseline four fifths of the way down it whatever the
+ face — measured on the fifteen faces the templates use and JetBrains Mono, 8 to 36pt — and the
+ page sets it the face's ascent below the line's top. The text was moved to the page's baseline by
+ its position, which counts in half points and was left alone under half a point: by its position
+ alone Helvetica's lines, which the page seats 0.78 of the way down, stood 0.12 to 0.38pt low in
+ Word. And LibreOffice moves raised text further than it is raised, by the face's height over its
+ em — Spectral's 1.53 times, Poppins' 1.49, Volkhov's 1.31 (measured) — so Spectral's 24pt line,
+ raised 4pt, stood 2.4pt high there (measured).
+ - A line Word sets low by a tenth of a point or more is moved up into the space written above
+ it, written to the twip, and that space is owed below it, so what follows stays where it was.
+ Both editors keep a paragraph's space above as written. What the space cannot give is left to
+ the position where the whole difference calls for one, as is a line Word sets high: moved
+ down, it would take its room out of the space below it, which is not known when it is written.
+ - A column's later layer, which measures the space to itself from the page, takes back the raise
+ of the line above it.
+ - Not a line pair's shared line, which moved would move its other half; not a line in a band, a
+ shape container, a canvas or a text box, whose writers measure what follows them from the page;
+ not a line cut to fit, a stack's or one held to its pictures; and not a paragraph the layout
+ moves to a new page, whose space above Word drops there, or breaks over one, whose lines on
+ the next page the space above does not move.
+
+ In the DOCX fidelity corpus 27 documents stand nearer the page in Word, the sum of their medians
+ 1.6pt nearer — `letter-blue_banner`'s median line from 0.39pt to 0.18pt, `cv-modern_professional`'s
+ from 0.32pt to 0.18pt — and 21 in LibreOffice on Windows, `cv-modern_professional`'s from 0.28pt
+ to 0.04pt. Two move a step of Word's grid further: `invoice-luma_studio`'s company lines, raised
+ where the page sets them, now show their block standing 0.3pt high (median 0.13pt to 0.14pt),
+ and `letter-panel`'s median from 0.14pt to 0.16pt; in LibreOffice two medians move 0.01pt. The
+ report names nothing more.
+
- **A DOCX export no longer stands what follows a width anchor, or a paragraph Word sets taller,
lower than the page.** Both reached past the block in Word, and neither was taken out of the
space below or named. Each now hangs below its block, as a line held to its icon does: the
diff --git a/assets/readme/examples/word-export-companion.docx b/assets/readme/examples/word-export-companion.docx
index d1c8545af93c3169078a1e790de4dabcd3fe5d07..944d2de0ebca094c6c01b7d629466fe3b1cd2a98 100644
GIT binary patch
delta 3574
zcmY*cc{mhY7oRZ(W63^Q!^~Kc?913+CE54gNOsw>M`#*Un24m+Zze
zgd(zLADVpSec$itJI`~Ud+zU?d(L_8{pa_?8*CfU8R~$@SpZa2Q~>wanw4~DAn4a#
zod9GzcalrUKK=%hLqQ1ip#HizgNB{+mp~K2GSLVjI;@{Ph%5%ipy){N<;^_1OZz%J
zbmLtV&zx8z;Gg>FXpSK?X;^2%3qpVfC%
zuN@Jgr1aj<4!kUf*1?C|Oz-i1b{K*^od;h(P%t|AORp8#oC)YmOXH-g-xKxW|3Ep)
zw12ouFM~&aX5Vg8h-~Hj(Pv8#&0XNnp|l2N?@D7VCTgX_K(2xdWW%-JrCCnL`DNq?
zO9@*$YfWcBUNL3__7kY9~*NM0$)ed&{Em~@MW6lr*f{q4{<9=+KoaLJlH&2Gp
zCxH)Gt8OdsRjLoepcZ@j&LU`MzhxwhEg1q8v%2O`FY6Q*!S6)uc_DR4APcNc#fyyL
zD!2AhVAlPttsx*ErQh?t>95Dx}Uh*DMt`o>Ap_K1RRN=Z9Ut(^t>;
z+10|*vyb%FQjFTNBiMX(viTOg;7W^g!9kPLG$BQPtt>0c|5iPTk0nUFA~#gXCJ(OL`El{$qQvp;nR^xD#R^@zTXHZn;|y}eSXj?5bX3#{n9AZiIc(YmpdDuN*ws)v)x&^I&LHoH^OavWgAWBCY#@em6Dn+tD8O8
zQlniBLMX{mdN&(+?Hd4}55fKlXL#tvs(QhR8tKsI8lb@tmpJt0c=>W+i`kslxAiTe
ztL@NUhRj_@1-GIp@D1IU0Q
zX-s1gg4
ztUD@6MZkgVN-0s9z5R`>U_xoP;BZvOk*2D4%*C1V;dqMGM}8Ia0oW&eBq5S^FLC5z
z{X~-q4ydaAZC3@z8b#x2iJ>mHXTxj-#`Ci~x-SaC3X?`}TFD1zP%H6UAi3joGKVdP
zpEaT99<1%H@ViFpsWwU_%v+)N_l~Q)=ZT#9*HgLL?mfSu!SZ&!01GYctSPZECX`I1
zMM>QsCGeVXpmk!o4>_*#f2&keO}j^qWf=y>FLxvI{XhWu%GNNKhU{-@)UnyIL1)rG
z7eY$#rAN2!nh|oK1;TSGGpJh)NiK2|oHdh)=c*6s~6^_#vQ
A line Word sets low is raised first by moving it up into the space written above it
+ * ({@link #raiseIntoTheSpaceAbove}), to the twip. What that space cannot give, and a line set
+ * high, is left to the text's position, which counts in half points: a line whose difference
+ * is under {@link #LEAST_BASELINE_SHIFT_POINTS} — a quarter point for a line of Lato body text
+ * — keeps no position, as every line of body text moved by one would win a quarter point at
+ * most.
*
* @param lineTopAbove how far above the page's first line the Word line starts, in points
* @param heldExact whether the line was cut to its pictures' reach, and so is seated
* however little
+ * @param ownsItsLine whether the Word paragraph holds this paragraph's text alone, and so
+ * its line can move for it
*/
private double shiftToThePagesBaseline(XWPFParagraph para, ParagraphNode node, double lineTopAbove,
- boolean heldExact) {
+ boolean heldExact, boolean ownsItsLine) {
CTPPr properties = para.getCTP().getPPr();
if (properties == null || !properties.isSetSpacing()) {
return 0;
@@ -9446,12 +9474,79 @@ private double shiftToThePagesBaseline(XWPFParagraph para, ParagraphNode node, d
// to fit its letters where the page sets them, and is seated however little; so
// is one cut to its pictures' reach, whose ink stands at its edges.
boolean cutToFit = lineTopAbove != 0 || stackedLineHeights.containsKey(node) || heldExact;
- return Math.abs(shift) < LEAST_BASELINE_SHIFT_POINTS && !cutToFit ? 0 : shift;
+ // The position is moved as before where the whole shift called for it, whatever
+ // the space above took off it: a line 0.6pt low with 0.2pt above it is left a tenth
+ // off by its position, not four tenths.
+ boolean moved = Math.abs(shift) >= LEAST_BASELINE_SHIFT_POINTS || cutToFit;
+ if (ownsItsLine && !cutToFit && node != paragraphOpeningItsPage && layout.onOnePage(node)) {
+ shift -= raiseIntoTheSpaceAbove(spacing, shift);
+ }
+ return moved ? shift : 0;
}
}
return 0;
}
+ /**
+ * Raises a paragraph's line by moving it up into the space written above it, by as much of
+ * {@code raise} as that space holds, and owes as much below the paragraph: the line moves,
+ * what follows stays.
+ *
+ *
A text's position is no way to move it a quarter point. It counts in half points, so a
+ * line a quarter point low — Helvetica's lines, which the page seats 0.78 of the way down,
+ * stood 0.12 to 0.38pt low in Word at 8 to 18pt — is moved a half point or not at all. And
+ * LibreOffice moves raised text further than it is raised, by the face's height over its em:
+ * Spectral's 1.53 times, Poppins' 1.49, Volkhov's 1.31 (measured), so Spectral's 24pt line,
+ * raised 4pt, stood 2.4pt high there. Both editors set a paragraph its space above below what
+ * comes before it, to the twip, and an exact line's baseline four fifths of the way down it
+ * ({@link DocxTextBands#BASELINE_SHARE}): a line moved up that space stands where the page
+ * sets it in both.
+ *
+ *
Only a raise: a line moved down takes its room out of the space below it, which is not
+ * known until what follows is written, and what that space could not take would stand all of
+ * it lower. Only a paragraph in the flow or in a cell, where the space owed below it is the
+ * space above what follows: a band, a shape container, a canvas and the text laid over the
+ * flow — the overlays — measure what follows them from the page ({@link #writeOverlayBand}),
+ * and the space a line owed inside them would be lost. A column's later layer measures the
+ * space to itself from the page too, and takes back the raise of the line above it
+ * ({@link #raiseOwedByTheLastLine}). Not a paragraph the layout moves to a new page: Word drops
+ * its space above there ({@link #holdAParagraphsTopEdgeOnItsPage}), and what the line owed
+ * would stand all below it lower. Not a paragraph the layout breaks over a page: its lines on
+ * the next page start at that page's top, where the space above moves none of them, and what
+ * it owed would stand what follows them lower. Less than
+ * {@link #LEAST_RAISE_INTO_THE_SPACE_ABOVE} is not moved.
+ *
+ * @param spacing the paragraph's spacing, its space above already written
+ * @param raise how far Word sets the line below the page's, in points
+ * @return how far the line was raised, in points
+ */
+ private double raiseIntoTheSpaceAbove(CTSpacing spacing, double raise) {
+ // A band and the text laid over the flow are overlays too (writeOverlayBand, writeOverTheFlow).
+ if (!(raise >= LEAST_RAISE_INTO_THE_SPACE_ABOVE) || overlayDepth > 0) {
+ return 0;
+ }
+ long room = twipsOf(spacing.isSetBefore() ? spacing.getBefore() : null);
+ long raised = Math.min(room, Math.round(raise * POINT_TO_TWIP));
+ if (raised < Math.round(LEAST_RAISE_INTO_THE_SPACE_ABOVE * POINT_TO_TWIP)) {
+ return 0;
+ }
+ spacing.setBefore(BigInteger.valueOf(room - raised));
+ owePendingSpacingAfter(raised / POINT_TO_TWIP);
+ lastRaise = raised / POINT_TO_TWIP;
+ blocksAtTheLastRaise = blocksWritten;
+ return raised / POINT_TO_TWIP;
+ }
+
+ /**
+ * What the line written last owes below it for its raise into the space above it
+ * ({@link #raiseIntoTheSpaceAbove}), in points, while no block has been written after it: a
+ * column's later layer measures the space to itself from the page and drops what the layers
+ * above owe, and the line above it was set that much higher than the page sets it.
+ */
+ private double raiseOwedByTheLastLine() {
+ return blocksWritten == blocksAtTheLastRaise ? lastRaise : 0;
+ }
+
/**
* Sets a run's letters closer by the room the shapes beside it take past their boxes.
*
@@ -12748,10 +12843,12 @@ private void writeLayerColumns(XWPFDocument document,
carriedSpacingBefore += node.margin().top() + node.padding().top();
} else {
// What the layers above still owe below themselves is space
- // the page does not have: the gap to this one is the page's.
+ // the page does not have: the gap to this one is the page's,
+ // from a last line set as high as it was raised.
+ double raised = raiseOwedByTheLastLine();
pendingSpacingAfter = 0;
pullBelow = 0;
- resumeSpacing = plan.resume(node);
+ resumeSpacing = plan.resume(node) + raised;
}
// A column layer is written as what it holds, never dispatched itself:
// no bookmark goes round it, though bookmarkedAnchorsIn counts one.
diff --git a/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxTextBands.java b/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxTextBands.java
index f707380bd..204ddcc93 100644
--- a/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxTextBands.java
+++ b/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxTextBands.java
@@ -33,8 +33,10 @@ final class DocxTextBands {
* Where both editors stand the baseline in an exact line, as a share of the line from its
* top. Measured, it is four fifths of the line whatever the face and size: Spectral, Lato
* and Arial at 10 to 46pt, in lines 12 to 100pt tall, within 0.1pt of it in Word and on it in
- * LibreOffice. A band's line is placed by it here, and a paragraph's text is moved from it to
- * the page's baseline ({@code DocxSemanticBackend#shiftToThePagesBaseline}).
+ * LibreOffice; and again on the fifteen faces the templates use and JetBrains Mono at 8 to
+ * 36pt, within 0.04pt of it in Word in median, and in the lines of the DOCX fidelity corpus,
+ * read off Word's own line tops. A band's line is placed by it here, and a paragraph's text is
+ * moved from it to the page's baseline ({@code DocxSemanticBackend#shiftToThePagesBaseline}).
*/
static final double BASELINE_SHARE = 0.8;
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxAdjacentTablesTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxAdjacentTablesTest.java
index 5a0aa03eb..0dbe93a63 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxAdjacentTablesTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxAdjacentTablesTest.java
@@ -97,9 +97,10 @@ void spaceOwedBelowATableGoesBelowItNotAboveIt() throws Exception {
XWPFParagraph title = document.getParagraphs().get(0);
var spacing = title.getCTP().getPPr().getSpacing();
- assertThat(spacing == null || !spacing.isSetAfter())
- .as("the card's bottom padding is below its table, not between its title and the table")
- .isTrue();
+ assertThat(spacing != null && spacing.isSetAfter() ? DocxTwips.of(spacing.getAfter()) : 0)
+ .as("the card's bottom padding is below its table, not between its title and the table:"
+ + " only what the title's line owes below it for its raise")
+ .isEqualTo(DocxExports.DEFAULT_LINE_RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBaselineSeatTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBaselineSeatTest.java
index 4c813abd3..57e301243 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBaselineSeatTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBaselineSeatTest.java
@@ -1,6 +1,10 @@
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.ParagraphBuilder;
+import com.demcha.compose.document.layout.payloads.ParagraphFragmentPayload;
+import com.demcha.compose.document.layout.payloads.ParagraphLine;
import com.demcha.compose.document.dsl.ShapeContainerBuilder;
import com.demcha.compose.document.node.LayerAlign;
import com.demcha.compose.document.style.ClipPolicy;
@@ -12,6 +16,8 @@
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
+import java.util.List;
+
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
@@ -28,6 +34,12 @@ class DocxBaselineSeatTest {
private static final double SPECTRAL_ASCENT = 1.059;
/** Spectral's own line, in ems: its ascent and 463 units of descent. */
private static final double SPECTRAL_LINE = 1.522;
+ /** Lato's ascent, in ems: 1974 of 2000 units. */
+ private static final double LATO_ASCENT = 0.987;
+ /** Poppins' ascent, in ems: 1050 of 1000 units. */
+ private static final double POPPINS_ASCENT = 1.05;
+ /** Gothic A1's ascent, in ems: 798 of 1000 units, its own line one em. */
+ private static final double GOTHIC_A1_ASCENT = 0.798;
private static DocumentTextStyle spectral(double size) {
return DocumentTextStyle.builder().fontName(FontName.SPECTRAL).size(size).build();
@@ -112,19 +124,245 @@ void theHalfOfALinePairSetLowerIsSeatedFromTheLinesTop() throws Exception {
@Test
void linesThatTookTheirGapFromTheSpaceAboveAreSeatedFromTheHigherTop() throws Exception {
// Two lines 10pt apart under 20pt of space: Word's lines take their gaps from above and
- // start 10pt above the page's first line.
+ // start 10pt above the page's first line, and are raised into the 10pt left above them.
try (XWPFDocument document = DocxExports.withLayout(240, 600, 20, page -> page
.addParagraph(p -> p.text("First line of it and second line of it").textStyle(spectral(20))
.lineSpacing(10).margin(new DocumentInsets(20, 0, 0, 0))))) {
XWPFParagraph text = paragraph(document, "First line of it and second line of it");
double line = line(text);
+ double raise = 0.8 * line - 10 - SPECTRAL_ASCENT * 20;
assertThat(line).as("the premise: two lines, each its gap taller").isGreaterThan(40);
- assertThat(position(text)).isCloseTo((int) Math.round((0.8 * line - 10 - SPECTRAL_ASCENT * 20) * 2),
- within(1));
+ assertThat(raise).as("the premise: Word's baseline is the lower, by less than the space left")
+ .isBetween(0.5, 10.0);
+ assertThat(before(text)).isCloseTo(Math.round((10 - raise) * 20), within(1L));
+ assertThat(position(text)).isZero();
+ }
+ }
+
+ @Test
+ void aLineWordSetsLowIsRaisedIntoTheSpaceAboveItAndOwesItBelow() throws Exception {
+ // 20pt above a 30pt Spectral title: Word's baseline stands nearly 5pt below the page's.
+ // The line moves up that much of the space, to the twip, where its position would move
+ // it in half points, and LibreOffice that half again; Lato under it, which Word sets high
+ // and so is never moved down, stands where the page does all the same.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Lead").textStyle(lato(10)))
+ .addParagraph(p -> p.text("Title").textStyle(spectral(30)).margin(DocumentInsets.top(20)))
+ .addParagraph(p -> p.text("Body").textStyle(lato(10))))) {
+ XWPFParagraph title = paragraph(document, "Title");
+ double raise = 0.8 * line(title) - SPECTRAL_ASCENT * 30;
+
+ assertThat(raise).as("the premise: Word's baseline is the lower, by less than the space")
+ .isBetween(1.0, 20.0);
+ assertThat(before(title)).isCloseTo(Math.round((20 - raise) * 20), within(1L));
+ assertThat(position(title)).as("nothing left to its position").isZero();
+ assertThat(before(paragraph(document, "Body"))).as("what the title owes below it")
+ .isCloseTo(Math.round(raise * 20), within(1L));
+ assertThat(position(paragraph(document, "Body"))).isZero();
+ }
+ }
+
+ @Test
+ void whatTheSpaceAboveCannotGiveIsLeftToThePosition() throws Exception {
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Lead").textStyle(lato(10)))
+ .addParagraph(p -> p.text("Title").textStyle(spectral(30)).margin(DocumentInsets.top(2)))
+ .addParagraph(p -> p.text("Body").textStyle(lato(10))))) {
+ XWPFParagraph title = paragraph(document, "Title");
+ double raise = 0.8 * line(title) - SPECTRAL_ASCENT * 30;
+
+ assertThat(before(title)).as("all of the 2pt").isZero();
+ assertThat(position(title)).isCloseTo((int) Math.round((raise - 2) * 2), within(1));
+ assertThat(before(paragraph(document, "Body"))).as("the 2pt the line took").isEqualTo(40);
+ }
+ }
+
+ @Test
+ void whatTheSpaceAboveLeavesOfAShiftOverHalfAPointKeepsItsPosition() throws Exception {
+ // Poppins at 10pt stands 0.7pt low in Word: under 0.4pt of space the line takes the 0.4pt,
+ // and the 0.3pt left is still moved by its position, a half point, not left 0.3pt low.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Lead").textStyle(lato(10)))
+ .addParagraph(p -> p.text("Low").textStyle(DocumentTextStyle.builder().fontName(FontName.POPPINS)
+ .size(10).build()).margin(DocumentInsets.top(0.4))))) {
+ XWPFParagraph low = paragraph(document, "Low");
+ double raise = 0.8 * line(low) - POPPINS_ASCENT * 10;
+
+ assertThat(raise).as("the premise: over half a point, and the space under it").isBetween(0.5, 0.9);
+ assertThat(before(low)).isZero();
+ assertThat(position(low)).isEqualTo((int) Math.round((raise - 0.4) * 2)).isPositive();
+ }
+ }
+
+ @Test
+ void aParagraphTheLayoutBreaksOverAPageKeepsTheSpaceAboveIt() throws Exception {
+ // Its lines on the next page start at that page's top: the space above moves none of them.
+ String text = "A title long enough to run onto a second line and a third one";
+ try (DocumentSession session = GraphCompose.document().pageSize(400, 600).margin(DocumentInsets.of(20)).create()) {
+ session.pageFlow(page -> page.spacer(1, 500)
+ .addParagraph(p -> p.name("Broken").text(text).textStyle(spectral(30)).margin(DocumentInsets.top(10))));
+ var placed = session.layoutGraph().nodes().stream()
+ .filter(node -> "Broken".equals(node.semanticName())).findFirst().orElseThrow();
+ try (XWPFDocument document = new XWPFDocument(
+ new java.io.ByteArrayInputStream(session.export(new DocxSemanticBackend())))) {
+ XWPFParagraph broken = paragraph(document, text);
+
+ assertThat(placed.endPage()).as("the premise: broken over a page").isGreaterThan(placed.startPage());
+ assertThat(before(broken)).as("the spacer's height past its hairline, and its own 10pt, whole")
+ .isEqualTo(Math.round((500 - 0.1 + 10) * 20));
+ assertThat(position(broken)).as("raised by its position, on both pages").isPositive();
+ }
+ }
+ }
+
+ @Test
+ void aRaiseUnderATenthOfAPointLeavesTheSpaceAboveAsWritten() throws Exception {
+ // Gothic A1's page seat is within a few hundredths of Word's four fifths: Word sets lines
+ // on a grid 0.12pt apart, and a twip less of space would move the line a step or nothing.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Lead").textStyle(lato(10)))
+ .addParagraph(p -> p.text("Even").textStyle(DocumentTextStyle.builder().fontName(FontName.GOTHIC_A1)
+ .size(14).build()).margin(DocumentInsets.top(10))))) {
+ XWPFParagraph even = paragraph(document, "Even");
+ double raise = 0.8 * line(even) - GOTHIC_A1_ASCENT * 14;
+
+ assertThat(raise).as("the premise: Word's baseline lower by a twip and more, under a tenth")
+ .isBetween(0.025, 0.1);
+ assertThat(before(even)).isEqualTo(200);
+ }
+ }
+
+ @Test
+ void aLineWordSetsHighKeepsTheSpaceAboveIt() throws Exception {
+ // Lato's ascent is 0.82 of its line: at 24pt Word's baseline stands 0.65pt above the
+ // page's. Moved down into the space above, the line would take that from the space
+ // below it, not known yet; it is lowered by its position, the space as written.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Lead").textStyle(lato(10)))
+ .addParagraph(p -> p.text("Heading").textStyle(lato(24)).margin(DocumentInsets.top(10))))) {
+ XWPFParagraph heading = paragraph(document, "Heading");
+ double raise = 0.8 * line(heading) - LATO_ASCENT * 24;
+
+ assertThat(raise).as("the premise: Word's baseline is the higher, by more than half a point")
+ .isLessThan(-0.5);
+ assertThat(before(heading)).isEqualTo(200);
+ assertThat(position(heading)).isEqualTo((int) Math.round(raise * 2));
+ }
+ }
+
+ @Test
+ void aLinePairKeepsTheSpaceAboveTheLineItsHalvesShare() throws Exception {
+ // A 30pt value, the line's first and tallest text, beside a 12pt label share one Word
+ // line: the value's raise moved into the space above would move the label with it.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Above").textStyle(lato(10)).margin(DocumentInsets.bottom(20)))
+ .add(new ShapeContainerBuilder().name("Row").rectangle(360, 60)
+ .clipPolicy(ClipPolicy.OVERFLOW_VISIBLE)
+ .position(new ParagraphBuilder().name("Value").text("Value").textStyle(spectral(30)).build(),
+ 0, 0, LayerAlign.CENTER_LEFT)
+ .position(new ParagraphBuilder().name("Label").text("Label").textStyle(spectral(12)).build(),
+ 0, 0, LayerAlign.CENTER_RIGHT)
+ .build()))) {
+ XWPFParagraph pair = document.getParagraphs().stream()
+ .filter(paragraph -> paragraph.getText().contains("Value")).findFirst().orElseThrow();
+ CTR value = pair.getRuns().stream().filter(run -> run.text().contains("Value")).findFirst()
+ .orElseThrow().getCTR();
+
+ double raise = 0.8 * line(pair) - SPECTRAL_ASCENT * 30;
+
+ assertThat(pair.getText()).as("the premise: one line").contains("Label");
+ assertThat(before(pair)).as("the premise: room above the line to move it into").isGreaterThan(400);
+ assertThat(positionOf(value)).as("the value raised by its own position, the line where it stood")
+ .isCloseTo((int) Math.round(raise * 2), within(1));
}
}
+ @Test
+ void aLineInALayerStackKeepsTheSpaceAboveIt() throws Exception {
+ // A stack measures what follows it from the page: a raise owed below a line inside it
+ // would not reach what follows.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Above").textStyle(lato(10)))
+ .addLayerStack(stack -> stack.name("Stack")
+ .back(new com.demcha.compose.document.dsl.ShapeBuilder().name("Backdrop").size(200, 80).build())
+ .layer(new ParagraphBuilder().name("Title").text("Title").textStyle(spectral(30))
+ .margin(DocumentInsets.top(20)).build(), LayerAlign.TOP_LEFT)))) {
+ XWPFParagraph title = paragraph(document, "Title");
+ double raise = 0.8 * line(title) - SPECTRAL_ASCENT * 30;
+
+ assertThat(raise).as("the premise: Word's baseline is the lower").isGreaterThan(1);
+ assertThat(position(title)).as("raised by its position").isCloseTo((int) Math.round(raise * 2), within(1));
+ }
+ }
+
+ @Test
+ void theLastLineOfACellOwesItsRaiseInsideTheCell() throws Exception {
+ // A column's last paragraph raised into the space above it owes that space below it, in
+ // its cell: the cell is as tall as before, and nothing below the row moves.
+ try (XWPFDocument document = DocxExports.withLayout(400, 600, 20, page -> page
+ .addParagraph(p -> p.text("Lead").textStyle(lato(10)))
+ .addRow(row -> row
+ .addParagraph(p -> p.text("Left").textStyle(spectral(30)).margin(DocumentInsets.top(20)))
+ .addParagraph(p -> p.text("Right").textStyle(lato(10))))
+ .addParagraph(p -> p.text("Below").textStyle(lato(10))))) {
+ List cell = document.getTables().get(0).getRow(0).getCell(0).getParagraphs();
+ XWPFParagraph left = cell.get(cell.size() - 1);
+ double raise = 0.8 * line(left) - SPECTRAL_ASCENT * 30;
+
+ assertThat(left.getText()).as("the premise: the column's last paragraph").isEqualTo("Left");
+
+ assertThat(before(left)).isCloseTo(Math.round((20 - raise) * 20), within(1L));
+ assertThat(after(left)).isCloseTo(Math.round(raise * 20), within(1L));
+ assertThat(position(left)).isZero();
+ assertThat(before(paragraph(document, "Below"))).as("nothing of the raise below the row").isZero();
+ }
+ }
+
+ @Test
+ void aLineOfTheDefaultTextIsRaisedByWhatTheSpacingTestsAllowFor() throws Exception {
+ assertThat(raiseOf(DocumentTextStyle.DEFAULT)).isEqualTo(DocxExports.DEFAULT_LINE_RAISE);
+ assertThat(raiseOf(DocumentTextStyle.DEFAULT.withSize(7))).isEqualTo(DocxExports.SMALL_LINE_RAISE);
+ }
+
+ /**
+ * How far Word stands a line of {@code style} below the page, in twips: four fifths of the
+ * line it is written at, against the page's baseline in its laid-out line.
+ */
+ private static long raiseOf(DocumentTextStyle style) throws Exception {
+ try (DocumentSession session = GraphCompose.document().pageSize(400, 600).margin(DocumentInsets.of(20)).create()) {
+ session.pageFlow(page -> page.addParagraph(p -> p.text("Line").textStyle(style)));
+ ParagraphLine line = session.layoutGraph().fragments().stream()
+ .map(fragment -> fragment.payload())
+ .filter(ParagraphFragmentPayload.class::isInstance)
+ .map(payload -> ((ParagraphFragmentPayload) payload).lines().get(0))
+ .findFirst()
+ .orElseThrow();
+ try (XWPFDocument document = new XWPFDocument(
+ new java.io.ByteArrayInputStream(session.export(new DocxSemanticBackend())))) {
+ double written = line(paragraph(document, "Line"));
+ double pageSeat = line.lineHeight() - line.baselineOffsetFromBottom();
+ return Math.round((0.8 * written - pageSeat) * 20);
+ }
+ }
+ }
+
+ private static DocumentTextStyle lato(double size) {
+ return DocumentTextStyle.builder().fontName(FontName.LATO).size(size).build();
+ }
+
+ private static long before(XWPFParagraph paragraph) {
+ var properties = paragraph.getCTP().getPPr();
+ return properties == null || !properties.isSetSpacing() || !properties.getSpacing().isSetBefore() ? 0
+ : DocxTwips.of(properties.getSpacing().getBefore());
+ }
+
+ private static long after(XWPFParagraph paragraph) {
+ var properties = paragraph.getCTP().getPPr();
+ return properties == null || !properties.isSetSpacing() || !properties.getSpacing().isSetAfter() ? 0
+ : DocxTwips.of(properties.getSpacing().getAfter());
+ }
+
@Test
void linesWhoseGapIsSharedOutAreSeatedAtTheMiddleOne() throws Exception {
// Two lines 10pt apart with no space above to give: Word's lines are each 5pt taller
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxCanvasRoomTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxCanvasRoomTest.java
index f6d9a31d0..1dc573ec9 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxCanvasRoomTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxCanvasRoomTest.java
@@ -57,6 +57,12 @@
class DocxCanvasRoomTest {
private static final DocumentColor INK = DocumentColor.rgb(26, 86, 148);
+ /**
+ * What a line of the default text in the flow is raised into the space above it, in points
+ * ({@link DocxExports#DEFAULT_LINE_RAISE}): the gap Word writes above it is that much less
+ * than the page's.
+ */
+ private static final double RAISE = DocxExports.DEFAULT_LINE_RAISE / 20.0;
@Test
void whatFollowsACanvasStartsBelowItsRoomNotBelowWhatItWrites() throws Exception {
@@ -66,7 +72,7 @@ void whatFollowsACanvasStartsBelowItsRoomNotBelowWhatItWrites() throws Exception
assertThat(gapInWord(exported.document(), "Caption", "Below"))
.as("the canvas's room under its caption")
- .isCloseTo(gapOnThePage(exported.layout(), "Caption", "Below"), within(0.1))
+ .isCloseTo(gapOnThePage(exported.layout(), "Caption", "Below") - RAISE, within(0.1))
.isGreaterThan(80);
assertThat(exported.report().bySubject()).doesNotContainKey("CanvasLayerNode");
}
@@ -84,7 +90,7 @@ void aCanvasWithPaddingAndMarginHoldsItsWholeBox() throws Exception {
assertThat(gapInWord(exported.document(), "Above", "Caption")).as("its top margin and padding")
.isCloseTo(gapOnThePage(exported.layout(), "Above", "Caption"), within(0.1));
assertThat(gapInWord(exported.document(), "Caption", "Below")).as("its room, padding and margin below")
- .isCloseTo(gapOnThePage(exported.layout(), "Caption", "Below"), within(0.1));
+ .isCloseTo(gapOnThePage(exported.layout(), "Caption", "Below") - RAISE, within(0.1));
}
@Test
@@ -96,8 +102,8 @@ void aCanvasThatOnlyDrawsHoldsItsWholeRoom() throws Exception {
.add(paragraph("Below")));
assertThat(gapInWord(exported.document(), "Above", "Below"))
- .isCloseTo(gapOnThePage(exported.layout(), "Above", "Below"), within(0.1))
- .isCloseTo(80, within(0.1));
+ .isCloseTo(gapOnThePage(exported.layout(), "Above", "Below") - RAISE, within(0.1))
+ .isCloseTo(80 - RAISE, within(0.1));
assertThat(exported.report().bySubject()).doesNotContainKey("CanvasLayerNode");
}
@@ -112,7 +118,7 @@ void aCanvasThatOnlyDrawsHoldsItsBoxOnceWhatItDrawsInHasEdgesToo() throws Except
.add(paragraph("Below")));
assertThat(gapInWord(exported.document(), "Above", "Below"))
- .isCloseTo(gapOnThePage(exported.layout(), "Above", "Below"), within(0.1));
+ .isCloseTo(gapOnThePage(exported.layout(), "Above", "Below") - RAISE, within(0.1));
}
@Test
@@ -130,7 +136,7 @@ void aCanvasInAStackOfOneLayerHoldsItsRoomInTheFlow() throws Exception {
.add(paragraph("Caption")).build(), LayerAlign.TOP_LEFT)));
assertThat(gapInWord(writing.document(), "Caption", "Below"))
- .isCloseTo(gapOnThePage(writing.layout(), "Caption", "Below"), within(0.1))
+ .isCloseTo(gapOnThePage(writing.layout(), "Caption", "Below") - RAISE, within(0.1))
.isGreaterThan(40);
assertThat(gapInWord(drawing.document(), "Above", "Caption")).as("the canvas only draws, the caption under it")
.isCloseTo(gapOnThePage(drawing.layout(), "Above", "Caption"), within(0.1))
@@ -200,7 +206,7 @@ void aCanvasThatOnlyDrawsEndingAShapeContainersLayerHoldsItsRoomThere() throws E
.add(paragraph("Below")));
assertThat(gapInWord(exported.document(), "Title", "Below"))
- .isCloseTo(gapOnThePage(exported.layout(), "Title", "Below"), within(0.1))
+ .isCloseTo(gapOnThePage(exported.layout(), "Title", "Below") - RAISE, within(0.1))
.isGreaterThan(100);
}
@@ -280,7 +286,7 @@ void aCanvasThatOnlyDrawsOpeningALaterLayerOfAColumnHoldsItsRoom() throws Except
.add(paragraph("Below")));
assertThat(gapInWord(exported.document(), "Heading", "Caption"))
- .isCloseTo(gapOnThePage(exported.layout(), "Heading", "Caption"), within(0.1))
+ .isCloseTo(gapOnThePage(exported.layout(), "Heading", "Caption") - RAISE, within(0.1))
.isGreaterThan(40);
}
@@ -314,7 +320,7 @@ void aCanvasThatOnlyDrawsInsideAnotherCanvasHoldsNoRoomOfItsOwn() throws Excepti
assertThat(before(caption) + lineOf(caption) + gapInWord(exported.document(), "Caption", "Below"))
.as("the outer canvas's height, its caption written at its corner")
- .isCloseTo(placed(exported.layout(), "Outer").placementHeight(), within(0.1));
+ .isCloseTo(placed(exported.layout(), "Outer").placementHeight() - RAISE, within(0.1));
assertThat(detailOf(exported.report())).isEqualTo("written as its contents; what it writes is written "
+ "from its corner, one block after another, not where it places it");
}
@@ -364,9 +370,9 @@ void aCanvasThatOnlyDrawsInsideWhatIsHeldWholeHoldsNoRoomOfItsOwn() throws Excep
.add(paragraph("Below")));
assertThat(gapInWord(inACanvas.document(), "Above", "Below")).as("the outer canvas's room")
- .isCloseTo(gapOnThePage(inACanvas.layout(), "Above", "Below"), within(0.1));
+ .isCloseTo(gapOnThePage(inACanvas.layout(), "Above", "Below") - RAISE, within(0.1));
assertThat(gapInWord(inAStack.document(), "Above", "Below")).as("the stack's room")
- .isCloseTo(gapOnThePage(inAStack.layout(), "Above", "Below"), within(0.1));
+ .isCloseTo(gapOnThePage(inAStack.layout(), "Above", "Below") - RAISE, within(0.1));
}
@Test
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerPaintTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerPaintTest.java
index 8711114cf..91d5946e6 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerPaintTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerPaintTest.java
@@ -303,7 +303,8 @@ void theCardsTopAndBottomMarginAreTheSpaceAroundTheTable() throws Exception {
assertThat(DocxTwips.of(lead.getCTP().getPPr().getSpacing().getAfter()))
.as("Word has no space above a table, so the paragraph before it holds it")
.isEqualTo(9 * 20L);
- assertThat(DocxTwips.of(after.getCTP().getPPr().getSpacing().getBefore())).isEqualTo(9 * 20L);
+ assertThat(DocxTwips.of(after.getCTP().getPPr().getSpacing().getBefore()))
+ .isEqualTo(9 * 20L - DocxExports.DEFAULT_LINE_RAISE);
CTPPr properties = after.getCTP().getPPr();
assertThat(properties.isSetShd()).as("the paint ends where the card ends").isFalse();
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerSpacingTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerSpacingTest.java
index f0009b039..965f5090d 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerSpacingTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxContainerSpacingTest.java
@@ -33,6 +33,8 @@
class DocxContainerSpacingTest {
private static final long NINE_POINTS = 9 * 20L;
+ /** What a line of the default text is raised into the space above it, and owes below. */
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
@Test
void aSectionsSpacingStandsBetweenEachTwoOfItsChildren() throws Exception {
@@ -47,8 +49,9 @@ void aSectionsSpacingStandsBetweenEachTwoOfItsChildren() throws Exception {
assertThat(paragraphs).extracting(XWPFParagraph::getText)
.containsExactly("Contact", "Skills", "Languages");
assertThat(before(paragraphs.get(0))).as("nothing above the first child").isZero();
- assertThat(before(paragraphs.get(1))).isEqualTo(NINE_POINTS);
- assertThat(before(paragraphs.get(2))).isEqualTo(NINE_POINTS);
+ assertThat(before(paragraphs.get(1))).isEqualTo(NINE_POINTS - RAISE);
+ assertThat(before(paragraphs.get(2))).as("raised as far as the line above it was")
+ .isEqualTo(NINE_POINTS);
}
}
@@ -78,7 +81,7 @@ void aPanelsSpacingStandsBetweenTheChildrenInItsCell() throws Exception {
List paragraphs = written(cell.getParagraphs());
assertThat(paragraphs).extracting(XWPFParagraph::getText).containsExactly("First", "Second");
- assertThat(before(paragraphs.get(1))).isEqualTo(NINE_POINTS);
+ assertThat(before(paragraphs.get(1))).isEqualTo(NINE_POINTS - RAISE);
}
}
@@ -95,7 +98,7 @@ void aPageBreakTakesNoSpacingBeforeItAndTheNextPageStartsItsSpacingDown() throws
List paragraphs = written(document.getParagraphs());
assertThat(after(paragraphs.get(0))).isZero();
- assertThat(before(paragraphs.get(1))).isEqualTo(NINE_POINTS);
+ assertThat(before(paragraphs.get(1))).isEqualTo(NINE_POINTS - RAISE);
}
}
@@ -117,7 +120,7 @@ void aSpacerIsItsHeightAndNotALineOfTextAsWell() throws Exception {
assertThat(spacing.getLineRule().toString()).isEqualTo("exact");
assertThat(DocxTwips.of(spacing.getLine())).as("a tenth of a point").isEqualTo(2L);
assertThat(DocxTwips.of(spacing.getLine()) + before(all.get(2)))
- .as("the hairline and the space above the next entry, the spacer's height").isEqualTo(90L);
+ .as("the hairline and the space above the next entry, the spacer's height").isEqualTo(90L - RAISE);
}
}
@@ -137,7 +140,7 @@ void theSpaceBelowASpacerOfNoHeightTakesItsHairline() throws Exception {
assertThat(spacer.getText()).isEmpty();
assertThat(before(spacer) + DocxTwips.of(spacer.getCTP().getPPr().getSpacing().getLine()) + before(all.get(2)))
.as("the section's spacing either side of the spacer, its hairline included")
- .isEqualTo(2 * NINE_POINTS);
+ .isEqualTo(2 * NINE_POINTS - RAISE);
}
}
@@ -157,7 +160,7 @@ void theSpaceUnderACardsOpeningSpacerOfNoHeightTakesItsHairline() throws Excepti
assertThat(cell.getParagraphs()).extracting(XWPFParagraph::getText).containsExactly("", "Title");
assertThat(DocxTwips.of(spacer.getCTP().getPPr().getSpacing().getLine()) + before(cell.getParagraphs().get(1)))
- .as("the card's spacing under the anchor, its hairline included").isEqualTo(NINE_POINTS);
+ .as("the card's spacing under the anchor, its hairline included").isEqualTo(NINE_POINTS - RAISE);
}
}
@@ -214,7 +217,7 @@ void aSpacerUnderATableInACellIsTheTablesCloserAndItsHeightOnce() throws Excepti
assertThat(content.get(content.indexOf(spacer) - 1)).as("right under the table")
.isInstanceOf(XWPFTable.class);
assertThat(DocxTwips.of(spacer.getCTP().getPPr().getSpacing().getLine()) + after(spacer) + before(after))
- .as("the hairline and the space below it, the spacer's height").isEqualTo(200L);
+ .as("the hairline and the space below it, the spacer's height").isEqualTo(200L - RAISE);
}
}
@@ -273,7 +276,7 @@ void aShapeContainersEdgesAreSpaceAroundWhatItHolds() throws Exception {
// The row stands at the top of the 20pt outline, which holds 7.05pt more under it.
assertThat(before(paragraph(document, "Java")))
.as("the outline under its row, its bottom padding and margin, above the paragraph after it")
- .isEqualTo(8 * 20L + Math.round(7.05 * 20));
+ .isEqualTo(8 * 20L + Math.round(7.05 * 20) - RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxDrawingsTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxDrawingsTest.java
index f2ed0d175..7bbe1c53c 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxDrawingsTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxDrawingsTest.java
@@ -180,9 +180,10 @@ void aTitleBesideItsBadgeStandsWhereThePageCentresItInTheHeader() throws Excepti
.isCloseTo(Math.round((above.placementY() - title.placementY() - title.placementHeight()) * 20),
org.assertj.core.data.Offset.offset(2L));
assertThat(twipsAfter(document, "EXPERIENCE") + twipsBefore(document, "Below"))
- .as("from the title past the header's foot to the line below, as on the page")
- .isCloseTo(Math.round((title.placementY() - below.placementY() - below.placementHeight()) * 20),
- org.assertj.core.data.Offset.offset(3L));
+ .as("from the title past the header's foot to the line below, as on the page, less that"
+ + " line's raise into it")
+ .isCloseTo(Math.round((title.placementY() - below.placementY() - below.placementHeight()) * 20)
+ - DocxExports.DEFAULT_LINE_RAISE, org.assertj.core.data.Offset.offset(3L));
assertThat(header.placementHeight()).isEqualTo(40);
}
}
@@ -217,9 +218,10 @@ void aBadgeAloneInTheFlowKeepsItsPlaceWithItsGlyphDrawnOverIt() throws Exception
assertThat(document.getDocument().xmlText()).doesNotContain(" 0
? ((Number) text.getCTR().getRPr().getPositionArray(0).getVal()).intValue() : 0;
+ // The line below is raised into the space above it, and that is no reach of the icon's.
return new Between(pageLine, DocxTwips.of(iconed.getLine()) / 20.0,
3 - DocxTwips.of(iconed.getBefore()) / 20.0,
- 3 - (after.isSetBefore() ? DocxTwips.of(after.getBefore()) : 0) / 20.0, textPosition);
+ 3 - ((after.isSetBefore() ? DocxTwips.of(after.getBefore()) : 0) + DocxExports.SMALL_LINE_RAISE) / 20.0,
+ textPosition);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLayerColumnsTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLayerColumnsTest.java
index df43c505c..ba93049aa 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLayerColumnsTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLayerColumnsTest.java
@@ -35,6 +35,8 @@ class DocxLayerColumnsTest {
private static final double MARGIN = 20;
private static final double SIDEBAR = 120;
private static final double MAIN = PAGE_WIDTH - 2 * MARGIN - SIDEBAR;
+ /** What a line of the default text in a column is raised into the space above it. */
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
/** A paragraph long enough to fill its column, so the stack is as wide as the page's. */
private static final String LONG = "Led the delivery of a document platform across three teams, "
+ "from the first prototype to the release that replaced the old reporting stack.";
@@ -64,6 +66,73 @@ void sideBySideLayersAreTheCellsOfOneRow() throws Exception {
}
}
+ @Test
+ void aLaterLayerStandsBelowTheLineAboveItAsFarAsThatLineWasRaised() throws Exception {
+ // The first layer's line, Spectral under 20pt of space, is moved up into that space and
+ // owes as much below it. The later layer measures the gap to itself from the page, where
+ // that line stood lower, so it takes the raise back with the gap.
+ com.demcha.compose.document.style.DocumentTextStyle spectral = com.demcha.compose.document.style
+ .DocumentTextStyle.builder().fontName(com.demcha.compose.font.FontName.SPECTRAL).size(30).build();
+ com.demcha.compose.document.style.DocumentTextStyle lato = com.demcha.compose.document.style
+ .DocumentTextStyle.builder().fontName(com.demcha.compose.font.FontName.LATO).size(10).build();
+ try (Export export = export(stack -> stack
+ .layer(column("TitleLayer", SIDEBAR, 0, top -> top.addParagraph(p -> p.name("Title").text("Title")
+ .textStyle(spectral).margin(DocumentInsets.top(20)))), LayerAlign.TOP_LEFT)
+ .layer(column("Sidebar", 0, MAIN, side -> side.addParagraph("Contact")), LayerAlign.TOP_LEFT)
+ .layer(column("MainLayer", SIDEBAR, 0, main -> main
+ .addSpacer(spacer -> spacer.name("TitlePlace").width(100).height(80))
+ .addParagraph(p -> p.name("Role").text("Engineer").textStyle(lato))), LayerAlign.TOP_LEFT))) {
+ XWPFTableCell main = export.document().getTables().get(0).getRow(0).getCell(1);
+ XWPFParagraph title = main.getParagraphs().get(0);
+ double line = org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule.EXACT
+ .equals(title.getCTP().getPPr().getSpacing().getLineRule())
+ ? DocxTwips.of(title.getCTP().getPPr().getSpacing().getLine()) / 20.0 : Double.NaN;
+ double raise = 0.8 * line - 1.059 * 30;
+ PlacedNode placedTitle = export.placed("Title");
+ PlacedNode role = export.placed("Role");
+ double gap = placedTitle.placementY() - (role.placementY() + role.placementHeight());
+
+ assertThat(main.getParagraphs()).extracting(XWPFParagraph::getText).containsExactly("Title", "Engineer");
+ assertThat(spacingBefore(title)).as("the premise: the title raised into the space above it")
+ .isCloseTo(Math.round((20 - raise) * 20), org.assertj.core.data.Offset.offset(1L));
+ assertThat(spacingBefore(main.getParagraphs().get(1)))
+ .isCloseTo(Math.round((gap + raise) * 20), org.assertj.core.data.Offset.offset(2L));
+ }
+ }
+
+ @Test
+ void aLaterLayerUnderAPanelTakesNoRaiseThePanelAlreadyOwedInside() throws Exception {
+ // The first layer ends in a painted card whose line is raised: the card's cell owes the
+ // raise below that line, inside the card, and the later layer's gap from the card's foot
+ // is the page's alone.
+ com.demcha.compose.document.style.DocumentTextStyle spectral = com.demcha.compose.document.style
+ .DocumentTextStyle.builder().fontName(com.demcha.compose.font.FontName.SPECTRAL).size(30).build();
+ com.demcha.compose.document.style.DocumentTextStyle lato = com.demcha.compose.document.style
+ .DocumentTextStyle.builder().fontName(com.demcha.compose.font.FontName.LATO).size(10).build();
+ try (Export export = export(stack -> stack
+ .layer(column("CardLayer", SIDEBAR, 0, top -> top.addSection("Card", card -> card
+ .fillColor(DocumentColor.rgb(238, 243, 249)).padding(DocumentInsets.of(4))
+ .addParagraph(p -> p.name("Title").text("Title").textStyle(spectral)
+ .margin(DocumentInsets.top(20))))), LayerAlign.TOP_LEFT)
+ .layer(column("Sidebar", 0, MAIN, side -> side.addParagraph("Contact")), LayerAlign.TOP_LEFT)
+ .layer(column("MainLayer", SIDEBAR, 0, main -> main
+ .addSpacer(spacer -> spacer.name("CardPlace").width(100).height(100))
+ .addParagraph(p -> p.name("Role").text("Engineer").textStyle(lato))), LayerAlign.TOP_LEFT))) {
+ XWPFTableCell main = export.document().getTables().get(0).getRow(0).getCell(1);
+ XWPFParagraph role = main.getParagraphs().stream()
+ .filter(paragraph -> "Engineer".equals(paragraph.getText())).findFirst().orElseThrow();
+ XWPFParagraph title = main.getTables().get(0).getRow(0).getCell(0).getParagraphs().stream()
+ .filter(paragraph -> "Title".equals(paragraph.getText())).findFirst().orElseThrow();
+ PlacedNode card = export.placed("Card");
+ PlacedNode placedRole = export.placed("Role");
+ double gap = card.placementY() - (placedRole.placementY() + placedRole.placementHeight());
+
+ assertThat(spacingBefore(title)).as("the premise: the title raised into the space above it")
+ .isLessThan(20 * 20L);
+ assertThat(spacingBefore(role)).isCloseTo(Math.round(gap * 20), org.assertj.core.data.Offset.offset(2L));
+ }
+ }
+
@Test
void layersSharingABandFollowOneAnotherAndTheStandInIsLeftOut() throws Exception {
// The name is drawn first, in a layer of its own; the main column holds its place with
@@ -88,7 +157,7 @@ void layersSharingABandFollowOneAnotherAndTheStandInIsLeftOut() throws Exception
double gap = name.placementY() - (role.placementY() + role.placementHeight());
assertThat(gap).as("the page puts the role below the name").isGreaterThan(10);
assertThat(spacingBefore(main.getParagraphs().get(1)))
- .isCloseTo(Math.round(gap * 20), org.assertj.core.data.Offset.offset(1L));
+ .isCloseTo(Math.round(gap * 20) - RAISE, org.assertj.core.data.Offset.offset(1L));
}
}
@@ -114,7 +183,7 @@ void aDrawingThatOpensALaterLayerKeepsItsRoomBelowTheResume() throws Exception {
double gap = name.placementY() - (placedRole.placementY() + placedRole.placementHeight());
assertThat(gap).as("the portrait stands between them on the page").isGreaterThan(30);
- assertThat(spacingBefore(role)).isCloseTo(Math.round(gap * 20), org.assertj.core.data.Offset.offset(2L));
+ assertThat(spacingBefore(role)).isCloseTo(Math.round(gap * 20) - RAISE, org.assertj.core.data.Offset.offset(2L));
}
}
@@ -162,7 +231,7 @@ void aStandInAtTheFootOfAnEarlierLayerIsNotWhereTheGapIsMeasuredFrom() throws Ex
.containsExactly("Ada Lovelace", "Engineer", LONG);
assertThat(gap).isGreaterThan(5);
assertThat(spacingBefore(main.getParagraphs().get(1)))
- .isCloseTo(Math.round(gap * 20), org.assertj.core.data.Offset.offset(1L));
+ .isCloseTo(Math.round(gap * 20) - RAISE, org.assertj.core.data.Offset.offset(1L));
}
}
@@ -179,7 +248,7 @@ void theFirstLayerKeepsItsTopEdgeAndTheStackItsLeftOne() throws Exception {
.addParagraph(LONG)), LayerAlign.TOP_LEFT))) {
XWPFTable table = export.document().getTables().get(0);
- assertThat(spacingBefore(table.getRow(0).getCell(0).getParagraphs().get(0))).isEqualTo(25 * 20L);
+ assertThat(spacingBefore(table.getRow(0).getCell(0).getParagraphs().get(0))).isEqualTo(25 * 20L - RAISE);
assertThat(table.getCTTbl().getTblPr().isSetTblInd()).as("the table is indented").isTrue();
assertThat(DocxTwips.of(table.getCTTbl().getTblPr().getTblInd().getW())).isEqualTo(16 * 20L);
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineHeightTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineHeightTest.java
index 4144153cd..51592a384 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineHeightTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineHeightTest.java
@@ -138,7 +138,8 @@ void theGapBetweenAParagraphsLinesIsInItsLinesAndTakenOnceFromAboveIt() throws E
XWPFParagraph with = gapped.getParagraphs().get(1);
assertThat(lineTwips(with)).isEqualTo(lineTwips(without) + 4 * 20L);
- assertThat(before(with)).isEqualTo(before(without) - 4 * 20L);
+ assertThat(before(with)).as("the 10pt above it, less the gap its lines took")
+ .isEqualTo((10 - 4) * 20L);
}
}
@@ -234,7 +235,8 @@ void aWrappedParagraphInACellLeavesTheSpaceAfterTheTableAlone() throws Exception
XWPFParagraph after = document.getParagraphs().stream()
.filter(paragraph -> "After".equals(paragraph.getText())).findFirst().orElseThrow();
- assertThat(before(after)).as("the space above it is its own, whole").isEqualTo(10 * 20L);
+ assertThat(before(after)).as("the space above it is its own, whole, less its line's raise into it")
+ .isEqualTo(10 * 20L - DocxExports.DEFAULT_LINE_RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLinePairTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLinePairTest.java
index 1241461bf..ce46edae9 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLinePairTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLinePairTest.java
@@ -400,7 +400,8 @@ void theHangReachesTheNextBlockOnlyNotThePageAfterABreak() throws Exception {
XWPFParagraph after = document.getParagraphs().stream()
.filter(paragraph -> "After".equals(paragraph.getText())).findFirst().orElseThrow();
- assertThat(before(after)).as("a new page: its 10pt whole").isEqualTo(10L * 20);
+ assertThat(before(after)).as("a new page: its 10pt whole, less its line's raise into it")
+ .isEqualTo(10L * 20 - DocxExports.DEFAULT_LINE_RAISE);
}
}
@@ -415,7 +416,8 @@ void theHangStaysInTheCellItHangsIn() throws Exception {
XWPFParagraph beside = document.getTables().get(0).getRow(0).getCell(1).getParagraphs().stream()
.filter(paragraph -> "Beside".equals(paragraph.getText())).findFirst().orElseThrow();
- assertThat(before(beside)).as("its 10pt whole").isEqualTo(10L * 20);
+ assertThat(before(beside)).as("its 10pt whole, less its line's raise into it")
+ .isEqualTo(10L * 20 - DocxExports.DEFAULT_LINE_RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineSurplusTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineSurplusTest.java
index cc5bddb85..16180465c 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineSurplusTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxLineSurplusTest.java
@@ -37,6 +37,8 @@ class DocxLineSurplusTest {
/** The page's content: 400 x 600 with a 20pt margin. */
private static final double CONTENT = 560;
+ /** What the default text's line after the paragraph is raised into the space above it, in points. */
+ private static final double RAISE = DocxExports.DEFAULT_LINE_RAISE / 20.0;
@Test
void theSpaceBelowAParagraphWordSetsTallerTakesTheDifference() throws Exception {
@@ -45,7 +47,7 @@ void theSpaceBelowAParagraphWordSetsTallerTakesTheDifference() throws Exception
assertThat(surplus).as("the premise: Word's lines at the tallest pass the page's").isGreaterThan(1);
assertThat(before(paragraph(exported.document(), "After")) / 20.0).as("the gap less what Word's lines pass the page by")
- .isCloseTo(20 - surplus, within(0.05));
+ .isCloseTo(20 - surplus - RAISE, within(0.05));
assertThat(exported.report().bySubject().get("space above")).isNull();
}
@@ -106,7 +108,7 @@ void theSpaceBelowAParagraphOfOneSizeTakesWhatItsRoundingAdds() throws Exception
double surplus = Math.round(page / line) * line - page;
assertThat(before(paragraph(exported.document(), "After")) / 20.0).as("the gap less what the lines pass the page by")
- .isCloseTo(20 - surplus, within(0.05));
+ .isCloseTo(20 - surplus - RAISE, within(0.05));
assertThat(exported.report().bySubject().get("space above")).isNull();
}
@@ -116,7 +118,8 @@ void aParagraphWrittenAtItsTallestLineOwesNothingForItsRounding() throws Excepti
// the page: owed, that rounding stood ModernInvoice's lines a step of Word's grid lower.
Exported exported = rounded(surplus -> surplus < -0.15);
- assertThat(before(paragraph(exported.document(), "After"))).as("the gap alone").isEqualTo(400);
+ assertThat(before(paragraph(exported.document(), "After"))).as("the gap alone")
+ .isEqualTo(400 - DocxExports.DEFAULT_LINE_RAISE);
}
@Test
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverTheFlowTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverTheFlowTest.java
index eeb046332..93971d7ce 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverTheFlowTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverTheFlowTest.java
@@ -75,7 +75,8 @@ void aLinePulledUpInItTakesNothingFromTheFlowAfterIt() throws Exception {
.addSection("Head", head -> head.padding(DocumentInsets.top(6)).addParagraph("Masthead")))) {
assertThat(document.getDocument().getBody().xmlText()).as("the line is in a text box")
.contains("");
- assertThat(before(masthead(document))).as("the section's space above it").isEqualTo(6 * 20L);
+ assertThat(before(masthead(document))).as("the section's space above it, less its line's raise into it")
+ .isEqualTo(6 * 20L - DocxExports.DEFAULT_LINE_RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverlayBandTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverlayBandTest.java
index bfe8f6714..b8158b234 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverlayBandTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxOverlayBandTest.java
@@ -34,6 +34,8 @@
class DocxOverlayBandTest {
private static final double BADGE = 80;
+ /** What a line of the default text in the flow is raised into the space above it. */
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
@Test
void aBadgeOverItsPlaceHolderIsWrittenWhereThePageDrawsIt() throws Exception {
@@ -51,7 +53,7 @@ void aBadgeOverItsPlaceHolderIsWrittenWhereThePageDrawsIt() throws Exception {
assertThat(before(paragraphs.get(1))).as("the initials sit where the ring centres them")
.isCloseTo(Math.round((6 + above) * 20), org.assertj.core.data.Offset.offset(2L));
assertThat(before(paragraphs.get(2))).as("and the badge keeps its height below them")
- .isCloseTo(Math.round((below + 12) * 20), org.assertj.core.data.Offset.offset(2L));
+ .isCloseTo(Math.round((below + 12) * 20) - RAISE, org.assertj.core.data.Offset.offset(2L));
}
}
@@ -82,7 +84,7 @@ void aBandNestedUnderADrawingIsMeasuredPastItsOwnPlaceHolder() throws Exception
assertThat(before(paragraphs.get(1))).as("the initials where the ring centres them")
.isCloseTo(Math.round((6 + above) * 20), org.assertj.core.data.Offset.offset(2L));
assertThat(before(paragraphs.get(2))).as("and the badge's height below them")
- .isCloseTo(Math.round(below * 20), org.assertj.core.data.Offset.offset(2L));
+ .isCloseTo(Math.round(below * 20) - RAISE, org.assertj.core.data.Offset.offset(2L));
}
}
@@ -174,7 +176,7 @@ void aDrawingThatIsNotWrittenStillTakesItsRoom() throws Exception {
XWPFParagraph below = document.getParagraphs().stream()
.filter(paragraph -> "Below".equals(paragraph.getText())).findFirst().orElseThrow();
- assertThat(before(below)).isEqualTo(50L * 20);
+ assertThat(before(below)).isEqualTo(50L * 20 - RAISE);
}
}
@@ -241,7 +243,7 @@ void aShapeContainersStackedLinesStandWhereTheOutlineSetsThem() throws Exception
assertThat(before(initial)).as("written from where the ring sets the first initial")
.isCloseTo(Math.round(above * 20), org.assertj.core.data.Offset.offset(2L));
assertThat(before(after)).as("and the ring's foot as far under the last as the page has it")
- .isCloseTo(Math.round((below + gap) * 20), org.assertj.core.data.Offset.offset(2L));
+ .isCloseTo(Math.round((below + gap) * 20) - RAISE, org.assertj.core.data.Offset.offset(2L));
}
}
@@ -291,7 +293,7 @@ void theLastLayersNegativeBottomEdgeIsTakenOnceBelowTheBand() throws Exception {
XWPFParagraph below = document.getParagraphs().stream()
.filter(paragraph -> "Below".equals(paragraph.getText())).findFirst().orElseThrow();
- assertThat(before(below)).isEqualTo((10 - 4) * 20L);
+ assertThat(before(below)).isEqualTo((10 - 4) * 20L - RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPanelTailTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPanelTailTest.java
index abf05cf60..ea09ac118 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPanelTailTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPanelTailTest.java
@@ -47,6 +47,8 @@ class DocxPanelTailTest {
private static final SvgIcon ICON = SvgIcon.parse("");
private static final DocumentTextStyle SMALL = DocumentTextStyle.DEFAULT.withSize(7);
+ /** What the default text's line after a panel is raised into the space above it. */
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
@Test
void aPaddedCardsBorderBelowComesOutOfItsPaddingWhereNoSpaceTakesIt() throws Exception {
@@ -68,7 +70,7 @@ void theSpaceBelowACardTakesItsBorderBeforeItsPaddingDoes() throws Exception {
assertThat(exported.report().bySubject()).doesNotContainKey("space above");
assertThat(bottomMargin(panel(exported))).as("its padding, less half the border").isEqualTo(3 * 20);
- assertThat(before(paragraph(exported, "After"))).as("the gap, less half the border").isEqualTo(9 * 20);
+ assertThat(before(paragraph(exported, "After"))).as("the gap, less half the border").isEqualTo(9 * 20 - RAISE);
}
@Test
@@ -339,7 +341,7 @@ void aPanelsHangingLastLineComesOutOfItsPaddingBelow() throws Exception {
assertThat(down).as("the line reaches below the page's").isPositive();
assertThat(bottomMargin(panel(exported))).as("the padding less the reach").isEqualTo(5 * 20 - down);
- assertThat(before(paragraph(exported, "After"))).as("the whole gap").isEqualTo(10 * 20);
+ assertThat(before(paragraph(exported, "After"))).as("the whole gap").isEqualTo(10 * 20 - RAISE);
}
@Test
@@ -351,7 +353,7 @@ void aPanelsHangingLastLineWithNoPaddingTakesTheGapUnderIt() throws Exception {
long down = reachBelow(exported, "Iconed");
assertThat(down).as("the line reaches below the page's").isPositive();
- assertThat(before(paragraph(exported, "After"))).as("the gap, less the reach").isEqualTo(10 * 20 - down);
+ assertThat(before(paragraph(exported, "After"))).as("the gap, less the reach").isEqualTo(10 * 20 - down - RAISE);
assertThat(exported.report().bySubject()).doesNotContainKey("space above");
}
@@ -446,7 +448,7 @@ void aMarginBelowZeroUnderAPanelPullsWhatFollowsUp() throws Exception {
.addParagraph(p -> p.name("After").text("After")));
assertThat(bottomMargin(panel(exported))).isEqualTo(8 * 20);
- assertThat(before(paragraph(exported, "After"))).as("the gap, less the pull").isEqualTo(6 * 20);
+ assertThat(before(paragraph(exported, "After"))).as("the gap, less the pull").isEqualTo(6 * 20 - RAISE);
assertThat(exported.report().bySubject()).doesNotContainKey("space above");
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPortraitTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPortraitTest.java
index 4ae70ddda..ae141f21d 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPortraitTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxPortraitTest.java
@@ -39,6 +39,8 @@ class DocxPortraitTest {
private static final double PHOTO = 123.8;
private static final double RING = 1.6;
+ /** What the default text's line under the frame is raised into the space above it. */
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
@Test
void aPhotoInARingWiderThanItsColumnKeepsItsSize() throws Exception {
@@ -80,7 +82,7 @@ void aLayersOwnMarginIsWrittenWithItAndNotTwice() throws Exception {
assertThat(beforeOf(picture)).isEqualTo(Math.round((25 + gaps[0]) * 20));
assertThat(beforeOf(paragraphs.get(paragraphs.indexOf(picture) + 1)))
- .isEqualTo(Math.round((gaps[1] + 22) * 20));
+ .isEqualTo(Math.round((gaps[1] + 22) * 20) - RAISE);
}
}
@@ -94,7 +96,8 @@ void aLayerMovedPastTheBottomLeavesTheFrameNoTallerThanItIs() throws Exception {
try (XWPFDocument document = inSidebar(frame)) {
List paragraphs = sidebar(document);
XWPFParagraph picture = pictureIn(paragraphs);
- long below = beforeOf(paragraphs.get(paragraphs.indexOf(picture) + 1)) - 22 * 20L;
+ // Less the 22pt above the heading under it, raised into that space.
+ long below = beforeOf(paragraphs.get(paragraphs.indexOf(picture) + 1)) + RAISE - 22 * 20L;
assertThat(beforeOf(picture) - 25 * 20L + 40 * 20L + below)
.as("the space above the picture, the picture and the space under it: the frame's 60pt")
@@ -118,7 +121,7 @@ void aLayerMovedPastTheTopLeavesTheFrameNoTallerThanItIs() throws Exception {
assertThat(beforeOf(picture)).as("none of the frame above the picture").isEqualTo(25 * 20L);
assertThat(beforeOf(paragraphs.get(paragraphs.indexOf(picture) + 1)))
.as("all of what it holds under it")
- .isEqualTo(Math.round((gaps[0] + gaps[1] + 22) * 20));
+ .isEqualTo(Math.round((gaps[0] + gaps[1] + 22) * 20) - RAISE);
}
}
@@ -148,7 +151,7 @@ void aPhotoStandsAsFarInsideItsRingAsThePageSetsIt() throws Exception {
assertThat(beforeOf(photo)).as("the sidebar's 25pt and the ring above the photo")
.isEqualTo(Math.round((25 + RING) * 20));
assertThat(beforeOf(heading)).as("the ring below the photo, and the heading's 22pt")
- .isEqualTo(Math.round((RING + 22) * 20));
+ .isEqualTo(Math.round((RING + 22) * 20) - RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowOverhangTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowOverhangTest.java
index 57860b59f..bf20279a2 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowOverhangTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowOverhangTest.java
@@ -35,6 +35,8 @@ class DocxRowOverhangTest {
+ "");
private static final DocumentTextStyle SMALL = DocumentTextStyle.DEFAULT.withSize(7);
private static final double GAP = 10;
+ /** What the small line after the row is raised into the space above it, and owes below. */
+ private static final long RAISE = DocxExports.SMALL_LINE_RAISE;
@Test
void theTallestCellsHangingLineTakesItsReachOutOfTheGapUnderTheRow() throws Exception {
@@ -48,7 +50,7 @@ void theTallestCellsHangingLineTakesItsReachOutOfTheGapUnderTheRow() throws Exce
assertThat(iconed.getCTP().getPPr().getSpacing().getLineRule()).as("held to its icon")
.isEqualTo(org.openxmlformats.schemas.wordprocessingml.x2006.main.STLineSpacingRule.EXACT);
assertThat(down).as("the line reaches below the page's").isPositive();
- assertThat(before(after(document))).as("the gap less that reach").isEqualTo(Math.round(GAP * 20) - down);
+ assertThat(before(after(document))).as("the gap less that reach").isEqualTo(Math.round(GAP * 20) - down - RAISE);
}
}
@@ -62,7 +64,7 @@ void aHangingLineWithRoomUnderItInItsRowTakesNothing() throws Exception {
right.addParagraph(p -> p.textStyle(SMALL).text("Line"));
}
}).document()) {
- assertThat(before(after(document))).isEqualTo(Math.round(GAP * 20));
+ assertThat(before(after(document))).isEqualTo(Math.round(GAP * 20) - RAISE);
}
}
@@ -76,7 +78,7 @@ void aShorterCellSetAtTheRowsFootHasItsRoomAllTheSame() throws Exception {
right.addParagraph(p -> p.textStyle(SMALL).text("Line"));
}
}, com.demcha.compose.document.node.RowVerticalAlign.BOTTOM).document()) {
- assertThat(before(after(document))).isEqualTo(Math.round(GAP * 20));
+ assertThat(before(after(document))).isEqualTo(Math.round(GAP * 20) - RAISE);
}
}
@@ -97,7 +99,7 @@ void aHangingLineTakesItsReachOutOfItsCellsPaddingFirst() throws Exception {
assertThat(spacing.isSetAfter() ? DocxTwips.of(spacing.getAfter()) : 0)
.as("the padding less the reach").isEqualTo(5 * 20 - down);
- assertThat(before(after(document))).isEqualTo(Math.round(GAP * 20));
+ assertThat(before(after(document))).isEqualTo(Math.round(GAP * 20) - RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowPaintTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowPaintTest.java
index cf8727b48..304e424a5 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowPaintTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRowPaintTest.java
@@ -325,7 +325,8 @@ void aPaintedRowTheLayoutMovesToANewPageKeepsTheSpaceAboveItThere() throws Excep
var before = (org.apache.poi.xwpf.usermodel.XWPFParagraph) element;
assertThat(before.getText()).isEqualTo("Before");
assertThat(twips(before.getCTP().getPPr().getSpacing().getAfter()))
- .as("its own 10pt, on the page above").isEqualTo(200);
+ .as("its own 10pt, on the page above, and what its line owes below it for its raise")
+ .isEqualTo(200 + DocxExports.DEFAULT_LINE_RAISE);
});
assertThat(exported.report().bySubject()).doesNotContainKey("row paint");
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRuleTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRuleTest.java
index f603717e3..f45bbb8db 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRuleTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxRuleTest.java
@@ -33,6 +33,8 @@
class DocxRuleTest {
private static final DocumentColor ACCENT = DocumentColor.rgb(26, 86, 148);
+ /** What the default text's line under a rule is raised into the space above it. */
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
@Test
void aFillLineIsAParagraphBorderAcrossTheWidth() throws Exception {
@@ -89,7 +91,7 @@ void theSpaceAroundTheStrokeInItsBoxIsKept() throws Exception {
CTPPr below = document.getParagraphs().get(1).getCTP().getPPr();
assertThat(DocxTwips.of(rule.getSpacing().getLine())).isEqualTo(110L);
- assertThat(DocxTwips.of(below.getSpacing().getBefore())).isEqualTo(110L);
+ assertThat(DocxTwips.of(below.getSpacing().getBefore())).isEqualTo(110L - RAISE);
}
}
@@ -262,7 +264,7 @@ void aStrokeThickerThanItsBoxTakesItsExtraFromTheSpaceBelow() throws Exception {
CTPPr after = document.getParagraphs().get(1).getCTP().getPPr();
// Box 1pt; Word takes 0.1 + 3: 2.1pt comes off the 10pt.
- assertThat(DocxTwips.of(after.getSpacing().getBefore())).isEqualTo(158L);
+ assertThat(DocxTwips.of(after.getSpacing().getBefore())).isEqualTo(158L - RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceAboveOnANewPageTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceAboveOnANewPageTest.java
index 17d15694e..a7e8f8887 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceAboveOnANewPageTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceAboveOnANewPageTest.java
@@ -71,7 +71,7 @@ void aSpacerOfNoHeightTheGapBeforeCarriesToANewPageHoldsTheGapInItsLine() throws
.isEqualTo(Math.round(GAP * 20) + HAIRLINE);
assertThat(before(spacing(paragraphWith(document, "After"))))
.as("the gap below it, less the hairline the spacer has not the height for")
- .isEqualTo(Math.round(GAP * 20) - HAIRLINE);
+ .isEqualTo(Math.round(GAP * 20) - HAIRLINE - DocxExports.DEFAULT_LINE_RAISE);
}
}
@@ -266,7 +266,8 @@ void aParagraphOnThePageOfTheBlockBeforeItIsWrittenAsBefore() throws Exception {
XWPFParagraph heading = paragraphWith(document, "Heading");
assertThat(document.getParagraphs()).as("the spacer and the heading, no line between them").hasSize(2);
- assertThat(before(spacing(heading))).isEqualTo(owed(CONTENT - 10 + GAP + PADDING));
+ assertThat(before(spacing(heading))).as("raised into it, on the page of the block before it")
+ .isEqualTo(owed(CONTENT - 10 + GAP + PADDING) - DocxExports.DEFAULT_LINE_RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceOnANewPageTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceOnANewPageTest.java
index 6b75c4d1b..0a4d595b8 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceOnANewPageTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxSpaceOnANewPageTest.java
@@ -42,8 +42,9 @@ void aRowMovedToANewPageHoldsItsTopEdgeInALineKeptWithIt() throws Exception {
.isEqualTo(Math.round(EDGE * 20));
assertThat(spacer.getCTP().getPPr().isSetKeepNext()).as("kept with the row").isTrue();
assertThat(spacingAfter(paragraphBefore(document, spacer)))
- .as("the gap stays at the foot of the page above, the edge does not")
- .isEqualTo(Math.round(GAP * 20));
+ .as("the gap stays at the foot of the page above, the edge does not; with it, what the"
+ + " line there owes below it for its raise")
+ .isEqualTo(Math.round(GAP * 20) + DocxExports.DEFAULT_LINE_RAISE);
}
}
@@ -95,7 +96,8 @@ void aRowOnThePageOfTheBlockBeforeItIsWrittenAsBefore() throws Exception {
XWPFParagraph above = paragraphBefore(document, onlyTable(document));
assertThat(above.getText()).as("no line between them").isNotEmpty();
- assertThat(spacingAfter(above)).isEqualTo(Math.round((GAP + EDGE) * 20));
+ assertThat(spacingAfter(above)).as("and what that line owes below it for its raise")
+ .isEqualTo(Math.round((GAP + EDGE) * 20) + DocxExports.DEFAULT_LINE_RAISE);
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackedLayersTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackedLayersTest.java
index 3e0e30eeb..f7c2ede73 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackedLayersTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxStackedLayersTest.java
@@ -92,8 +92,8 @@ void theLastLineOfAStackEndsAtTheContainersFootAndHangsPastNothing() throws Exce
+ line(paragraph(document, "Three"));
assertThat(stack).as("as tall as the box, its last line's own 36pt running past it")
.isCloseTo(2 * PITCH + 34, within(0.1));
- assertThat(before(paragraph(document, "After"))).as("the whole gap under the box")
- .isCloseTo(30, within(0.05));
+ assertThat(before(paragraph(document, "After"))).as("the whole gap under the box, less its line's raise")
+ .isCloseTo(30 - DocxExports.DEFAULT_LINE_RAISE / 20.0, within(0.05));
}
}
@@ -112,8 +112,8 @@ void theLettersOfAStacksLastLineHangingPastTheFootComeOutOfTheGapUnderIt() throw
assertThat(hang).as("just below its letters, not where its own line ends")
.isCloseTo(last.pageBaseline() + last.inkBelow() + DocxStackedLines.INK_MARGIN - (2 * PITCH + 26),
within(0.1));
- assertThat(before(paragraph(document, "After"))).as("by as much less gap under it")
- .isCloseTo(30 - hang, within(0.1));
+ assertThat(before(paragraph(document, "After"))).as("by as much less gap under it, and its line's raise")
+ .isCloseTo(30 - hang - DocxExports.DEFAULT_LINE_RAISE / 20.0, within(0.1));
}
}
diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxVerticalSpacingTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxVerticalSpacingTest.java
index b26f6f69a..5e0f36c34 100644
--- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxVerticalSpacingTest.java
+++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxVerticalSpacingTest.java
@@ -31,11 +31,15 @@
* the first paragraph written inside it and its bottom edge to the last, because that is
* where a reader sees it either way.
*
+ *
The space above a line of the default text is written less what the line is raised into
+ * it, and that is owed below the line ({@link DocxExports#DEFAULT_LINE_RAISE}).
+ *
* @author Artem Demchyshyn
*/
class DocxVerticalSpacingTest {
private static final double TWIPS_PER_POINT = 20.0;
+ private static final long RAISE = DocxExports.DEFAULT_LINE_RAISE;
@Test
void aParagraphCarriesItsOwnMarginAndPadding() throws Exception {
@@ -46,7 +50,7 @@ void aParagraphCarriesItsOwnMarginAndPadding() throws Exception {
.margin(DocumentInsets.bottom(6)))
.addParagraph(p -> p.text("Below")));
- assertThat(before(paragraphs.get(1))).isEqualTo(Math.round(16 * TWIPS_PER_POINT));
+ assertThat(before(paragraphs.get(1))).isEqualTo(Math.round(16 * TWIPS_PER_POINT) - RAISE);
assertThat(before(paragraphs.get(2)))
.as("the 6pt below it, written once, above what follows")
.isEqualTo(Math.round(6 * TWIPS_PER_POINT));
@@ -60,7 +64,7 @@ void marginAndPaddingOnTheSameEdgeAddUp() throws Exception {
.padding(DocumentInsets.top(10))
.margin(DocumentInsets.top(4))));
- assertThat(before(paragraphs.get(0))).isEqualTo(Math.round(14 * TWIPS_PER_POINT));
+ assertThat(before(paragraphs.get(0))).isEqualTo(Math.round(14 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -76,11 +80,12 @@ void aContainersEdgesGoToItsFirstAndLastParagraph() throws Exception {
assertThat(paragraphs).hasSize(4);
assertThat(before(paragraphs.get(0)))
.as("14pt of padding and 6pt of margin, on the paragraph that starts the card")
- .isEqualTo(Math.round(20 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(20 * TWIPS_PER_POINT) - RAISE);
assertThat(before(paragraphs.get(1))).as("nothing in the middle").isZero();
assertThat(after(paragraphs.get(1))).isZero();
assertThat(before(paragraphs.get(3)))
- .as("and the same below the one that ends it, above what follows the card")
+ .as("and the same below the one that ends it, above what follows the card, raised as far"
+ + " as the line above it")
.isEqualTo(Math.round(20 * TWIPS_PER_POINT));
}
@@ -218,7 +223,7 @@ void nestingAddsUpOnTheSameParagraph() throws Exception {
.padding(DocumentInsets.top(12))
.addParagraph(p -> p.text("Deep").padding(DocumentInsets.top(3))))));
- assertThat(before(paragraphs.get(0))).isEqualTo(Math.round(23 * TWIPS_PER_POINT));
+ assertThat(before(paragraphs.get(0))).isEqualTo(Math.round(23 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -236,7 +241,7 @@ void aContainerOfTablesHandsOnItsBottomEdgeAndDropsItsTop() throws Exception {
assertThat(before(paragraphs.get(paragraphs.size() - 1)))
.as("the bottom edge, and only it — the top one did not follow the table out")
- .isEqualTo(160L);
+ .isEqualTo(160L - RAISE);
}
@Test
@@ -260,7 +265,7 @@ void aContainerThatWritesNothingHandsBackTheEdgesAroundIt() throws Exception {
assertThat(paragraphs).hasSize(1);
assertThat(before(paragraphs.get(0)))
.as("the sidebar's 30pt of padding, then the portrait's 5 + 40 + 7")
- .isEqualTo(Math.round(82 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(82 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -335,7 +340,7 @@ void aTableDropsTheEdgeItStoodBelow() throws Exception {
.isZero();
assertThat(before(pastADivider.get(pastADivider.size() - 1)))
.as("nor was it handed on by the divider the export drops, which keeps its own 4pt")
- .isEqualTo(Math.round(4 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(4 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -350,7 +355,7 @@ void oneGapIsWrittenOnceRatherThanFromBothSides() throws Exception {
assertThat(before(paragraphs.get(1)))
.as("the whole gap, on the side that can hold it")
- .isEqualTo(Math.round(36 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(36 * TWIPS_PER_POINT) - RAISE);
assertThat(after(paragraphs.get(0)))
.as("and nothing on the other, so adding and taking the maximum agree")
.isZero();
@@ -435,7 +440,7 @@ void aTableHoldsItsOwnSpaceAboveAndBelow() throws Exception {
.isEqualTo(Math.round(9 * TWIPS_PER_POINT));
assertThat(before(paragraphs.get(1)))
.as("its bottom edge, on the paragraph below it")
- .isEqualTo(Math.round(12 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(12 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -450,7 +455,7 @@ void aRowHoldsItsOwnPaddingTheSameWay() throws Exception {
.addParagraph(p -> p.text("After")));
assertThat(after(paragraphs.get(0))).isEqualTo(Math.round(14 * TWIPS_PER_POINT));
- assertThat(before(paragraphs.get(1))).isEqualTo(Math.round(14 * TWIPS_PER_POINT));
+ assertThat(before(paragraphs.get(1))).isEqualTo(Math.round(14 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -464,7 +469,7 @@ void aTableWithNothingAboveItLosesThatEdgeAndKeepsTheOther() throws Exception {
assertThat(before(paragraphs.get(0)))
.as("the bottom edge and only it — the top had nothing to land on")
- .isEqualTo(Math.round(12 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(12 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -486,7 +491,7 @@ void aPictureKeepsItsOwnMargin() throws Exception {
// top edge is on it and its bottom edge lands on the paragraph after.
assertThat(before(paragraphs.get(paragraphs.size() - 1)))
.as("the picture's bottom edge reaches the block under it")
- .isEqualTo(Math.round(12 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(12 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -513,7 +518,7 @@ void aListKeepsItsOwnBoxAndTheSpaceBetweenItsItems() throws Exception {
assertThat(before(paragraphs.get(3))).isEqualTo(Math.round(3 * TWIPS_PER_POINT));
assertThat(before(paragraphs.get(4)))
.as("the list's bottom edge, on the paragraph after it")
- .isEqualTo(Math.round(10 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(10 * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -548,7 +553,7 @@ void aNegativeBottomEdgePullsTheNextParagraphUpOutOfItsContainer() throws Except
.addParagraph(p -> p.text("Role").margin(new DocumentInsets(10, 0, 0, 0))));
assertThat(after(body.get(0))).as("no space below the line pulled into").isZero();
- assertThat(before(body.get(1))).isEqualTo(Math.round((10 - 4) * TWIPS_PER_POINT));
+ assertThat(before(body.get(1))).isEqualTo(Math.round((10 - 4) * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -569,7 +574,7 @@ void aPullTheSpaceOwedAboveCannotGiveComesOutOfTheParagraphsOwnEdge() throws Exc
.addParagraph(p -> p.text("Role").margin(new DocumentInsets(10, 0, 0, 0))));
assertThat(after(body.get(0))).isZero();
- assertThat(before(body.get(1))).isEqualTo(Math.round((2 - 4 + 10) * TWIPS_PER_POINT));
+ assertThat(before(body.get(1))).isEqualTo(Math.round((2 - 4 + 10) * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -590,7 +595,7 @@ void aPullComesOutOfASpacerUnderIt() throws Exception {
.addParagraph(p -> p.text("After")));
// Less the spacer's own hairline, which is part of its height.
- assertThat(before(body.get(1))).isEqualTo(Math.round((10 - 4 - 0.1) * TWIPS_PER_POINT));
+ assertThat(before(body.get(1))).isEqualTo(Math.round((10 - 4 - 0.1) * TWIPS_PER_POINT) - RAISE);
}
@Test
@@ -602,7 +607,7 @@ void aPullStopsAtATable() throws Exception {
assertThat(before(body.stream().filter(p -> p.getText().equals("After")).findFirst().orElseThrow()))
.as("the paragraph after the table keeps its own edge")
- .isEqualTo(Math.round(10 * TWIPS_PER_POINT));
+ .isEqualTo(Math.round(10 * TWIPS_PER_POINT) - RAISE);
}
private static long before(XWPFParagraph paragraph) {
From f317cf37462c54142a64a7e5f1d1be27d4c7c7f3 Mon Sep 17 00:00:00 2001
From: DemchaAV
Date: Thu, 8 Oct 2026 21:18:58 +0100
Subject: [PATCH 2/3] fix(docx): leave a panel's top border the space above its
first line, and keep a raise owed past an empty layer
- A panel's first line raised into its space above took the room the
panel's top border reach comes out of (takeTheTopBorderInside): the line
gave it back, the panel grew by what it owed, and the note said more than
the line stood off. writePanelPiece now keeps the border's share of that
space, less what the padding takes, out of the raise
(panelsFirstLineKeeps).
- A layer column's later layer that writes nothing no longer drops what the
raised line above it owes: the cell ends with it.
- raiseIntoTheSpaceAbove checks every condition it documents; the Javadoc
names overlays (layer stacks among them), a container's stacked lines and
the panel's border space.
- Docs: the backend capability matrix's paragraph row, the recipe and the
CHANGELOG list the same exclusions; the corpus figures corrected.
- Tests: a panel's first line leaves its top border the space above it, the
note unchanged; a later layer that writes nothing leaves the raise owed.
---
CHANGELOG.md | 20 ++---
.../architecture/backend-capability-matrix.md | 2 +-
docs/recipes/docx-export.md | 2 +-
.../semantic/docx/DocxSemanticBackend.java | 81 +++++++++++++------
.../semantic/docx/DocxBaselineSeatTest.java | 29 +++++++
.../semantic/docx/DocxLayerColumnsTest.java | 39 ++++++++-
6 files changed, 137 insertions(+), 36 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b209efce..1998a0802 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,17 +24,19 @@ follow semantic versioning; release dates are ISO 8601.
down, it would take its room out of the space below it, which is not known when it is written.
- A column's later layer, which measures the space to itself from the page, takes back the raise
of the line above it.
- - Not a line pair's shared line, which moved would move its other half; not a line in a band, a
- shape container, a canvas or a text box, whose writers measure what follows them from the page;
- not a line cut to fit, a stack's or one held to its pictures; and not a paragraph the layout
- moves to a new page, whose space above Word drops there, or breaks over one, whose lines on
- the next page the space above does not move.
-
- In the DOCX fidelity corpus 27 documents stand nearer the page in Word, the sum of their medians
- 1.6pt nearer — `letter-blue_banner`'s median line from 0.39pt to 0.18pt, `cv-modern_professional`'s
+ - Not a line pair's shared line, which moved would move its other half; not a line in an
+ overlay — a band, a layer stack, a shape container, a canvas, a text box — whose writers
+ measure what follows them from the page; not a line cut to fit, a container's stacked lines or
+ one held to its pictures; not a paragraph the layout moves to a new page, whose space above
+ Word drops there, or breaks over one, whose lines on the next page the space above does not
+ move; and not into the space above a panel's first line that its top border takes.
+
+ In the DOCX fidelity corpus 27 documents stand nearer the page in Word, the sum of the medians
+ 1.65pt nearer — `letter-blue_banner`'s median line from 0.39pt to 0.18pt, `cv-modern_professional`'s
from 0.32pt to 0.18pt — and 21 in LibreOffice on Windows, `cv-modern_professional`'s from 0.28pt
to 0.04pt. Two move a step of Word's grid further: `invoice-luma_studio`'s company lines, raised
- where the page sets them, now show their block standing 0.3pt high (median 0.13pt to 0.14pt),
+ where the page sets them, now show their block standing 0.2 to 0.3pt high (median 0.13pt to
+ 0.14pt),
and `letter-panel`'s median from 0.14pt to 0.16pt; in LibreOffice two medians move 0.01pt. The
report names nothing more.
diff --git a/docs/architecture/backend-capability-matrix.md b/docs/architecture/backend-capability-matrix.md
index 35ac09ef4..d285452c3 100644
--- a/docs/architecture/backend-capability-matrix.md
+++ b/docs/architecture/backend-capability-matrix.md
@@ -63,7 +63,7 @@ Payload records live in `core` under
| Capability (payload) | PDF (fixed) | PPTX (fixed) | DOCX (semantic) |
|---|---|---|---|
-| Paragraph — pre-wrapped lines, runs, alignment (`ParagraphFragmentPayload`) | ✅ `PdfParagraphFragmentRenderHandler` | ✅ `PptxParagraphFragmentRenderHandler` (one absolute, wrap-disabled frame per measured line) | ⚠️ semantic paragraphs (`DocxSemanticBackend`) — each run keeps its own style, falling back to the paragraph's when it has none; a centred or right-aligned left-to-right line of its own, of text alone and untracked, that Word sets a point or more wider or narrower at its half-point size has its letters spaced by the difference (`w:spacing`) and its room reckoned from the page's width; a `linkTarget` becomes a `w:hyperlink`, with a relationship for an address or `w:anchor` for one of the document's own anchors, and a run's own link wins over the paragraph's; a paragraph seated off its baseline (`TextVerticalAlign`) has its runs raised or lowered in the line (`w:position`) by the PDF backend's own correction (`ParagraphSeating`), one shift for the paragraph where the page seats each line by its own; Word and LibreOffice stand an exact line's baseline four fifths of the way down it whatever the face, where the page sets it the face's ascent down, so a paragraph whose face puts the two half a point or more apart — Spectral's, not Lato's — has its text moved to the page's baseline in the same position, matched at its middle line (not yet a list item's or a table text cell's; a picture among it moves with it in Word and stays on its own baseline in LibreOffice); lines a container stacks over one another tighter than their face each end halfway between their letters and the next line's (Word draws an exact line's text on screen only inside the line; its PDF export does not cut it), and the last layer of a shape container on one page, where its line runs past the foot, ends at the foot or below its letters; letters two lines share are split halfway so the page does not move, and a stack that holds a picture keeps its lines' own heights; a `bulletOffset` of spaces becomes the paragraph's indent (`w:ind` left, hanging or first line, by `indentStrategy`) in the flow and in cells, not yet over the flow, in an overlay's left-and-right pair, as a badge's initials or in a header or footer; one with letters in it is not written, its wrapped lines still set after the spaces that cover it; an auto-sized paragraph's text that takes its style is written at the size the page fits it to, read off the laid-out lines, a run with a style of its own keeping it, on every path that writes a paragraph — at its style's size where the lines do not tell the fitted size (no lines read, lines in sizes that do not say which is the paragraph's, or one paragraph added at more than one place); a paragraph a session reads as markdown — the default, unless `markdown(false)` — is written as the page sets it, read through the page's own parser, one run a piece in the face, family, colour, tracking and size the page's laid-out lines hold (an auto-sized one's read at the size the page fits it to, a heading at its multiple of it), its marks dropped, wherever the lines hold the pieces' letters so; where they are not read, or hold other letters or none (text the parser reads into nothing, which the page sets as nothing), as authored, its marks as letters; a `bookmark(...)` is Word's `HeadingN`, which Word's outline lists by the text of its Word paragraph — an overlay's pair's whole line, one level for both sides — at no level past the ninth. Outside a header or footer, the paragraph's report note (`ParagraphNode`) names each of these where it moves or renames something: the prefix's letters, and the room a path that writes no prefix leaves out where it moves a line; the size an auto-sized paragraph's text is written at, where the size the page fits it to is not measured; the marks of a paragraph the page read as markdown and the file holds as letters, where its laid-out lines hold fewer of them than its text, not measured where its lines are not read; a markdown heading written taller than the line the page sets it in, which Word cuts on screen; an outline title that is not the text Word lists, a level past the ninth that shares it with another, and the right side's entry where the left holds the line's level |
+| Paragraph — pre-wrapped lines, runs, alignment (`ParagraphFragmentPayload`) | ✅ `PdfParagraphFragmentRenderHandler` | ✅ `PptxParagraphFragmentRenderHandler` (one absolute, wrap-disabled frame per measured line) | ⚠️ semantic paragraphs (`DocxSemanticBackend`) — each run keeps its own style, falling back to the paragraph's when it has none; a centred or right-aligned left-to-right line of its own, of text alone and untracked, that Word sets a point or more wider or narrower at its half-point size has its letters spaced by the difference (`w:spacing`) and its room reckoned from the page's width; a `linkTarget` becomes a `w:hyperlink`, with a relationship for an address or `w:anchor` for one of the document's own anchors, and a run's own link wins over the paragraph's; a paragraph seated off its baseline (`TextVerticalAlign`) has its runs raised or lowered in the line (`w:position`) by the PDF backend's own correction (`ParagraphSeating`), one shift for the paragraph where the page seats each line by its own; Word and LibreOffice stand an exact line's baseline four fifths of the way down it whatever the face, where the page sets it the face's ascent down, matched at a paragraph's middle line: a line of its own Word sets a tenth of a point or more low is moved up into the space written above it and that space owed below it, in the flow and in cells, not in an overlay, a paragraph the layout moves to a new page or breaks over one, nor the space a panel's top border takes above its first line; what that space cannot give, and a line Word sets high, is moved in the same position where the two are half a point or more apart — Spectral's, not Lato's — which LibreOffice moves further by the face's height over its em (not yet a list item's or a table text cell's; a picture among it moves with it in Word and stays on its own baseline in LibreOffice); lines a container stacks over one another tighter than their face each end halfway between their letters and the next line's (Word draws an exact line's text on screen only inside the line; its PDF export does not cut it), and the last layer of a shape container on one page, where its line runs past the foot, ends at the foot or below its letters; letters two lines share are split halfway so the page does not move, and a stack that holds a picture keeps its lines' own heights; a `bulletOffset` of spaces becomes the paragraph's indent (`w:ind` left, hanging or first line, by `indentStrategy`) in the flow and in cells, not yet over the flow, in an overlay's left-and-right pair, as a badge's initials or in a header or footer; one with letters in it is not written, its wrapped lines still set after the spaces that cover it; an auto-sized paragraph's text that takes its style is written at the size the page fits it to, read off the laid-out lines, a run with a style of its own keeping it, on every path that writes a paragraph — at its style's size where the lines do not tell the fitted size (no lines read, lines in sizes that do not say which is the paragraph's, or one paragraph added at more than one place); a paragraph a session reads as markdown — the default, unless `markdown(false)` — is written as the page sets it, read through the page's own parser, one run a piece in the face, family, colour, tracking and size the page's laid-out lines hold (an auto-sized one's read at the size the page fits it to, a heading at its multiple of it), its marks dropped, wherever the lines hold the pieces' letters so; where they are not read, or hold other letters or none (text the parser reads into nothing, which the page sets as nothing), as authored, its marks as letters; a `bookmark(...)` is Word's `HeadingN`, which Word's outline lists by the text of its Word paragraph — an overlay's pair's whole line, one level for both sides — at no level past the ninth. Outside a header or footer, the paragraph's report note (`ParagraphNode`) names each of these where it moves or renames something: the prefix's letters, and the room a path that writes no prefix leaves out where it moves a line; the size an auto-sized paragraph's text is written at, where the size the page fits it to is not measured; the marks of a paragraph the page read as markdown and the file holds as letters, where its laid-out lines hold fewer of them than its text, not measured where its lines are not read; a markdown heading written taller than the line the page sets it in, which Word cuts on screen; an outline title that is not the text Word lists, a level past the ninth that shares it with another, and the right side's entry where the left holds the line's level |
| List hanging indent — a marker column and a content column (`ListBuilder.hangingIndent(true)`, `markerGap(...)`) | ✅ marker and content emitted as separate `ParagraphFragmentPayload` fragments at the resolved `markerX` / `contentX` | ✅ the same fragments — the fixed-layout pipeline resolves the geometry before either backend sees it | ⚠️ the top level only. `DocxSemanticBackend` exports a list as a real Word list — `numbering.xml`, `w:numPr` per item, the level carrying the marker — or, with rich items or a drawn marker, as paragraphs; content and nesting are unaffected. With the flag, the top level's marker column is the layout's — the marker's width and `markerGap`, the text and its wrapped lines where the page sets them — where the gap covers what Word may set the marker wider: a picture at its written size, its edges included, or text in the page's face (embedded, or a standard one Word sets in the same widths) grown to its half-point size, half a point clear. A Word list's level then indents and hangs by that column; a list of paragraphs writes the marker, a tab to a stop there, and hangs the item there. Word places content at absolute indents and has no relative-advance primitive, so without the layout's measure the gap could not be honoured; a Word list without the flag that the layout placed and that does not nest takes the page's column too, the spaces the page sets its wrapped lines after, its marker followed by a space (`w:suff`) and an item that wraps measured at Word's half-point size; a list that nests items, a list built as a tree of items (laid out flattened), and a marker the gap does not clear keep the stated column (180 twips, plus 120 per nesting level) — except, in a list of paragraphs, a nested rich item with no marker, which stands where the layout set its text, its measure weighed at Word's half-point sizes, where the layout's items are matched to the list's; a list that nests only such items sets its top level at the page's column too. The report counts, on the list, the items that stand at a stated column, a space past their marker or two spaces a level in, and names a centred or right-aligned list written flush left, a lineSpacing not written where the layout's items are not the list's own and one wraps (in a list composed in a table cell, its wrapping not measured), a continuationIndent not written where an item of a markerless list or a tree of items without the flag wraps or its wrapping is not measured, the rows the page draws as a marker alone for blank items of a flagged list, which are not written, and what items the page reads as markdown lose. An item of plain text the page reads as markdown — the default, unless `markdown(false)` — is written as the page sets it, matched to the lines the page laid it out in and read as the page lays it out (a flat item after the marker the page sets before it; a flagged item as its text alone; an item of a list built as a tree of items without the flag after the indent and marker the page reads with it), one run a piece in the face, family, colour, tracking and size those lines hold, Word or the file drawing the marker where it did (Word draws a tree's bullets regular, as the parser sets the marker it reads), the font table shipping the faces the page sets the pieces in; it is written as authored, its marks as letters, where its list's items are not matched one by one to the layout's (no layout, composed in a table cell, an item run onto the next page, a flagged list with a blank item), where its lines hold other letters, where the parser reads a tree's marker as markdown with the item (`*a*`), and where the parser reads it into nothing, and named where the page drops a mark from it or sets none of its text — not where it changes only its face or letters no mark is made of (`1.`); a markdown heading written taller than its item's line is named |
| Inline code/badge chips (`InlineBackground` on text spans) | ✅ `PdfParagraphFragmentRenderHandler` | ✅ `PptxParagraphFragmentRenderHandler` | ⚠️ `DocxSemanticBackend` — the fill becomes the run's own `w:shd`, in a paragraph and in a list item alike, so a badge still reads as a badge. What Word has no way to say is the shape: shading covers the glyph box, so the corner radius and the padding above and below the letters are not in the file, and the export records them. The padding beside the letters is written as the room it takes (`spaceAfterTheLastLetter`): character spacing after the chip's last letter, shaded with it, and after the letter before the chip, unshaded. A chip opening its line or following a picture has no letter before it, so its left padding is not in the file; no space is written after right-to-left letters or after a symbol or emoji. The export records, chip by chip, how each side was written. LibreOffice sets no spacing after a line's last letter, so it does not apply the right padding of a chip that ends a line. A `w:shd` fill is opaque, so a translucent chip is flattened first against what Word paints underneath it — the paragraph's shading, the cell's, or else the colour the page paints under the paragraph, a page background included — so the chip agrees with the file it is in and shows the colour the PDF shows. It stops being translucent, and that is recorded with the rest |
| Inline images (`ParagraphImageSpan`) | ✅ `PdfParagraphFragmentRenderHandler` | ✅ `PptxParagraphFragmentRenderHandler` | ✅ `DocxSemanticBackend.writeInlinePicture` (a picture in its own run where it sits among the words, at its size, inside the run's or the paragraph's link; raised or lowered by `w:position` to where the page's alignment and `baselineOffset` put it, from the layout's measure of the paragraph's first line — in a list, the list's text on a line as tall as the item's own tallest picture; LibreOffice ignores `w:position` on a picture and stands it on the baseline, so a picture the export draws itself (icon, emoji, shape) that the page raises carries the rise as transparent rows and needs no `w:position`, while one the page lowers stands in LibreOffice higher than on the page by as much as the page lowers it — up to the text's descent for a centred icon as tall as its line; the editor clips a picture to an exact line height, so a paragraph holding a picture that leaves its text — past the ascent or the descent, in Word's placement or on the baseline — has its lines written at least the height the picture reaches, grown by the editor rather than clipped, every line of the paragraph since Word has one line height for it, and each as tall as the editor's font makes it — for 14pt text about 2.5pt taller than the page's in LibreOffice; a picture inside its text in both editors keeps the exact height; a paragraph of one line of text in a Word paragraph of its own, with room above for its pictures' reach, keeps an exact line at the page's height of it, the pictures set in it where the page puts them in Word and what their ink reaches past it taken from the gaps around it, and in LibreOffice a lowered picture there stands higher and loses what passes the line's top; its description is the text it stands for or empty) |
diff --git a/docs/recipes/docx-export.md b/docs/recipes/docx-export.md
index f88de39ca..889c37d69 100644
--- a/docs/recipes/docx-export.md
+++ b/docs/recipes/docx-export.md
@@ -185,7 +185,7 @@ it cannot work out for itself:
| What | Where it lands |
|---|---|
-| Line height | `w:spacing w:lineRule="exact"` on every paragraph, cells and list items included — the height the engine measured, not a multiple Word would measure again against a substituted font. Word has one height for a paragraph's lines: it is the tallest line's text, or, where the page sets lines of different heights further apart than that, the page's mean distance between their baselines, with what a paragraph on one page then falls short of the page owed below it, and what it passes the page by — written at its tallest line, a wrapped line after a large first one, which the page sets at its own height — hung below it, as a line held to its icon is: the space below takes it, and what it cannot take is named (`space above`) (not yet a list item's, or text set over the flow; measured: `CompactMono`'s sidebar, whose skills are two lines a paragraph and each written 0.12pt taller than the page, ended a point low in Word). Lines rounded up to the twip, over enough of them, hang the same way; what rounding takes from a paragraph written at its tallest line is not owed (measured: owed, it stood `ModernInvoice`'s lines lower in Word). A tenth of a point or less is left either way: Word sets lines on a grid of its own, 0.12pt apart (measured). In a paragraph of more than one line on one page, the spaces a `bulletOffset` sets before a line, written as an indent, do not count towards that line's text. A paragraph of lines as tall as their text, on one page, opening a table cell takes the gap above its first line from the cell's top padding, no more than steps its lines the page's distance apart — not in a row beside a merged cell or a cell opening with a table, whose margin Word would set the whole row at, nor in a panel. One with no room above it for the gap (opening a column, or a cell padded less) shares the gaps out over all its lines, so its lines stand a little closer than on the page. A paragraph the layout did not measure — one in a composed table cell — is left to the editor, and a line holding a picture above its text is written "at least" that height — except a paragraph of one line of text with room above for its pictures' reach, held exact at the page's height (see "Inline pictures"); in both the paragraph mark is set in the text's size and face, since the mark counts towards the last line's height. A line holding pictures and no text, where they fill the page's line, has its mark and its pictures' runs set at a point instead, so Word makes the line as tall as the pictures and no taller: in the paragraph's own size the mark's depth went under the picture (measured: `SlateOrange`'s skills, a 12.4pt icon beside each label, stood 0.2pt taller each in Word). A smaller picture in a line the page sets at its font's height keeps its mark, and so does a line holding a letter, a break, a tab, a field or a link's text. A paragraph's own line of drawn shapes and no text written at least their reach, which Word grows to the pictures and the transparent frame each keeps around its ink, has that frame taken from the space above the line and above what follows, where it passes the height written: the ink stands where the page draws it, and what follows where the page sets it. Both editors stand the baseline of an exact line four fifths of the way down it whatever the face (measured in Word and LibreOffice on the fifteen faces the templates use and JetBrains Mono, 8 to 36pt), and the page sets it the face's ascent below the line's top, matched at a paragraph's middle line. A line Word sets lower than the page by a tenth of a point or more is moved up into the space written above it, written to the twip, and that space is owed below it, so what follows stays where it was; both editors keep a paragraph's space above as written (by its position alone, Helvetica's lines, which the page seats 0.78 of the way down, stood 0.12 to 0.38pt low in Word). A column's later layer, which measures the space to itself from the page, takes back the raise of the line above it. Not a line pair's shared line, which moved would move its other half; not a line in a band, a shape container, a canvas or a text box, whose writers measure what follows them from the page; not a line cut to fit; and not a paragraph the layout moves to a new page, whose space above Word drops there, or breaks over one. What that space cannot give, and a line Word sets higher than the page — moved down, it would take its room out of the space below it, not known when it is written — is raised or lowered to the page's baseline by `w:position` where the whole difference is half a point or more, a face with a deep descent, as Spectral's is. A list item's and a table text cell's lines are not seated yet. LibreOffice moves text by `w:position` further than it is raised, by the face's height over its em — Spectral's 1.53 times, Poppins' 1.49, Volkhov's 1.31 (measured) — so a line raised by its position stands where the page sets it in Word only: Spectral's 24pt line, raised 4pt, stood 2.4pt high in LibreOffice. A picture among such text moves with it in Word; LibreOffice keeps a picture on its own baseline, where it stood before. Lines a container stacks tighter than their face — a title's lines a pitch apart — each end halfway between their letters and the next line's, since Word draws an exact line's text on screen only inside the line, and the last layer of a shape container, where its line runs past the foot, ends at the foot or below its letters |
+| Line height | `w:spacing w:lineRule="exact"` on every paragraph, cells and list items included — the height the engine measured, not a multiple Word would measure again against a substituted font. Word has one height for a paragraph's lines: it is the tallest line's text, or, where the page sets lines of different heights further apart than that, the page's mean distance between their baselines, with what a paragraph on one page then falls short of the page owed below it, and what it passes the page by — written at its tallest line, a wrapped line after a large first one, which the page sets at its own height — hung below it, as a line held to its icon is: the space below takes it, and what it cannot take is named (`space above`) (not yet a list item's, or text set over the flow; measured: `CompactMono`'s sidebar, whose skills are two lines a paragraph and each written 0.12pt taller than the page, ended a point low in Word). Lines rounded up to the twip, over enough of them, hang the same way; what rounding takes from a paragraph written at its tallest line is not owed (measured: owed, it stood `ModernInvoice`'s lines lower in Word). A tenth of a point or less is left either way: Word sets lines on a grid of its own, 0.12pt apart (measured). In a paragraph of more than one line on one page, the spaces a `bulletOffset` sets before a line, written as an indent, do not count towards that line's text. A paragraph of lines as tall as their text, on one page, opening a table cell takes the gap above its first line from the cell's top padding, no more than steps its lines the page's distance apart — not in a row beside a merged cell or a cell opening with a table, whose margin Word would set the whole row at, nor in a panel. One with no room above it for the gap (opening a column, or a cell padded less) shares the gaps out over all its lines, so its lines stand a little closer than on the page. A paragraph the layout did not measure — one in a composed table cell — is left to the editor, and a line holding a picture above its text is written "at least" that height — except a paragraph of one line of text with room above for its pictures' reach, held exact at the page's height (see "Inline pictures"); in both the paragraph mark is set in the text's size and face, since the mark counts towards the last line's height. A line holding pictures and no text, where they fill the page's line, has its mark and its pictures' runs set at a point instead, so Word makes the line as tall as the pictures and no taller: in the paragraph's own size the mark's depth went under the picture (measured: `SlateOrange`'s skills, a 12.4pt icon beside each label, stood 0.2pt taller each in Word). A smaller picture in a line the page sets at its font's height keeps its mark, and so does a line holding a letter, a break, a tab, a field or a link's text. A paragraph's own line of drawn shapes and no text written at least their reach, which Word grows to the pictures and the transparent frame each keeps around its ink, has that frame taken from the space above the line and above what follows, where it passes the height written: the ink stands where the page draws it, and what follows where the page sets it. Both editors stand the baseline of an exact line four fifths of the way down it whatever the face (measured in Word and LibreOffice on the fifteen faces the templates use and JetBrains Mono, 8 to 36pt), and the page sets it the face's ascent below the line's top, matched at a paragraph's middle line. A line Word sets lower than the page by a tenth of a point or more is moved up into the space written above it, written to the twip, and that space is owed below it, so what follows stays where it was; both editors keep a paragraph's space above as written (by its position alone, Helvetica's lines, which the page seats 0.78 of the way down, stood 0.12 to 0.38pt low in Word). A column's later layer, which measures the space to itself from the page, takes back the raise of the line above it. Not a line pair's shared line, which moved would move its other half; not a line in an overlay — a band, a layer stack, a shape container, a canvas, a text box — whose writers measure what follows them from the page; not a line cut to fit, a container's stacked lines or one held to its pictures; not a paragraph the layout moves to a new page, whose space above Word drops there, or breaks over one; and not into the space above a panel's first line that its top border takes. What that space cannot give, and a line Word sets higher than the page — moved down, it would take its room out of the space below it, not known when it is written — is raised or lowered to the page's baseline by `w:position` where the whole difference is half a point or more, a face with a deep descent, as Spectral's is. A list item's and a table text cell's lines are not seated yet. LibreOffice moves text by `w:position` further than it is raised, by the face's height over its em — Spectral's 1.53 times, Poppins' 1.49, Volkhov's 1.31 (measured) — so a line raised by its position stands where the page sets it in Word only: Spectral's 24pt line, raised 4pt, stood 2.4pt high in LibreOffice. A picture among such text moves with it in Word; LibreOffice keeps a picture on its own baseline, where it stood before. Lines a container stacks tighter than their face — a title's lines a pitch apart — each end halfway between their letters and the next line's, since Word draws an exact line's text on screen only inside the line, and the last layer of a shape container, where its line runs past the foot, ends at the foot or below its letters |
| Table columns | the resolved cell widths as `w:gridCol`, with `w:tblLayout` fixed so Word does not re-fit them |
| Row columns | where the layout placed each child, with the row's gap and padding folded into the neighbouring column and taken back out as that cell's margin — in a painted row's panel the padding is the panel cell's margins instead, and the columns are without it. A column sized to its content (`DocumentRowColumn.auto()`) gets a point more, taken from the row's weight columns so the row keeps its width, for the reason a table's does: the editor's substitute font would wrap it — a table of contents' labels broke mid-word ("Intr" / "o") in LibreOffice without it. A row with no auto column, no weight column, or no stated columns (weights, an even split) is written as placed |
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 1a5e8efbe..586582108 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
@@ -397,6 +397,9 @@ public final class DocxSemanticBackend implements SemanticBackend {
private String badgeText;
// The cell of the panel being written, painted or framed; null outside a panel.
private XWPFTableCell panelCell;
+ // How much of the space above the first paragraph of panelCell its top border takes, in twips
+ // (writePanelPiece): no room to raise that paragraph's line into (raiseIntoTheSpaceAbove).
+ private long panelsFirstLineKeeps;
// The text style the document is mostly written in, promoted to Word's Normal style.
// Null until an export computes it, and when the graph carries no text at all.
private DocumentTextStyle documentDefaultStyle;
@@ -792,6 +795,7 @@ private byte[] write(List sections, Path outputFile) throws Exc
cellHang = 0;
cellTextShift = 0;
paragraphOpeningItsPage = null;
+ panelsFirstLineKeeps = 0;
lastRaise = 0;
blocksAtTheLastRaise = -1;
nextDrawingId = 100_000;
@@ -5386,12 +5390,18 @@ private void writePanelPiece(XWPFDocument document, DocumentNode node, Container
if (first && last) {
cutTheLabelToItsOutline(node, borders, cell);
}
+ // What of the top border's reach the padding cannot take comes out of the space above the
+ // first paragraph (takeTheTopBorderInside, below): that much of it is no room to raise a
+ // line into.
+ long outerKeptAbove = panelsFirstLineKeeps;
+ panelsFirstLineKeeps = Math.max(0, toTwips(topNotTaken) - cellMargin(cell, true));
try {
writeInCell(cell, content);
} finally {
surfaceBehind = outerSurface;
currentCellWidth = outerCellWidth;
panelCell = outerPanelCell;
+ panelsFirstLineKeeps = outerKeptAbove;
}
if (cell.getParagraphs().isEmpty()) {
// A panel with nothing Word can hold inside is its padding tall on the page, not a
@@ -9333,7 +9343,8 @@ private boolean holdsText(ParagraphNode node) {
* is raised as a part of its zone's line ({@link #zonePlacement}).
*
*
The baseline the page seats off is not where Word puts it either (see
- * {@link #shiftToThePagesBaseline}), and the two moves are one position.
+ * {@link #shiftToThePagesBaseline}): what of that the space above does not take and the
+ * page's seat are one position.
*
* @param runsBefore how many runs the Word paragraph held before this one's were written
* @param lineTopAbove how far above the page's first line of the paragraph the Word line
@@ -9434,8 +9445,9 @@ private double seatShift(ParagraphNode node) {
* shared by the first and last. 0 for a paragraph not written at an exact height: Word
* then seats it by its own measure of the face.
*
- *
A line Word sets low is raised first by moving it up into the space written above it
- * ({@link #raiseIntoTheSpaceAbove}), to the twip. What that space cannot give, and a line set
+ *
A line of its own Word sets low is raised first by moving it up into the space written
+ * above it, where that space can take it ({@link #raiseIntoTheSpaceAbove}). What that space
+ * cannot give, and a line set
* high, is left to the text's position, which counts in half points: a line whose difference
* is under {@link #LEAST_BASELINE_SHIFT_POINTS} — a quarter point for a line of Lato body text
* — keeps no position, as every line of body text moved by one would win a quarter point at
@@ -9478,8 +9490,8 @@ private double shiftToThePagesBaseline(XWPFParagraph para, ParagraphNode node, d
// the space above took off it: a line 0.6pt low with 0.2pt above it is left a tenth
// off by its position, not four tenths.
boolean moved = Math.abs(shift) >= LEAST_BASELINE_SHIFT_POINTS || cutToFit;
- if (ownsItsLine && !cutToFit && node != paragraphOpeningItsPage && layout.onOnePage(node)) {
- shift -= raiseIntoTheSpaceAbove(spacing, shift);
+ if (ownsItsLine && !cutToFit) {
+ shift -= raiseIntoTheSpaceAbove(para, node, spacing, shift);
}
return moved ? shift : 0;
}
@@ -9497,46 +9509,62 @@ private double shiftToThePagesBaseline(XWPFParagraph para, ParagraphNode node, d
* stood 0.12 to 0.38pt low in Word at 8 to 18pt — is moved a half point or not at all. And
* LibreOffice moves raised text further than it is raised, by the face's height over its em:
* Spectral's 1.53 times, Poppins' 1.49, Volkhov's 1.31 (measured), so Spectral's 24pt line,
- * raised 4pt, stood 2.4pt high there. Both editors set a paragraph its space above below what
- * comes before it, to the twip, and an exact line's baseline four fifths of the way down it
- * ({@link DocxTextBands#BASELINE_SHARE}): a line moved up that space stands where the page
+ * raised 4pt, stood 2.4pt high there. Both editors keep a paragraph's space above as written,
+ * Word on its own 0.12pt grid, and stand an exact line's baseline four fifths of the way down
+ * it ({@link DocxTextBands#BASELINE_SHARE}): a line moved up that space stands where the page
* sets it in both.
*
*
Only a raise: a line moved down takes its room out of the space below it, which is not
* known until what follows is written, and what that space could not take would stand all of
- * it lower. Only a paragraph in the flow or in a cell, where the space owed below it is the
- * space above what follows: a band, a shape container, a canvas and the text laid over the
- * flow — the overlays — measure what follows them from the page ({@link #writeOverlayBand}),
- * and the space a line owed inside them would be lost. A column's later layer measures the
- * space to itself from the page too, and takes back the raise of the line above it
- * ({@link #raiseOwedByTheLastLine}). Not a paragraph the layout moves to a new page: Word drops
- * its space above there ({@link #holdAParagraphsTopEdgeOnItsPage}), and what the line owed
- * would stand all below it lower. Not a paragraph the layout breaks over a page: its lines on
- * the next page start at that page's top, where the space above moves none of them, and what
- * it owed would stand what follows them lower. Less than
- * {@link #LEAST_RAISE_INTO_THE_SPACE_ABOVE} is not moved.