From 7f1eb13d8d89c5df79111027d0eeb310c6c44120 Mon Sep 17 00:00:00 2001 From: DemchaAV Date: Sun, 18 Oct 2026 12:06:39 +0100 Subject: [PATCH] fix(docx): name a border Word draws at another width than the page, and write a separator of no width A Word border is two to ninety-six eighths of a point wide, and the export held every border to that range without a note: a panel's, a row's and a table cell's borders, a rule written as a paragraph's border, and a text header's or footer's separator. A 20pt panel border was written 12pt wide, a 0.1pt rule a quarter of a point. DocxBorderWidths holds the range and says what falls outside it, to the eighth: a border is named (border width) once for a panel, once for a table, once for a rule, and once for a separator however many headers it is written into. A width that rounds to an eighth Word draws is drawn at it, unnamed. A separator of no width, which the PDF strokes as the thinnest line a device shows, was not written. It is drawn at Word's thinnest border and named, and the band's reach past the page margin counts the separator as Word draws it. One set below zero, or not a number, is named as not written. --- CHANGELOG.md | 11 + .../architecture/backend-capability-matrix.md | 8 +- docs/recipes/docx-export.md | 10 +- .../semantic/docx/DocxBorderWidths.java | 104 ++++++ .../semantic/docx/DocxSemanticBackend.java | 130 +++++-- .../semantic/docx/DocxBorderWidthsTest.java | 321 ++++++++++++++++++ .../docx/DocxNodeFieldLedgerTest.java | 29 +- 7 files changed, 574 insertions(+), 39 deletions(-) create mode 100644 render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidths.java create mode 100644 render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidthsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 62b79f6d9..cbd4b024a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,17 @@ follow semantic versioning; release dates are ISO 8601. ### Public API +- **A DOCX export names a border Word draws at another width than the page, and writes a text + header's or footer's separator of no width.** A Word border is no thinner than a quarter of a + point and no wider than twelve, and the export held a border to that without a word: a panel's + 20pt border, a table cell's or a row's, was written 12pt wide, a 0.1pt hairline a quarter of a + point, a rule as thin and a separator as thin or as wide. Each is now named (`border width`), + once for a panel, a table and a rule, and once for a separator however many headers it is + written into. A separator of no width, which the page strokes as the thinnest line a screen or + a printer shows, was not written; it is drawn at Word's thinnest and named, and counts as Word + draws it where the export decides whether a band reaches past the page margin. One set below + zero, or not a number, is named as not written. A width that rounds to an eighth Word draws — + 0.2pt to a quarter of a point — is drawn at it, unnamed. - **A DOCX export says why a drawing is not in it and what a section with no layout leaves to the editor, names the application that made it, gives every table a grid, and names an anchor in a repeated table header.** Without the layout — a document the engine refused, or a bare diff --git a/docs/architecture/backend-capability-matrix.md b/docs/architecture/backend-capability-matrix.md index aecc9c7ff..803ddafbb 100644 --- a/docs/architecture/backend-capability-matrix.md +++ b/docs/architecture/backend-capability-matrix.md @@ -70,9 +70,9 @@ Payload records live in `core` under | Inline vector shapes (`ParagraphShapeSpan`) | ✅ `PdfParagraphFragmentRenderHandler` | ⚠️ `PptxParagraphFragmentRenderHandler` + `PptxInlineGeometry` (distinct per-corner radii render with the top-left radius — single-adjust preset) | ⚠️ `DocxSemanticBackend.writeInlinePicture` + `DocxShapePictures` (a transparent PNG drawn by the shared `InlineSvgRasters` from the outline, fill and stroke — every outline kind, each layer centred in the run's box — placed as an inline picture is; the picture takes as far as the stroked ink reaches past the outline — half the stroke on an edge, more at a sharp corner's miter — and a pixel on each side, measured side by side, and is lowered by what it takes below, so no edge is cut and a shape takes that much more room in the line; a list marker that draws a disc is its picture; at the top level of a `hangingIndent(true)` list that does not nest it is followed by a tab to where the layout starts the item's text, the item's lines hanging there, when the picture clears that stop, else by a space; Word could hold a shape in the line, `wp:inline` round a `wps:wsp`, which the export does not write, so each shape among the words is reported `APPROXIMATED` as a picture) | | Inline SVG (`ParagraphSvgSpan`) | ✅ `PdfParagraphFragmentRenderHandler` + `PdfPathPainter` | ⚠️ `PptxParagraphFragmentRenderHandler` + `PptxInlineGeometry` + `PptxInlineSvgRasterizer` (simple layers stay native; arbitrary clips, exact dash/cap/join styles, and off-viewBox art use a transparent PNG fallback — drawn by the shared `InlineSvgRasters`; gradient paints use their primary colour) | ⚠️ `DocxSemanticBackend.writeInlinePicture` (always the transparent PNG: the same layers the layout resolves, through `InlineSvgLayers`, drawn by the raster the PPTX fallback uses — `InlineSvgRasters`, four pixels a point — and placed as an inline picture is; emoji included, so an emoji is a picture rather than a character; every icon is reported `APPROXIMATED` as a picture, and an icon's text as its description) | | Text an inline icon stands for — copy, search, extraction (`ParagraphSvgSpan.text`, set by `SvgIcon.withText` and on every `EmojiLibrary` emoji) | ✅ `PdfTextLayer` via `PdfRenderEnvironment.writeTextLayer`: one invisible glyph over the icon on the line's baseline, from a Type 3 font of empty glyphs whose `ToUnicode` states each text, a whole ZWJ sequence included; rendering mode 3, so nothing is painted. One font per document, a new one after 255 distinct texts; a text over 256 UTF-16 units is not written. A block icon (`addSvgIcon`, `SvgIcon.node`) writes no text. `ActualText` around the paths was measured to reach none of PDFBox, poppler, pdf.js and MuPDF — it replaces glyphs, and a drawing has none. In a right-to-left line the glyph sits between the words it was written between and states its whole text; reading such a line back, PDFBox reverses the emoji one UTF-16 unit at a time and poppler reverses the code points of a ZWJ sequence or a U+FE0F pair, while pdf.js and MuPDF keep it whole (measured; a reader-side reversal of the glyph's text) | ❌ the icon is drawn and its text is not written | ⚠️ the icon is a picture whose description (`docPr/@descr`) is its text — read by a screen reader, but not a character a reader copies or searches | -| Rectangle shape — fill, stroke, per-corner radii, side borders (`ShapeFragmentPayload`) | ✅ `PdfShapeFragmentRenderHandler` | ⚠️ `PptxShapeFragmentRenderHandler` (distinct per-corner radii render with the top-left radius on all corners — single-adjust `roundRect` preset — until custom geometry lands; uniform radii and side borders exact) | ⚠️ `DocxSemanticBackend.writeContainerChildren` — a `SectionNode` or `ContainerNode` carrying a fill, per-side borders or a uniform stroke is written as a one-cell table, and so is a `RowNode` in the flow that paints its box (`writePaintedRow`, through the same `writePanelPiece`), its columns a table nested in the cell without its padding — not in a band of layers or a stack's measured column, with a padding or margin it cannot hold, composed in a table cell or in a page zone, where it is its columns alone and its paint is reported: the cell's shading is the fill behind everything inside, its borders are the container's at its full height, and its margins are the padding on all four sides, less half of each border, with the table half a border wider on each side, so the text and the border land where the page draws them — in the body, the left margin is the whole padding, the table no wider on that side, and its indent places its text, as Word 16 and LibreOffice on Windows centre a body table's left border on its edge (an older LibreOffice, the Linux CI's, reads the indent as the table's edge and sets the text about a padding right). Word sets a cell's content its whole top border and its margin inside the row, and ends the row its margin and its whole bottom border past the content, so half of each border — and as much of its inner half as the padding falls short of it — reaches past the panel: the space round it takes that first, then its padding, the border then drawn that much inside the panel's edge, then, above, the room over its first line; what none of them takes is reported (`space above` on the block below, the panel's kind for its top border). What its content leaves below itself past where the page ends it — a last line held to an icon, a card's border ending it, which that card's padding takes first — comes out of its padding below first, the same way; a card's border ending a row's cell reaches past the row only by what the row's room under that cell does not hold, and one ending a table's composed cell is reported on the card, its row up to that much taller. A negative bottom margin pulls what follows up out of the space between them, and what that space cannot give is reported, as is the tenth of a point of the paragraph between any two tables where the space between them does not take it. A shape container's borders stay inside its outline. A panel the layout measures holds the page's height less its padding as its row's height, which Word and LibreOffice on Windows read as its content's, its margins and borders round it; a shape container holds its outline's, less its margins and its borders as wide as Word draws them, two and a half twips an eighth of a point rounded down. A panel's borders are written from two to ninety-six eighths of a point, as a table cell's rules are. The table takes the width the layout placed the container at, plus a point of editor slack; in a cell, a panel whose left border hangs half its width left of the cell's text gives up what runs past the cell's edge as Word starts it, half that border in — no more than its left side had given its text, the half border the table is wider by and what its left margin gave back of the other half —, since a nested table running past its cell widens the cell, fixed layout or not. A `keepTogether()` panel the layout held on one page is a row that may not split. Panels, rows and tables inside it are tables in its cell; a table cell no style fills is written white, as the page draws it. One deviation: the corner radius is dropped (a cell is rectangular) with one warning per export. A translucent fill is flattened against what Word paints under the panel: the panel or cell around it as written, or on the page the colour the layout paints there (`DocxLayoutMetrics.colourUnder`: the fills drawn before it, at its centre, a page background included and a row's own fill left out, what stands on it being written in the row's panel, on its shading). A translucent border is flattened against the panel's fill where it has one, since a cell's shading and borders are opaque; each is named in the report as `translucency`. An unpainted container is not a table: its paragraphs are indented by every enclosing margin and padding, and its rows and tables get `w:tblInd`. A standalone `ShapeNode` that is only a fill, with no stroke, radius, gradient or transform, and no taller than Word's thickest border (12pt) — an `addDivider` — is a rule, written as a line's is; any other `ShapeNode`, standalone or laid over others, is drawn by `DocxDrawings` as a floating DrawingML shape behind the text, where the layout placed it — `rect`, or `roundRect` with the largest corner radius, in its fill and outline colours with their alpha, the outline mitred at its corners as the page strokes it, each side border a line along its edge; a gradient paint and a transform are not carried, nor are a link, an outline entry or an anchor's bookmark — each named in the shape's report note, as unequal corners are —, and a shape with neither a fill colour nor an outline is dropped and reported. It is anchored in the paragraph whose text it stands beside, placed down from its top, so it moves with that text when the text above is edited; beside no text, in a body paragraph on its page (a table cell's only on a page with no other, reported), where it stays — except a drawing that is all a table cell holds, an icon beside its label (in a row of the flow, a layer stack or shape container that only draws, with no margins, on one page and painting nothing outside its box; in a composed cell, a layer stack of shapes with no margin or padding, the only drawing the cell holds, matched to the table's fragments inside the cell by kind and size), which is anchored in that cell's paragraph, held at its height and placed from its top and the cell's text column, so it moves with its row; a drawing holding a line stays on the page —, and is drawn in front of the text inside a filled panel unless it frames text or a picture there; reported `APPROXIMATED` | +| Rectangle shape — fill, stroke, per-corner radii, side borders (`ShapeFragmentPayload`) | ✅ `PdfShapeFragmentRenderHandler` | ⚠️ `PptxShapeFragmentRenderHandler` (distinct per-corner radii render with the top-left radius on all corners — single-adjust `roundRect` preset — until custom geometry lands; uniform radii and side borders exact) | ⚠️ `DocxSemanticBackend.writeContainerChildren` — a `SectionNode` or `ContainerNode` carrying a fill, per-side borders or a uniform stroke is written as a one-cell table, and so is a `RowNode` in the flow that paints its box (`writePaintedRow`, through the same `writePanelPiece`), its columns a table nested in the cell without its padding — not in a band of layers or a stack's measured column, with a padding or margin it cannot hold, composed in a table cell or in a page zone, where it is its columns alone and its paint is reported: the cell's shading is the fill behind everything inside, its borders are the container's at its full height, and its margins are the padding on all four sides, less half of each border, with the table half a border wider on each side, so the text and the border land where the page draws them — in the body, the left margin is the whole padding, the table no wider on that side, and its indent places its text, as Word 16 and LibreOffice on Windows centre a body table's left border on its edge (an older LibreOffice, the Linux CI's, reads the indent as the table's edge and sets the text about a padding right). Word sets a cell's content its whole top border and its margin inside the row, and ends the row its margin and its whole bottom border past the content, so half of each border — and as much of its inner half as the padding falls short of it — reaches past the panel: the space round it takes that first, then its padding, the border then drawn that much inside the panel's edge, then, above, the room over its first line; what none of them takes is reported (`space above` on the block below, the panel's kind for its top border). What its content leaves below itself past where the page ends it — a last line held to an icon, a card's border ending it, which that card's padding takes first — comes out of its padding below first, the same way; a card's border ending a row's cell reaches past the row only by what the row's room under that cell does not hold, and one ending a table's composed cell is reported on the card, its row up to that much taller. A negative bottom margin pulls what follows up out of the space between them, and what that space cannot give is reported, as is the tenth of a point of the paragraph between any two tables where the space between them does not take it. A shape container's borders stay inside its outline. A panel the layout measures holds the page's height less its padding as its row's height, which Word and LibreOffice on Windows read as its content's, its margins and borders round it; a shape container holds its outline's, less its margins and its borders as wide as Word draws them, two and a half twips an eighth of a point rounded down. A panel's borders are written from two to ninety-six eighths of a point, as a table cell's rules and a rule are, and a width that, rounded to the eighth, is thinner or wider is named (`border width`). The table takes the width the layout placed the container at, plus a point of editor slack; in a cell, a panel whose left border hangs half its width left of the cell's text gives up what runs past the cell's edge as Word starts it, half that border in — no more than its left side had given its text, the half border the table is wider by and what its left margin gave back of the other half —, since a nested table running past its cell widens the cell, fixed layout or not. A `keepTogether()` panel the layout held on one page is a row that may not split. Panels, rows and tables inside it are tables in its cell; a table cell no style fills is written white, as the page draws it. One deviation: the corner radius is dropped (a cell is rectangular) with one warning per export. A translucent fill is flattened against what Word paints under the panel: the panel or cell around it as written, or on the page the colour the layout paints there (`DocxLayoutMetrics.colourUnder`: the fills drawn before it, at its centre, a page background included and a row's own fill left out, what stands on it being written in the row's panel, on its shading). A translucent border is flattened against the panel's fill where it has one, since a cell's shading and borders are opaque; each is named in the report as `translucency`. An unpainted container is not a table: its paragraphs are indented by every enclosing margin and padding, and its rows and tables get `w:tblInd`. A standalone `ShapeNode` that is only a fill, with no stroke, radius, gradient or transform, and no taller than Word's thickest border (12pt) — an `addDivider` — is a rule, written as a line's is; any other `ShapeNode`, standalone or laid over others, is drawn by `DocxDrawings` as a floating DrawingML shape behind the text, where the layout placed it — `rect`, or `roundRect` with the largest corner radius, in its fill and outline colours with their alpha, the outline mitred at its corners as the page strokes it, each side border a line along its edge; a gradient paint and a transform are not carried, nor are a link, an outline entry or an anchor's bookmark — each named in the shape's report note, as unequal corners are —, and a shape with neither a fill colour nor an outline is dropped and reported. It is anchored in the paragraph whose text it stands beside, placed down from its top, so it moves with that text when the text above is edited; beside no text, in a body paragraph on its page (a table cell's only on a page with no other, reported), where it stays — except a drawing that is all a table cell holds, an icon beside its label (in a row of the flow, a layer stack or shape container that only draws, with no margins, on one page and painting nothing outside its box; in a composed cell, a layer stack of shapes with no margin or padding, the only drawing the cell holds, matched to the table's fragments inside the cell by kind and size), which is anchored in that cell's paragraph, held at its height and placed from its top and the cell's text column, so it moves with its row; a drawing holding a line stays on the page —, and is drawn in front of the text inside a filled panel unless it frames text or a picture there; reported `APPROXIMATED` | | Ellipse (`EllipseFragmentPayload`) | ✅ `PdfEllipseFragmentRenderHandler` | ✅ `PptxEllipseFragmentRenderHandler` | ⚠️ `DocxDrawings` — an `ellipse` shape anchored as a rectangle is; a shape container's elliptical outline is drawn the same way, and a picture that fills the container it clips takes the ellipse as its geometry; a transform is not carried, nor a link, an outline entry or an anchor's bookmark (each named in the ellipse's report note), and a shape in a filled panel is drawn in front of the text, over the cell's shading, unless it frames text or a picture; a shape is anchored as a rectangle is — except, as for a rectangle, a drawing that is all a table cell holds — in a row of the flow, a badge alone beside its text — which is anchored in that cell and moves with its row | -| Line — dash pattern, line cap (`LineFragmentPayload`) | ✅ `PdfLineFragmentRenderHandler` | ⚠️ `PptxLineFragmentRenderHandler` (numeric dash arrays map to the generic dashed preset; solid lines and caps exact) | ⚠️ `DocxSemanticBackend.writeRule` — a horizontal line with no transform, stroked no thicker than Word's 12pt border, is Word's own rule: an empty paragraph whose bottom border is the stroke (colour, thickness in eighths of a point), its ends as the paragraph's indents and the space above and below the stroke in its box as the paragraph's height and the space owed below it, and what Word's paragraph stands taller than the box — the tenth of a point of line a stroke with no room above it is held to, and the border counted in whole twips of its eighths — taken out of the space owed below and, past that, hung below the rule for the space above what follows to take, as a line hanging below a block is; a dash pattern becomes Word's dashed or dotted border, reported `APPROXIMATED`; a translucent stroke is flattened against the colour the page paints under it, a page background included, reported as `translucency`; the line cap and a link are not carried (both reported, a link as `rule link`; an outline entry on it is reported too); composed in a table's cell, it is written once, where the page draws it, and its table does not draw it again — unless it stands in a panel or a row inside the cell, or another drawing of its kind and size there cannot be told from it, where both stay and the report says it stands twice. A thicker line (holding its room in the flow and among the text of a stack of one layer, none in a table's cell, reported), a vertical or slanted line, and a line laid over others in a layer stack, canvas or shape container — a line among the text of a layer stack of one layer excepted, which is a rule —, is drawn by `DocxDrawings` as a `line` shape anchored as a rectangle is, ending in the page's cap — the dash pattern and a transform are not carried, nor a link, an outline entry or an anchor's bookmark (each named in the line's report note); a line in a page zone is dropped and reported | +| Line — dash pattern, line cap (`LineFragmentPayload`) | ✅ `PdfLineFragmentRenderHandler` | ⚠️ `PptxLineFragmentRenderHandler` (numeric dash arrays map to the generic dashed preset; solid lines and caps exact) | ⚠️ `DocxSemanticBackend.writeRule` — a horizontal line with no transform, stroked no thicker than Word's 12pt border, is Word's own rule: an empty paragraph whose bottom border is the stroke (colour, thickness in eighths of a point, a hairline thinner than Word's thinnest drawn at it and reported, `border width`), its ends as the paragraph's indents and the space above and below the stroke in its box as the paragraph's height and the space owed below it, and what Word's paragraph stands taller than the box — the tenth of a point of line a stroke with no room above it is held to, and the border counted in whole twips of its eighths — taken out of the space owed below and, past that, hung below the rule for the space above what follows to take, as a line hanging below a block is; a dash pattern becomes Word's dashed or dotted border, reported `APPROXIMATED`; a translucent stroke is flattened against the colour the page paints under it, a page background included, reported as `translucency`; the line cap and a link are not carried (both reported, a link as `rule link`; an outline entry on it is reported too); composed in a table's cell, it is written once, where the page draws it, and its table does not draw it again — unless it stands in a panel or a row inside the cell, or another drawing of its kind and size there cannot be told from it, where both stay and the report says it stands twice. A thicker line (holding its room in the flow and among the text of a stack of one layer, none in a table's cell, reported), a vertical or slanted line, and a line laid over others in a layer stack, canvas or shape container — a line among the text of a layer stack of one layer excepted, which is a rule —, is drawn by `DocxDrawings` as a `line` shape anchored as a rectangle is, ending in the page's cap — the dash pattern and a transform are not carried, nor a link, an outline entry or an anchor's bookmark (each named in the line's report note); a line in a page zone is dropped and reported | | Polygon (`PolygonFragmentPayload`) | ✅ `PdfPolygonFragmentRenderHandler` | ✅ `PptxPolygonFragmentRenderHandler` + `PptxInlineGeometry` | ⚠️ `DocxDrawings` + `DocxCustomGeometry` — `a:custGeom`, the vertex ring closed, its corners mitred as the page strokes them (LibreOffice bevels one sharper than 30 degrees), anchored as a rectangle is | | Free path — segments, dash, cap, join (`PathFragmentPayload`) | ✅ `PdfPathFragmentRenderHandler` + `PdfPathPainter` | ⚠️ `PptxPathFragmentRenderHandler` + `PptxInlineGeometry` (numeric dash arrays map to the dashed preset) | ⚠️ `DocxDrawings` + `DocxCustomGeometry` — `a:custGeom` through the same move/line/cubic/close segments, an unfilled path left open; the fill and stroke colours are carried, and the outline's cap and join as the page's — butt, round or square; mitred up to ten times the stroke's width, round or bevelled — which Word draws as the page does, and LibreOffice too but for a mitred corner sharper than 30 degrees, which it bevels — neither reads the miter limit, Word's own being the page's (written with neither cap nor join, both end an outline flat and round its corners); a gradient paint and the dash pattern are not carried, and a path's report note names which of them it loses, composed in a table cell the table's note naming them; the SVG icons of a block (`addSvgIcon`) are drawn this way, one shape per layer, unclipped | | Linear gradient fill (`DocumentPaint`) | ✅ `PdfShadingSupport` | ✅ `PptxGradientFill` (native `gradFill`; explicit-axis endpoints approximate to the angle) | ❌ | @@ -80,7 +80,7 @@ Payload records live in `core` under | Gradient strokes | ✅ `PdfPathPainter` (pattern stroking colour) | ✅ `PptxGradientFill` (native `ln`/`gradFill`) | ❌ | | Image — STRETCH / CONTAIN / COVER fit (`ImageFragmentPayload`) | ✅ `PdfImageFragmentRenderHandler` | ✅ `PptxImageFragmentRenderHandler` (COVER via the picture source crop) | ✅ `DocxSemanticBackend.writeImage` (the box comes from `NodeDefinitionSupport.resolveImageDimensions`, the same rule layout applies to `width` / `height` / `scale` and the content-width clamp; CONTAIN is embedded at its fitted size, COVER via the picture source crop as in PPTX, and the picture type is read from the bytes; its left margin and padding are not written, and a picture drawn beside its text is fitted to its box with its padding in it — each named in the report) | | Barcode / QR (`BarcodeFragmentPayload`) | ✅ `PdfBarcodeFragmentRenderHandler` (vector: the ZXing bit matrix filled as merged rectangles) | ✅ `PptxBarcodeFragmentRenderHandler` (native freeforms: the same ZXing bit matrix as merged rectangles) | ⚠️ `DocxSemanticBackend.writeBarcode` (a PNG picture of the same ZXing bit matrix through `BarcodeMatrices`, one pixel a cell, in the symbol's two colours with their alpha and at the node's size, its data as the picture's description; it scans, but its data is part of the picture rather than editable, reported `APPROXIMATED`, which also names a link, a transform or its left margin and padding as not carried; an `anchor` is a bookmark on its paragraph; in a page zone it is skipped) | -| Table rows — resolved cells, row/col spans, two-pass fill/border paint (`TableRowFragmentPayload`) | ✅ `PdfTableRowFragmentRenderHandler` + row grouping in `PdfFixedLayoutBackend` | ✅ `PptxTableRowFragmentRenderHandler` + row grouping in `PptxFixedLayoutBackend` (positioned rectangles, edge lines, and text frames — never native PPTX tables, which re-lay-out content) | ⚠️ `DocxSemanticBackend.writeTable` (a real Word table on the grid `TableGrid` resolves: `colSpan` maps to `w:gridSpan`, `rowSpan` to `w:vMerge`, and the cascaded `DocumentTableStyle` text style reaches the cell's runs; the cell's fill maps to `w:shd` and its stroke to `w:tcBorders` — the engine's default 1pt black rule where the table states none, not Word's thinner grid — its padding to `w:tcMar`, less above and below the room Word makes for the horizontal rules (half of a rule between two rows, the lower row's, to each; the rules above and below the table whole to their row), each as wide as Word draws it, in eighths of a point, and counted as both editors count it, two and a half twips an eighth rounded down (a rule between two rows shared in whole twips, the row above it taking half rounded down; a cell's top and bottom margins rounded to the twip together), a row held at the page's height less the most any of its cells takes, its margins and the rules it holds — between two others, the rest of its own above and half that of the cell under it; LibreOffice makes room at the edge between two rows for the heavier of their rules, where Word makes it for the lower row's, and under a row ruled heavier than it a row stands the difference lower there; a row of text cells moved by its top and bottom margins together, from Word's seat four fifths of the way down an exact line onto the page's baselines, by the least its cells' lines call for and no further than the margins hold — not a row holding a composed cell, one the layout did not measure, one in a vertical merge or whose cells call for opposite ways, nor a least call under a tenth of a point — and what the margins leave of a cell's call, half a point and more, moved by its text's position, and less, from a tenth of a point, by the height of its lines, each written shorter and the space after it taller, or the other way as far as that space holds, which keeps the cell's content as tall — where every paragraph of the cell is one line, in a face whose letters the export reads, and its letters stay clear of the line's top and foot; a row's cells at the row's smallest top and bottom margins, since both editors give every cell the row's largest, the rest of each cell's padding as space above its first paragraph and below its last, down to the largest margin a cell opening with a table or in a vertical merge keeps; the cascaded `textAnchor` maps to `w:vAlign` on every cell and to `w:jc` on a text cell's paragraph, with the engine's default — the vertical middle, on the left, or on the right for a right-to-left cell — and `DEFAULT` at the bottom left, as the renderer draws it; a composed cell is written by the same writers that write its node anywhere, so one built from an image, a list or a table carries it — a nested table is a real `w:tbl` taking the width of the column it sits in, less its own margins and padding, which is the column's rather than the one the page gives it, since the layout reports a composed cell's content under the owner's path; the paragraph Word requires after a nested table is hidden where it ends its cell holding nothing and no space; a translucent fill is flattened against the colour the page paints under the cell, and a translucent rule against the cell's fill where it has one, since `w:shd` and `w:tcBorders` are opaque, and the table's report note names it (`translucency`); Word re-paginates, so the export states where the layout breaks: every row the layout placed is `w:cantSplit`, `repeatHeader(n)` rows are `w:tblHeader` and keep with the row under them, and a row of blocks is kept whole the same way; the paragraph Word requires after a document's closing table is an ordinary one where the last page has room for two lines below it, so a reader can type below the table, and otherwise a point tall with its mark hidden, so it opens no blank page, reported `APPROXIMATED` since text typed at the end then goes into the table's last cell) | +| Table rows — resolved cells, row/col spans, two-pass fill/border paint (`TableRowFragmentPayload`) | ✅ `PdfTableRowFragmentRenderHandler` + row grouping in `PdfFixedLayoutBackend` | ✅ `PptxTableRowFragmentRenderHandler` + row grouping in `PptxFixedLayoutBackend` (positioned rectangles, edge lines, and text frames — never native PPTX tables, which re-lay-out content) | ⚠️ `DocxSemanticBackend.writeTable` (a real Word table on the grid `TableGrid` resolves: `colSpan` maps to `w:gridSpan`, `rowSpan` to `w:vMerge`, and the cascaded `DocumentTableStyle` text style reaches the cell's runs; the cell's fill maps to `w:shd` and its stroke to `w:tcBorders` — the engine's default 1pt black rule where the table states none, not Word's thinner grid — its padding to `w:tcMar`, less above and below the room Word makes for the horizontal rules (half of a rule between two rows, the lower row's, to each; the rules above and below the table whole to their row), each as wide as Word draws it, in eighths of a point (one outside Word's range reported, `border width`), and counted as both editors count it, two and a half twips an eighth rounded down (a rule between two rows shared in whole twips, the row above it taking half rounded down; a cell's top and bottom margins rounded to the twip together), a row held at the page's height less the most any of its cells takes, its margins and the rules it holds — between two others, the rest of its own above and half that of the cell under it; LibreOffice makes room at the edge between two rows for the heavier of their rules, where Word makes it for the lower row's, and under a row ruled heavier than it a row stands the difference lower there; a row of text cells moved by its top and bottom margins together, from Word's seat four fifths of the way down an exact line onto the page's baselines, by the least its cells' lines call for and no further than the margins hold — not a row holding a composed cell, one the layout did not measure, one in a vertical merge or whose cells call for opposite ways, nor a least call under a tenth of a point — and what the margins leave of a cell's call, half a point and more, moved by its text's position, and less, from a tenth of a point, by the height of its lines, each written shorter and the space after it taller, or the other way as far as that space holds, which keeps the cell's content as tall — where every paragraph of the cell is one line, in a face whose letters the export reads, and its letters stay clear of the line's top and foot; a row's cells at the row's smallest top and bottom margins, since both editors give every cell the row's largest, the rest of each cell's padding as space above its first paragraph and below its last, down to the largest margin a cell opening with a table or in a vertical merge keeps; the cascaded `textAnchor` maps to `w:vAlign` on every cell and to `w:jc` on a text cell's paragraph, with the engine's default — the vertical middle, on the left, or on the right for a right-to-left cell — and `DEFAULT` at the bottom left, as the renderer draws it; a composed cell is written by the same writers that write its node anywhere, so one built from an image, a list or a table carries it — a nested table is a real `w:tbl` taking the width of the column it sits in, less its own margins and padding, which is the column's rather than the one the page gives it, since the layout reports a composed cell's content under the owner's path; the paragraph Word requires after a nested table is hidden where it ends its cell holding nothing and no space; a translucent fill is flattened against the colour the page paints under the cell, and a translucent rule against the cell's fill where it has one, since `w:shd` and `w:tcBorders` are opaque, and the table's report note names it (`translucency`); Word re-paginates, so the export states where the layout breaks: every row the layout placed is `w:cantSplit`, `repeatHeader(n)` rows are `w:tblHeader` and keep with the row under them, and a row of blocks is kept whole the same way; the paragraph Word requires after a document's closing table is an ordinary one where the last page has room for two lines below it, so a reader can type below the table, and otherwise a point tall with its mark hidden, so it opens no blank page, reported `APPROXIMATED` since text typed at the end then goes into the table's last cell) | | Clip region open/close (`ShapeClipBegin/EndPayload`) | ✅ `PdfShapeClipBegin/EndRenderHandler` (CLIP_BOUNDS + CLIP_PATH) | ✅ `PptxClipSafety` + raster fallback in `PptxFixedLayoutBackend` — a provably no-op clip (padded content that cannot be cut) skips the fallback entirely and stays native, editable shapes; a clip that can cut ink renders through the PDF backend into one transparent picture on the clip bounds (pixel-exact, not editable as shapes; run-level link hotspots are not emitted and custom fragment handlers do not apply inside the picture; `Builder.clipRasterFallback(false)` restores unclipped vectors + warning; the raster targets a 2048px long edge, clamped to between native size and 4x, so a region larger than that is rendered at native resolution rather than downscaled — which also means its transient memory grows with the clip instead of stopping at the target (a 3370pt A0-landscape region costs ~45MB while rendering, against ~17MB for anything up to 2048pt); a true vector clip is tracked in [#413](https://github.com/DemchaAV/GraphCompose/issues/413)) | ⚠️ inline fallback + one-time capability warning; the report names a clip that cuts what its layers paint, measured from the layout's fragments by `DocxClipInk` — a clip that cuts nothing (an icon inside its box, a disc's initials, a photo filling its circle) is not named; a picture that fills a container clipped to an ellipse takes the ellipse as its geometry, which both editors crop it to; a badge's glyph — a smaller picture in a painted container that clips it to its outline (`CLIP_PATH`) and holds nothing else but drawing — is drawn by `DocxDrawings` as a floating picture over the outline, where the layout places it, reported `APPROXIMATED` — inside a filled panel the badge and its glyph are drawn in front of the shading; an icon picture beside its text in an unpainted container or a layer stack is drawn the same way; a filled or outlined rectangle or rounded rectangle holding text, composed in a table cell, which has no place in the layout to be drawn at, is written as a panel — a one-cell table in its fill and outline, its corners squared and reported, its row held at least the outline's height less its borders and margins, which keep inside it, and a one-line label the shape centres top to bottom on a line taller than the room Word leaves its content cut alike on both sides to that room, no closer to its letters than three quarters of a point, and seated where the page sets it, from the shape's top where the line is taller than its outline and Word sets it on the shape's middle, and a label it holds whole written at the line height that stands its text on the page's baseline, as far as its letters and the room allow, by a tenth of a point or more and not in a standard face the export does not embed — its row held and its label cut in whole twips rounded down, as the row the cell is in holds the page's height rounded once, and what its letters keep the label past that room taken out of the margins of the cell it is in, where it is all that cell holds and the cell all its row holds; the rest of what a composed cell draws (an icon, a tile, a disc) is the table's own drawing and is drawn by `drawCellDrawing` where the layout puts it, anchored as a rectangle is | | Timeline rail — one logical connector line resolved from marker and entry anchors after layout (`ShapeFragmentPayload` per page) | ✅ `PdfShapeFragmentRenderHandler` — one fragment per page, spliced beneath the markers | ✅ `PptxShapeFragmentRenderHandler` — same payload, same per-page fragments | ⚠️ `DocxDrawings` — the rail is read from the resolved layout's pass fragments and drawn per page as a `line` shape, and the markers as the shapes they are, anchored as a rectangle is: beside an entry's text they move with it when the text above is edited | | Transform open/close — rotate/scale about fragment centre (`TransformBegin/EndPayload`) | ✅ `PdfTransformBegin/EndRenderHandler` | ✅ `PptxTransformBegin/EndRenderHandler` (group shape; rotation and centre-pivot scaling via the exterior/interior frame ratio) | ⚠️ inline fallback + one-time capability warning; a turned shape container is written upright, and the report names its transform — in its drawn outline's note, or on its own where the outline draws nothing | @@ -114,7 +114,7 @@ honour an option ignores it (documented contract). | Metadata (title, author, …) | ✅ `PdfDocumentPostProcessor` | ⚠️ `applyMetadata` in `PptxFixedLayoutBackend` (OPC core properties + extended `Application`; OPC has no producer field, so that value is not representable) | ⚠️ `applyMetadata` (OPC core properties — title, author as creator, subject, keywords — and the creating application as the extended `Application`; OPC has no producer field here either, so that value is not representable, and the report names one the caller set other than the application) | | Page backgrounds (`DocumentSession.pageBackgrounds`, `PageBackgroundFill` — full page, columns, bands) | ✅ `DocumentPageBackgrounds` adds each fill as a shape fragment under every page's content, drawn by the ordinary shape handler | ✅ the same fragments, drawn as shapes on every slide | ⚠️ `DocxPageBackgrounds` — each fill is a rectangle anchored to the page, behind the text. A section of more than one page, or with a header or footer, carries them in every header part it has (default, first page, even pages), so they are drawn on every page; a section without a header gets an empty one against the page edge to carry them, and a later section without fills gets an empty header of its own rather than inheriting them. On a page with no top margin LibreOffice still sets the first line about 3pt lower under that header. A section of one page with neither draws them from the body instead — in the first cell's paragraph when the page opens with a table — and its lines stand where the page sets them in both editors (the seven sidebar CVs stood 2.6 to 3.3pt low in LibreOffice); they are on that page alone, so a page an editor's text runs onto has none. A fill's alpha is carried as the shape's. A two-column layout still flows its columns one after the other, so a column fill can stand beside text that is not its column's | | Watermark (front/back layers) | ✅ `PdfWatermarkRenderer` | ✅ `PptxChromeRenderer` (per-slide shape at the PDF placement math; behind-content applies before fragments, so no z-order surgery) | ❌ (not written; reported `DROPPED`, `watermark`) | -| Repeating headers / footers | ✅ `PdfHeaderFooterRenderer` — the zone's `fontName` is resolved through the document's own `FontLibrary`, so a zone draws in the family the author named; unnamed means standard-14 Helvetica, and a code point that family cannot encode is substituted with `?` exactly as body text is | ✅ `PptxChromeRenderer` (positioned per-slide text boxes; `{page}` / `{pages}` / `{date}` tokens with the numbering window rules). The named family reaches the slide run through `PptxFontMapping.familyFor`, and the same family measures the slots — a run measured against one face and typeset in another lands off-centre | ✅ `DocxSemanticBackend.writeBand` (`DocxTextBands`) — one line of a Word header or footer part: the left slot, the centre slot at a centre tab and the right slot at a right tab against the margins; `{page}` / `{pages}` as `PAGE` / `NUMPAGES` (`SECTIONPAGES` per section) fields with the roman or alphabetic switch; `{date}` as the date of the export; the separator as the paragraph's border, a translucent one flattened against white and reported (`translucency`); the header or footer distance from the band's geometry, baseline within 0.1pt in LibreOffice; a band sharing its kind with another band or a page zone stands in a frame (`w:framePr`) at its own height; `showOnFirstPage(false)` or counting from page 2 → an empty first-page part. A band starting after page 2, numbers not counting from 1 on page 1, and a band alone of its kind reaching past the page margin (written as a negative margin, so that Word holds the body at it as the page does; LibreOffice moves the body clear of it) are reported | +| Repeating headers / footers | ✅ `PdfHeaderFooterRenderer` — the zone's `fontName` is resolved through the document's own `FontLibrary`, so a zone draws in the family the author named; unnamed means standard-14 Helvetica, and a code point that family cannot encode is substituted with `?` exactly as body text is | ✅ `PptxChromeRenderer` (positioned per-slide text boxes; `{page}` / `{pages}` / `{date}` tokens with the numbering window rules). The named family reaches the slide run through `PptxFontMapping.familyFor`, and the same family measures the slots — a run measured against one face and typeset in another lands off-centre | ✅ `DocxSemanticBackend.writeBand` (`DocxTextBands`) — one line of a Word header or footer part: the left slot, the centre slot at a centre tab and the right slot at a right tab against the margins; `{page}` / `{pages}` as `PAGE` / `NUMPAGES` (`SECTIONPAGES` per section) fields with the roman or alphabetic switch; `{date}` as the date of the export; the separator as the paragraph's border, a translucent one flattened against white and reported (`translucency`), one wider or thinner than Word draws held to its range, one of no width drawn at Word's thinnest and one below zero not written, each reported (`border width`); the header or footer distance from the band's geometry, baseline within 0.1pt in LibreOffice; a band sharing its kind with another band or a page zone stands in a frame (`w:framePr`) at its own height; `showOnFirstPage(false)` or counting from page 2 → an empty first-page part. A band starting after page 2, numbers not counting from 1 on page 1, and a band alone of its kind reaching past the page margin (written as a negative margin, so that Word holds the body at it as the page does; LibreOffice moves the body clear of it) are reported | | Page zones (node subtree in the band) | ✅ Spliced into the layout graph by `DocumentPageZones`, so the ordinary fragment handlers draw it — no zone-specific code in the backend | ✅ Same splice, same reason: `PptxFixedLayoutBackend.renderGraph` draws every fragment of the graph | ✅ Written into a real `w:ftr` / `w:hdr` part. The band's children become runs on one Word line: a paragraph contributes its runs, an `ImageNode` an inline picture at the size the page draws it — contained or cropped to cover its box as the page draws it, its link its run's — a flex spacer becomes the right tab stop, and `PageContext.pageNumber()` / `pageTotal()` become live `PAGE` / `NUMPAGES` fields. Other node kinds are skipped, logged once a kind and reported once each (`DROPPED`, `page zone content`); a zone row's own fill, outline and side borders are reported as `row paint`. Word sets the line's parts one after another from the left margin and, after the first spacer, against the right margin, on one baseline, its tallest part's, in a zone of one line a one-line part the page sets on a baseline of its own raised or lowered to it by `w:position`, in whole half points — lowered only as far as the line holds below its baseline, a fifth of it or as far as its tallest part reaches; LibreOffice raises a run about a seventh further than Word, does not raise a page field and stands every picture on the baseline —; the page sets each by the zone's padding, a row's columns and gap, a paragraph's alignment and a part's own sides (a page field's alignment moves nothing: its box is a point wider than its number). The `page zone` note counts the parts the page sets elsewhere — read from the layout's zone fragments: a part stands where the page sets it when its line starts, or against the right margin ends, within a point and a half of Word's, on the baseline Word sets it on, in one line and with no prefix before it on the left side; past a part whose width Word does not keep, or a zone whose nodes the page names or nests otherwise, where a part stands is said to be not measured — and names a zone paragraph's right-to-left direction, prefix letters, fitted size where it is not measured, markdown marks written as letters, a markdown heading taller than its line, outline entry, anchor (no bookmark) and a picture set off the baseline, which the line does not carry, and a picture part's transform, outline entry and anchor. The line is an exact line as tall as the tallest part's line on the page — taller for a picture in it, a part written at a larger size than the page's or a part raised above it — standing as far from its edge as puts that part's baseline — a picture's foot — where the page has it (a lone or tallest part within 0.1pt in Word and LibreOffice, measured on 8pt and 18pt Lato headers and 8pt Lato footers), a lone part's padding and margin above and below included; a tallest part of more lines than one is as many exact lines, a footer's standing as many lines further from its edge; lines reaching past the page margin by more than half a point are held there with a negative margin and named; a zone the layout measures that shares its kind with another page zone stands in a frame (`w:framePr`) at its own height, at least its lines tall; a zone the page draws otherwise on the page it is measured on than it is written — other text, face, size or pictures — is not measured, its line Word's, and a zone whose content is none for every page Word writes it on is not written and named, as is one building none for the first page or the pages between, where the page draws it. Because Word paginates, `PageContext.number()` refuses here rather than baking a number that would be wrong on every page but one. The content is built for the first page and for the pages after it (`PageContext.unpaginated(first, last)`): built otherwise for the first, it becomes the title page's part (`w:titlePg`) and the ordinary one, a measured one framed where the two cannot share one distance; built otherwise for the last page, it is written there as built for the pages between and reported. A zone's `appliesTo` predicate is asked over sample pages (`DocxPageClasses`) and, when it follows Word's first / even / other pages, becomes the matching part — `w:titlePg` for the first page, `w:evenAndOddHeaders` for even pages — with an empty part on the pages it skips; a predicate that picks pages within a kind (the last page) is written on every page and reported | | Protection / encryption | ✅ `PdfDocumentPostProcessor` | ❌ (ignored with a one-time warning — no OOXML encryption support planned) | ❌ (not written, so the file opens unprotected; reported `DROPPED`, `protection`) | | Viewer preferences | ✅ `applyViewerPreferences` in `PdfFixedLayoutBackend` | ❌ (ignored with a one-time warning — PDF-viewer concept) | n/a (not written; reported `DROPPED`, `viewer preferences`) | diff --git a/docs/recipes/docx-export.md b/docs/recipes/docx-export.md index afabecc64..3994a2349 100644 --- a/docs/recipes/docx-export.md +++ b/docs/recipes/docx-export.md @@ -544,7 +544,9 @@ How it lands: sets it; above, then, the room over its first line. What none of them takes stands the content, or the block below, that much lower, and the report names it: on the panel for its top border, on the block below for its bottom one (`space above`). A panel's border is - written from two to ninety-six eighths of a point, as a table cell's rule is. A shape container's + written from two to ninety-six eighths of a point, as a table cell's rule and a rule are: a + width that, rounded to the eighth Word counts in, is thinner than a quarter of a point or + wider than twelve is drawn at Word's thinnest or widest, and named (`border width`). A shape container's borders, its layers centred in it, stay inside its outline, which its row holds less them as wide as Word draws them, two and a half twips an eighth of a point rounded down (measured: taken off at the 0.7pt the page strokes, a 20.3pt chip whose border Word draws 0.75pt wide @@ -1179,7 +1181,11 @@ fields, and `{date}` is the date of the export, as the page prints the date it was rendered. Its separator is the paragraph's border, and the line stands as far from the page edge as the page sets the text — its baseline within 0.1pt, its separator within 0.6pt (measured in LibreOffice at 7, 9 -and 12pt). A band that shares its kind with another band or a page zone — an +and 12pt). The separator's width is held to Word's range, as a panel's border +is, and named where it falls outside it (`border width`); one +of no width, which the page strokes as the thinnest +line a screen or a printer shows, is drawn at Word's thinnest, a quarter of +a point, and named, and one set below zero is named and not written. A band that shares its kind with another band or a page zone — an invoice's legal lines and its page number — stands in a frame at its own height on the page, since one after another in the footer they would keep the order they were added in rather than the page's order by height. A diff --git a/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidths.java b/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidths.java new file mode 100644 index 000000000..f15c28263 --- /dev/null +++ b/render-docx/src/main/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidths.java @@ -0,0 +1,104 @@ +package com.demcha.compose.document.backend.semantic.docx; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +/** + * How wide Word draws a border, and which of the widths the page strokes it does not draw. + * + *

A Word border's width is its {@code w:sz}, in eighths of a point, and a line border's runs + * from two to ninety-six (ECMA-376): no border Word draws is thinner than a quarter of a point + * or wider than twelve. The page strokes a border at the width it is given, so a panel's 20pt + * border is drawn 12pt wide and a 0.1pt hairline a quarter of a point, and the report names + * each; a width that rounds to an eighth Word draws is drawn at that eighth, unnamed.

+ * + * @author Artem Demchyshyn + */ +final class DocxBorderWidths { + + /** Word's thinnest border, in eighths of a point. */ + static final long THINNEST = 2; + + /** Word's widest, in eighths of a point. */ + static final long WIDEST = 96; + + private DocxBorderWidths() { + } + + /** + * A border's width as {@code w:sz}: eighths of a point, held from Word's thinnest to its + * widest. + * + * @param points the width the page strokes it at + * @return the eighths written + */ + static long eighths(double points) { + return Math.max(THINNEST, Math.min(WIDEST, Math.round(points * 8))); + } + + /** + * What a note says of borders Word draws at another width than the page strokes them, or + * {@code null} where it draws each in the eighth of a point nearest the page's. + * + * @param what what the borders are, as "its borders" or "the rule" + * @param plural whether {@code what} names more than one + * @param widths the widths the page strokes them at, in points, each above zero + * @return the note's text, or {@code null} + */ + static String notHeld(String what, boolean plural, Collection widths) { + TreeSet thinner = new TreeSet<>(); + TreeSet wider = new TreeSet<>(); + for (double width : widths) { + long eighths = Math.round(width * 8); + if (eighths < THINNEST) { + thinner.add(width); + } else if (eighths > WIDEST) { + wider.add(width); + } + } + if (thinner.isEmpty() && wider.isEmpty()) { + return null; + } + String them = plural ? "them" : "it"; + List drawn = new ArrayList<>(2); + if (!thinner.isEmpty()) { + drawn.add(pointsOf(THINNEST / 8.0) + "pt wide where the page strokes " + them + " " + listed(thinner)); + } + if (!wider.isEmpty()) { + drawn.add(pointsOf(WIDEST / 8.0) + "pt wide where the page strokes " + them + " " + listed(wider)); + } + return what + (plural ? " are" : " is") + " drawn " + String.join(", and ", drawn) + + ": a Word border is no thinner than " + pointsOf(THINNEST / 8.0) + "pt and no wider than " + + pointsOf(WIDEST / 8.0) + "pt"; + } + + /** + * What a note says of a border the page strokes at no width, which it draws as the thinnest + * line a screen or a printer shows (a line width of 0, in PDF). + * + * @param what what the border is, as "a page header's separator" + * @return the note's text + */ + static String ofNoWidth(String what) { + return what + ", which the page strokes 0pt wide, the thinnest line a screen or a printer shows, is " + + "drawn " + pointsOf(THINNEST / 8.0) + "pt wide: a Word border is no thinner"; + } + + /** Widths as a note lists them: "0.1pt", "0.05pt and 0.1pt". */ + private static String listed(TreeSet widths) { + List each = widths.stream().map(width -> pointsOf(width) + "pt").collect(Collectors.toList()); + if (each.size() == 1) { + return each.get(0); + } + return String.join(", ", each.subList(0, each.size() - 1)) + " and " + each.get(each.size() - 1); + } + + /** A width to the thousandth of a point, with no trailing zeros: a hairline is no tenth of one. */ + private static String pointsOf(double points) { + return BigDecimal.valueOf(Math.round(points * 1000) / 1000.0).stripTrailingZeros().toPlainString(); + } +} 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 d3e9a71f1..543f44ee6 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 @@ -210,6 +210,11 @@ public final class DocxSemanticBackend implements SemanticBackend { * border — flattened against the colour under it (see {@link DocxTranslucency}). */ private static final String TRANSLUCENCY = "translucency"; + /** + * The report's subject for a border the page strokes thinner or wider than any Word draws + * (see {@link DocxBorderWidths}). + */ + private static final String BORDER_WIDTH = "border width"; private static final Logger LOG = LoggerFactory.getLogger(DocxSemanticBackend.class); // The page's content width, so an image is held to the same bound layout holds it to. // Set per export; Double.MAX_VALUE means "no canvas, so nothing to clamp against". @@ -254,8 +259,8 @@ public final class DocxSemanticBackend implements SemanticBackend { // paragraphs had been written when it was (raiseOwedByTheLastLine). private double lastRaise; private long paragraphsAtTheLastRaise = -1; - // The text bands whose translucent separator is already reported this export: a band is - // written into each kind of header or footer Word is given. + // The text bands whose separator is already reported this export, its colour or its width: a + // band is written into each kind of header or footer Word is given. private final java.util.Set separatorsReported = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); // Whether any text fill was written this export, so the finished parts are settled only then. @@ -2138,12 +2143,18 @@ private static String zoneName(DocumentHeaderFooter band) { private void writeBand(XWPFHeaderFooter part, DocumentHeaderFooter band, boolean framed) { boolean inFrame = framed && !Double.isNaN(canvasHeight); double line = DocxTextBands.lineHeight(band); - boolean separated = band.isShowSeparator() && band.getSeparatorColor() != null - && band.getSeparatorColor().color().getAlpha() > 0 && band.getSeparatorThickness() > 0; + boolean separated = separatorWritten(band); + if (separatorShown(band) && !separated && separatorsReported.add(band)) { + report.add(DocxExportReport.Severity.DROPPED, BORDER_WIDTH, + sectioned ? "section " + (sectionIndex + 1) : null, + "a page " + zoneName(band) + "'s separator is set at no width a border has, below zero or " + + "not a number, so it is not written"); + } // The frame holds the separator too, below a header's line and above a footer's, as the // border is written: its space in whole points, its width in eighths of a point. double border = separated - ? Math.round(DocxTextBands.separatorSpace(band)) + ruleEighths(band.getSeparatorThickness()) / 8.0 + ? Math.round(DocxTextBands.separatorSpace(band)) + + DocxBorderWidths.eighths(band.getSeparatorThickness()) / 8.0 : 0; long frameTop = toTwips(band.getZone() == DocumentHeaderFooterZone.HEADER ? DocxTextBands.distanceFromEdge(band) @@ -2201,14 +2212,26 @@ private void writeBand(XWPFHeaderFooter part, DocumentHeaderFooter band, boolean // so there is no one colour under it to flatten a translucent one against but the page's // white. java.awt.Color colour = band.getSeparatorColor().color(); - paintEdge(edge, STBorder.SINGLE, BigInteger.valueOf(ruleEighths(band.getSeparatorThickness())), + paintEdge(edge, STBorder.SINGLE, + BigInteger.valueOf(DocxBorderWidths.eighths(band.getSeparatorThickness())), toHexColor(DocxTranslucency.flatten(colour, java.awt.Color.WHITE))); edge.setSpace(BigInteger.valueOf(Math.round(DocxTextBands.separatorSpace(band)))); - if (DocxTranslucency.translucent(colour) && separatorsReported.add(band)) { - report.add(DocxExportReport.Severity.APPROXIMATED, TRANSLUCENCY, - sectioned ? "section " + (sectionIndex + 1) : null, - "a page " + zoneName(band) + "'s separator is flattened against white, because a " - + "paragraph border is opaque"); + // A band is written into each kind of header it is given: told once. + if (separatorsReported.add(band)) { + String section = sectioned ? "section " + (sectionIndex + 1) : null; + if (DocxTranslucency.translucent(colour)) { + report.add(DocxExportReport.Severity.APPROXIMATED, TRANSLUCENCY, section, + "a page " + zoneName(band) + "'s separator is flattened against white, because a " + + "paragraph border is opaque"); + } + String separator = "a page " + zoneName(band) + "'s separator"; + String drawn = band.getSeparatorThickness() > 0 + ? DocxBorderWidths.notHeld(separator, false, + List.of((double) band.getSeparatorThickness())) + : DocxBorderWidths.ofNoWidth(separator); + if (drawn != null) { + report.add(DocxExportReport.Severity.APPROXIMATED, BORDER_WIDTH, section, drawn); + } } } } @@ -2295,10 +2318,31 @@ private void placeBand(XWPFDocument document, DocumentHeaderFooter band, boolean } } - /** How far a text band reaches from its page edge, its separator included, in points. */ + /** + * How far a text band reaches from its page edge, its separator included as Word draws it, in + * points. + */ private static double reachOf(DocumentHeaderFooter band) { return DocxTextBands.distanceFromEdge(band) + DocxTextBands.lineHeight(band) - + (band.isShowSeparator() ? DocxTextBands.separatorSpace(band) + band.getSeparatorThickness() : 0); + + (separatorWritten(band) + ? DocxTextBands.separatorSpace(band) + + DocxBorderWidths.eighths(band.getSeparatorThickness()) / 8.0 + : 0); + } + + /** Whether a text band's separator shows: asked for, in a colour not wholly transparent. */ + private static boolean separatorShown(DocumentHeaderFooter band) { + return band.isShowSeparator() && band.getSeparatorColor() != null + && band.getSeparatorColor().color().getAlpha() > 0; + } + + /** + * Whether a text band's separator is written, as its paragraph's border. The page strokes one + * of no width as the thinnest line a screen or a printer shows, and it is drawn at Word's + * thinnest border; one below zero, or not a number, no border has. + */ + private static boolean separatorWritten(DocumentHeaderFooter band) { + return separatorShown(band) && band.getSeparatorThickness() >= 0; } /** @@ -6549,6 +6593,7 @@ private void writePanelPiece(XWPFDocument document, DocumentNode node, Container paintCellSides(cell, DocxTranslucency.flattenedBorders(paint.borders(), fill != null ? fill.color() : under)); if (first) { reportFlattenedPaint(node, translucentFill, translucentSides, "its fill", "its borders"); + reportBorderWidths(node, "its borders", true, widthsOf(borders)); } DocumentInsets margins = insideTheBorders(padding, borders); applyCellPadding(cell, new DocumentInsets(margins.top(), Math.max(0, margins.right() - shortOfTheEdge), @@ -6872,6 +6917,35 @@ private static double outsideTheRow(DocumentStroke border, double padding) { return half + Math.max(0, half - Math.max(0, padding)); } + /** + * Names in the report borders Word draws at another width than the page strokes them + * ({@link DocxBorderWidths#notHeld}). + * + * @param what what the report calls them, as "its borders" + * @param plural whether {@code what} names more than one + * @param widths the widths the page strokes them at, each above zero + */ + private void reportBorderWidths(DocumentNode node, String what, boolean plural, + java.util.Collection widths) { + String drawn = DocxBorderWidths.notHeld(what, plural, widths); + if (drawn != null) { + report.add(DocxExportReport.Severity.APPROXIMATED, BORDER_WIDTH, layout.pathOf(node), drawn); + } + } + + /** The widths of the sides a panel strokes. */ + private static List widthsOf(DocumentBorders borders) { + List widths = new ArrayList<>(4); + // A side the panel does not stroke is null. + for (DocumentStroke side : java.util.Arrays.asList(borders.top(), borders.right(), borders.bottom(), + borders.left())) { + if (side != null && side.width() > 0) { + widths.add(side.width()); + } + } + return widths; + } + /** * Names in the report a node's translucent fill or strokes, which a cell's shading and its * borders hold only opaque, so they are flattened against the colour under them. @@ -6921,7 +6995,7 @@ private static void paintCellSide(CTBorder edge, DocumentStroke stroke) { // w:sz counts eighths of a point, from Word's thinnest to its thickest, as a table cell's // rule does: a hairline the author asked for stays a line, and a row counts the border at // the width written (eighthsInTwips). - paintEdge(edge, STBorder.SINGLE, BigInteger.valueOf(ruleEighths(stroke.width())), + paintEdge(edge, STBorder.SINGLE, BigInteger.valueOf(DocxBorderWidths.eighths(stroke.width())), toHexColor(stroke.color().color())); } @@ -13115,7 +13189,9 @@ private void writeRule(XWPFDocument document, DocumentNode node, DocxRules.Rule spacing.setLineRule(STLineSpacingRule.EXACT); spacing.setLine(BigInteger.valueOf(line)); owePendingSpacingAfter(below); - double drawn = colour.getAlpha() > 0 ? eighthsInTwips(ruleEighths(rule.thickness())) / POINT_TO_TWIP : 0; + double drawn = colour.getAlpha() > 0 + ? eighthsInTwips(DocxBorderWidths.eighths(rule.thickness())) / POINT_TO_TWIP + : 0; double excess = line / POINT_TO_TWIP + drawn + below - rule.boxHeight(); if (excess > 0) { double owed = Math.max(0, pendingSpacingAfter); @@ -13125,9 +13201,12 @@ private void writeRule(XWPFDocument document, DocumentNode node, DocxRules.Rule if (colour.getAlpha() > 0) { CTPBdr borders = properties.isSetPBdr() ? properties.getPBdr() : properties.addNewPBdr(); CTBorder bottom = borders.isSetBottom() ? borders.getBottom() : borders.addNewBottom(); - paintEdge(bottom, dashOf(rule), BigInteger.valueOf(ruleEighths(rule.thickness())), + paintEdge(bottom, dashOf(rule), BigInteger.valueOf(DocxBorderWidths.eighths(rule.thickness())), toHexColor(colour.getAlpha() < 255 ? DocxTranslucency.flatten(colour, colourUnder(node)) : colour)); bottom.setSpace(BigInteger.ZERO); + // A rule wider than Word's widest is drawn rather than written (DocxRules); a hairline + // thinner than its thinnest is written at that. + reportBorderWidths(node, "the rule", false, List.of(rule.thickness())); } if (DocxTranslucency.translucent(colour)) { report.add(DocxExportReport.Severity.APPROXIMATED, TRANSLUCENCY, layout.pathOf(node), @@ -13155,11 +13234,6 @@ private static STBorder.Enum dashOf(DocxRules.Rule rule) { return on <= rule.thickness() * 1.5 ? STBorder.DOTTED : STBorder.DASHED; } - /** A rule's thickness as {@code w:sz}: eighths of a point, from Word's thinnest to its thickest. */ - private static long ruleEighths(double thickness) { - return Math.max(2, Math.min(Math.round(DocxRules.MAX_RULE_POINTS * 8), Math.round(thickness * 8))); - } - /** * Crops a {@code COVER} image to its box, centred, in source space. * @@ -14228,6 +14302,7 @@ private void writeTableRows(XWPFDocument document, TableNode node) throws Except applyTableWidth(table, node, columnCount); boolean translucentFills = false; boolean translucentRules = false; + java.util.Set ruleWidths = new java.util.TreeSet<>(); for (int rowIdx = 0; rowIdx < rowCount; rowIdx++) { XWPFTableRow row = table.getRow(rowIdx); List physical = new ArrayList<>(); @@ -14254,6 +14329,9 @@ private void writeTableRows(XWPFDocument document, TableNode node) throws Except boolean translucentRule = DocxTranslucency.flattensStroke(stroke); translucentFills |= translucentFill; translucentRules |= translucentRule; + if (stroke != null && stroke.width() > 0) { + ruleWidths.add(stroke.width()); + } java.awt.Color under = !(translucentFill || translucentRule) ? java.awt.Color.WHITE : surfaceBehind != null ? surfaceBehind.color() : layout.colourUnderCell(node, placement.row(), placement.column()).orElse(java.awt.Color.WHITE); @@ -14299,6 +14377,7 @@ private void writeTableRows(XWPFDocument document, TableNode node) throws Except indentTable(table); carryDrawingsInRows(table, node); reportFlattenedPaint(node, translucentFills, translucentRules, "its cells' fills", "its cells' rules"); + reportBorderWidths(node, "its cells' rules", true, ruleWidths); } /** @@ -14412,7 +14491,7 @@ private void applyCellPaint(XWPFTableCell cell, DocumentColor fill, DocumentStro : properties.addNewTcBorders(); if (stroke.width() > 0) { // A hairline the author asked for stays a line, at Word's thinnest. - BigInteger eighths = BigInteger.valueOf(ruleEighths(stroke.width())); + BigInteger eighths = BigInteger.valueOf(DocxBorderWidths.eighths(stroke.width())); String colour = toHexColor(stroke.color().color()); paintEdge(borders.addNewTop(), STBorder.SINGLE, eighths, colour); paintEdge(borders.addNewBottom(), STBorder.SINGLE, eighths, colour); @@ -14434,11 +14513,14 @@ private void applyCellPaint(XWPFTableCell cell, DocumentColor fill, DocumentStro /** * How wide Word draws a cell's rule, in twips: the width written in eighths of a point, from * Word's thinnest to its thickest — the two to ninety-six eighths a line border's {@code w:sz} - * runs over (ECMA-376) — ({@link #ruleEighths(double)}), counted to the twip as a row's height + * runs over (ECMA-376) — ({@link DocxBorderWidths#eighths(double)}), counted to the twip as a + * row's height * counts it ({@link #eighthsInTwips}); 0 for none. */ private static long ruleTwips(DocumentStroke stroke) { - return stroke == null || !(stroke.width() > 0) ? 0 : eighthsInTwips(ruleEighths(stroke.width())); + return stroke == null || !(stroke.width() > 0) + ? 0 + : eighthsInTwips(DocxBorderWidths.eighths(stroke.width())); } /** diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidthsTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidthsTest.java new file mode 100644 index 000000000..e2aa9e725 --- /dev/null +++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxBorderWidthsTest.java @@ -0,0 +1,321 @@ +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.PageFlowBuilder; +import com.demcha.compose.document.dsl.TableBuilder; +import com.demcha.compose.document.output.DocumentHeaderFooter; +import com.demcha.compose.document.output.DocumentHeaderFooterZone; +import com.demcha.compose.document.output.DocumentPageNumbering; +import com.demcha.compose.document.style.DocumentBorders; +import com.demcha.compose.document.style.DocumentColor; +import com.demcha.compose.document.style.DocumentInsets; +import com.demcha.compose.document.style.DocumentStroke; +import com.demcha.compose.document.table.DocumentTableCell; +import com.demcha.compose.document.table.DocumentTableColumn; +import com.demcha.compose.document.table.DocumentTableStyle; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.junit.jupiter.api.Test; +import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder; + +import java.io.ByteArrayInputStream; +import java.math.BigInteger; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * A border the page strokes thinner or wider than any Word draws: written at Word's thinnest or + * widest, a quarter of a point and twelve, and named in the report — a panel's, a table cell's, + * a rule's and a page header's separator, whose width of none the page strokes as the thinnest + * line it can. + */ +class DocxBorderWidthsTest { + + private static final DocumentColor INK = DocumentColor.rgb(20, 40, 90); + private static final String RANGE = ": a Word border is no thinner than 0.25pt and no wider than 12pt"; + + @Test + void aWidthIsWrittenInEighthsHeldToWordsRange() { + assertThat(DocxBorderWidths.eighths(1)).isEqualTo(8); + assertThat(DocxBorderWidths.eighths(0.3)).as("rounded to the eighth").isEqualTo(2); + assertThat(DocxBorderWidths.eighths(0.1)).isEqualTo(2); + assertThat(DocxBorderWidths.eighths(0)).isEqualTo(2); + assertThat(DocxBorderWidths.eighths(12)).isEqualTo(96); + assertThat(DocxBorderWidths.eighths(20)).isEqualTo(96); + } + + @Test + void onlyAWidthOutsideWordsRangeIsNamed() { + // Rounding to the eighth Word counts in is no width it cannot draw: 0.2pt is two eighths. + assertThat(DocxBorderWidths.notHeld("its borders", true, List.of(0.2, 1.0, 12.0, 12.06))).isNull(); + assertThat(DocxBorderWidths.notHeld("the rule", false, List.of(0.1))) + .isEqualTo("the rule is drawn 0.25pt wide where the page strokes it 0.1pt" + RANGE); + assertThat(DocxBorderWidths.notHeld("its cells' rules", true, List.of(20.0, 0.05, 1.0, 0.001, 16.0))) + .isEqualTo("its cells' rules are drawn 0.25pt wide where the page strokes them 0.001pt and 0.05pt, " + + "and 12pt wide where the page strokes them 16pt and 20pt" + RANGE); + } + + @Test + void aPanelsBorderWiderThanWordsWidestIsWrittenAtItAndNamed() throws Exception { + try (Exported exported = export(null, page -> page + .addSection("Card", card -> card.borders(DocumentBorders.all(DocumentStroke.of(INK, 20))) + .padding(DocumentInsets.of(24)).addParagraph("Inside")))) { + CTBorder top = onlyCell(exported.document()).getCTTc().getTcPr().getTcBorders().getTop(); + assertThat(top.getSz()).isEqualTo(BigInteger.valueOf(96)); + assertThat(notes(exported)).containsExactly("its borders are drawn 12pt wide where the page strokes " + + "them 20pt" + RANGE); + } + } + + @Test + void aPanelsHairlineIsWrittenAtWordsThinnestAndNamed() throws Exception { + try (Exported exported = export(null, page -> page + .addSection("Card", card -> card.borders(new DocumentBorders(DocumentStroke.of(INK, 0.1), null, + DocumentStroke.of(INK, 1), null)) + .addParagraph("Inside")))) { + var borders = onlyCell(exported.document()).getCTTc().getTcPr().getTcBorders(); + assertThat(borders.getTop().getSz()).isEqualTo(BigInteger.valueOf(2)); + assertThat(borders.getBottom().getSz()).isEqualTo(BigInteger.valueOf(8)); + assertThat(notes(exported)).containsExactly("its borders are drawn 0.25pt wide where the page strokes " + + "them 0.1pt" + RANGE); + } + } + + @Test + void bordersWordDrawsAsThePageDoesAreNotNamed() throws Exception { + // A stroke of no width is no border, on the page as in the file. + try (Exported exported = export(null, page -> page + .addSection("Card", card -> card.borders(new DocumentBorders(DocumentStroke.of(INK, 0.5), + DocumentStroke.of(INK, 0), DocumentStroke.of(INK, 12), DocumentStroke.of(INK, 0))) + .addParagraph("Inside")) + .addDivider(d -> d.width(200).thickness(12).color(INK)) + .add(table(DocumentStroke.of(INK, 1), DocumentStroke.of(INK, 0.25))) + .add(table(DocumentStroke.of(INK, 0), DocumentStroke.of(INK, 0))))) { + assertThat(notes(exported)).isEmpty(); + } + } + + @Test + void aRowsBorderIsItsPanelsAndNamedSo() throws Exception { + try (Exported exported = export(null, page -> page + .addRow(row -> row.stroke(DocumentStroke.of(INK, 14)).padding(DocumentInsets.of(16)) + .addParagraph("Left").addParagraph("Right")))) { + assertThat(notes(exported)).containsExactly("its borders are drawn 12pt wide where the page strokes " + + "them 14pt" + RANGE); + } + } + + @Test + void aTablesCellRulesOutsideWordsRangeAreNamedOnceForTheTable() throws Exception { + try (Exported exported = export(null, page -> page + .add(table(DocumentStroke.of(INK, 0.05), DocumentStroke.of(INK, 20))))) { + var first = exported.document().getTables().get(0).getRow(0).getCell(0).getCTTc().getTcPr() + .getTcBorders(); + var last = exported.document().getTables().get(0).getRow(1).getCell(1).getCTTc().getTcPr() + .getTcBorders(); + assertThat(first.getTop().getSz()).isEqualTo(BigInteger.valueOf(2)); + assertThat(last.getTop().getSz()).isEqualTo(BigInteger.valueOf(96)); + assertThat(notes(exported)).containsExactly("its cells' rules are drawn 0.25pt wide where the page " + + "strokes them 0.05pt, and 12pt wide where the page " + + "strokes them 20pt" + RANGE); + } + } + + @Test + void aHairlineRuleIsWrittenAtWordsThinnestAndNamed() throws Exception { + try (Exported exported = export(null, page -> page.addDivider(d -> d.width(200).thickness(0.1).color(INK)))) { + CTBorder bottom = ruleParagraph(exported.document()).getCTP().getPPr().getPBdr().getBottom(); + assertThat(bottom.getSz()).isEqualTo(BigInteger.valueOf(2)); + assertThat(notes(exported)).containsExactly("the rule is drawn 0.25pt wide where the page strokes it " + + "0.1pt" + RANGE); + } + } + + @Test + void aPanelSplitByAPageBreakIsNamedOnce() throws Exception { + try (Exported exported = export(null, page -> page + .addSection("Card", card -> card.borders(DocumentBorders.all(DocumentStroke.of(INK, 20))) + .addParagraph("First").addPageBreak(pageBreak -> { }).addParagraph("Second")))) { + assertThat(exported.document().getTables()).as("a table a piece").hasSize(2); + assertThat(notes(exported)).hasSize(1); + } + } + + @Test + void aHairlineLineIsARuleWrittenAtWordsThinnestAndNamed() throws Exception { + try (Exported exported = export(null, page -> page.add(new com.demcha.compose.document.dsl.LineBuilder() + .horizontal(200).thickness(0.1).color(INK).build()))) { + CTBorder bottom = ruleParagraph(exported.document()).getCTP().getPPr().getPBdr().getBottom(); + assertThat(bottom.getSz()).isEqualTo(BigInteger.valueOf(2)); + assertThat(notes(exported)).containsExactly("the rule is drawn 0.25pt wide where the page strokes it " + + "0.1pt" + RANGE); + } + } + + @Test + void aTranslucentSeparatorWiderThanWordsWidestIsNamedForBoth() throws Exception { + try (Exported exported = export(session -> session.header(DocumentHeaderFooter.builder() + .zone(DocumentHeaderFooterZone.HEADER).height(40).fontSize(10).leftText("Header") + .showSeparator(true).separatorColor(DocumentColor.rgba(200, 0, 0, 100)).separatorThickness(20) + .build()), page -> page.addParagraph("Body"))) { + assertThat(notes(exported)).containsExactly("a page header's separator is drawn 12pt wide where the " + + "page strokes it 20pt" + RANGE); + assertThat(exported.report().bySubject().get("translucency")).singleElement() + .extracting(DocxExportReport.Note::detail).isEqualTo("a page header's separator is flattened " + + "against white, because a paragraph border " + + "is opaque"); + } + } + + @Test + void aFramedSeparatorOfNoWidthFitsInItsFrameAsTheBorderIsWritten() throws Exception { + // Two footers share Word's one: each stands in a frame as tall as its line and its border. + try (Exported exported = export(session -> { + session.footer(DocumentHeaderFooter.builder().zone(DocumentHeaderFooterZone.FOOTER).height(26) + .fontSize(7).leftText("Legal line").showSeparator(true).separatorColor(INK) + .separatorThickness(0).build()); + session.footer(DocumentHeaderFooter.builder().zone(DocumentHeaderFooterZone.FOOTER).height(14) + .fontSize(7).rightText("Page {page}").build()); + }, page -> page.addParagraph("Body"))) { + XWPFParagraph legal = exported.document().getFooterList().get(0).getParagraphs().get(0); + CTBorder top = legal.getCTP().getPPr().getPBdr().getTop(); + assertThat(top.getSz()).isEqualTo(BigInteger.valueOf(2)); + double border = ((Number) top.getSpace()).doubleValue() + 2 / 8.0; + assertThat(((Number) legal.getCTP().getPPr().getFramePr().getH()).longValue()) + .isEqualTo(Math.round((7 * DocxTextBands.LINE_FACTOR + border) * 20)); + } + } + + @Test + void aSeparatorOfNoWidthAtTheMarginReachesPastItAsWordDrawsIt() throws Exception { + // Its band ends at the 20pt margin; Word draws its border a quarter of a point past it, so + // the margin is written negative and the body held at it, as for any band reaching past. + try (Exported exported = export(separator(0, null, 20), page -> page.addParagraph("Body"))) { + Object top = exported.document().getDocument().getBody().getSectPr().getPgMar().getTop(); + assertThat(((Number) top).longValue()).isEqualTo(-400); + } + try (Exported exported = export(separator(-1, null, 20), page -> page.addParagraph("Body"))) { + Object top = exported.document().getDocument().getBody().getSectPr().getPgMar().getTop(); + assertThat(((Number) top).longValue()).as("a separator not written reaches nothing").isEqualTo(400); + } + } + + @Test + void aSeparatorOfNoWidthIsWrittenAtWordsThinnestAndNamed() throws Exception { + // The page strokes it at a line width of 0, the thinnest line a screen or printer shows; + // the export wrote no border at all. + try (Exported exported = export(separator(0, null), page -> page.addParagraph("Body"))) { + CTBorder bottom = band(exported.document()).getCTP().getPPr().getPBdr().getBottom(); + assertThat(bottom.getSz()).isEqualTo(BigInteger.valueOf(2)); + assertThat(notes(exported)).containsExactly("a page header's separator, which the page strokes 0pt " + + "wide, the thinnest line a screen or a printer shows, is " + + "drawn 0.25pt wide: a Word border is no thinner"); + } + } + + @Test + void aSeparatorWiderThanWordsWidestIsNamedOnceThoughWrittenIntoSeveralParts() throws Exception { + try (Exported exported = export(separator(20, footerOffTheFirstPage()), page -> page.addParagraph("Body"))) { + assertThat(exported.document().getHeaderList()).as("written into more than one part").hasSizeGreaterThan(1); + assertThat(band(exported.document()).getCTP().getPPr().getPBdr().getBottom().getSz()) + .isEqualTo(BigInteger.valueOf(96)); + assertThat(notes(exported)).containsExactly("a page header's separator is drawn 12pt wide where the " + + "page strokes it 20pt" + RANGE); + } + } + + @Test + void aSeparatorBelowZeroOrNotANumberIsNotWrittenAndIsNamedOnce() throws Exception { + for (float thickness : new float[]{-1, Float.NaN}) { + try (Exported exported = export(separator(thickness, footerOffTheFirstPage()), + page -> page.addParagraph("Body"))) { + assertThat(band(exported.document()).getCTP().getPPr().isSetPBdr()).as("%s", thickness).isFalse(); + assertThat(exported.report().bySubject().get("border width")).singleElement().satisfies(note -> { + assertThat(note.severity()).isEqualTo(DocxExportReport.Severity.DROPPED); + assertThat(note.detail()).isEqualTo("a page header's separator is set at no width a border " + + "has, below zero or not a number, so it is not written"); + }); + } + } + } + + private static Consumer separator(float thickness, Consumer more) { + return separator(thickness, more, 40); + } + + private static Consumer separator(float thickness, Consumer more, + float height) { + return session -> { + session.header(DocumentHeaderFooter.builder().zone(DocumentHeaderFooterZone.HEADER).height(height) + .fontSize(10).leftText("Header").showSeparator(true).separatorColor(INK) + .separatorThickness(thickness).build()); + if (more != null) { + more.accept(session); + } + }; + } + + /** A footer kept off the first page, which gives the section a first page's part of its own. */ + private static Consumer footerOffTheFirstPage() { + return session -> session.footer(DocumentHeaderFooter.builder().zone(DocumentHeaderFooterZone.FOOTER) + .height(20).fontSize(8).rightText("{page}") + .numbering(DocumentPageNumbering.builder().showOnFirstPage(false).build()).build()); + } + + private static com.demcha.compose.document.node.TableNode table(DocumentStroke first, DocumentStroke last) { + DocumentTableStyle one = DocumentTableStyle.builder().stroke(first).build(); + DocumentTableStyle other = DocumentTableStyle.builder().stroke(last).build(); + return new TableBuilder().name("Rota") + .columns(DocumentTableColumn.fixed(100), DocumentTableColumn.fixed(100)) + .rowCells(DocumentTableCell.text("A").withStyle(one), DocumentTableCell.text("B").withStyle(one)) + .rowCells(DocumentTableCell.text("C").withStyle(other), DocumentTableCell.text("D").withStyle(other)) + .build(); + } + + private record Exported(XWPFDocument document, DocxExportReport report) implements AutoCloseable { + @Override + public void close() throws Exception { + document.close(); + } + } + + private static Exported export(Consumer setup, Consumer content) throws Exception { + AtomicReference captured = new AtomicReference<>(); + byte[] bytes; + try (DocumentSession session = GraphCompose.document().pageSize(400, 400).margin(DocumentInsets.of(20)) + .create()) { + if (setup != null) { + setup.accept(session); + } + session.pageFlow(content::accept); + bytes = session.export(new DocxSemanticBackend(captured::set)); + } + return new Exported(new XWPFDocument(new ByteArrayInputStream(bytes)), captured.get()); + } + + private static List notes(Exported exported) { + return exported.report().bySubject().getOrDefault("border width", List.of()).stream() + .map(DocxExportReport.Note::detail).toList(); + } + + private static org.apache.poi.xwpf.usermodel.XWPFTableCell onlyCell(XWPFDocument document) { + assertThat(document.getTables()).hasSize(1); + return document.getTables().get(0).getRow(0).getCell(0); + } + + private static XWPFParagraph ruleParagraph(XWPFDocument document) { + return document.getParagraphs().stream() + .filter(p -> p.getCTP().getPPr() != null && p.getCTP().getPPr().isSetPBdr()) + .findFirst().orElseThrow(); + } + + /** The header band's paragraph, in the default header. */ + private static XWPFParagraph band(XWPFDocument document) { + return document.getHeaderFooterPolicy().getDefaultHeader().getParagraphs().stream() + .filter(p -> p.getText().contains("Header")).findFirst().orElseThrow(); + } +} diff --git a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxNodeFieldLedgerTest.java b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxNodeFieldLedgerTest.java index 1713f58ea..597aeb836 100644 --- a/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxNodeFieldLedgerTest.java +++ b/render-docx/src/test/java/com/demcha/compose/document/backend/semantic/docx/DocxNodeFieldLedgerTest.java @@ -93,6 +93,9 @@ private record Entry(Fate fate, String note) { private static final String PANEL_TRANSLUCENCY = "its translucency, as a panel's, flattened against the colour " + "under it, a border's against the panel's fill where it has " + "one; any other is written"; + // Word draws a border from a quarter of a point to 12pt wide, in eighths of a point. + private static final String BORDER_WIDTH = "a width that, rounded to the eighth of a point, is below a quarter " + + "of a point or past 12pt, drawn at Word's thinnest or widest"; // Word draws a panel's borders above and below past its box; what the space round it and its // padding do not take stands the content, or the block below, lower, and is reported. private static final String PANEL_BORDERS = "its translucency, as a panel's, flattened against the colour " @@ -101,16 +104,18 @@ private record Entry(Fate fate, String note) { + "neither the space above it, its padding nor the room over its " + "first line takes, on the panel; below, what neither the space " + "below it nor its padding takes, on the block below " - + "(space above); any other is written"; + + "(space above); " + BORDER_WIDTH + "; any other is written"; // An edge below zero pulls the next block up; Word sets no block over another. private static final String PULL = "below zero below it, the pull the space under it and the next block's own " + "top edge do not give back, on the next block (space above); any other is " + "written"; private static final String RULE_TRANSLUCENCY = "its translucency, as a rule's, flattened against the colour " + "under it; drawn, its alpha is written; any other is written"; + // A rule is a paragraph's border, no wider than 12pt (DocxRules): only a hairline is held. + private static final String RULE_WIDTH = "as a rule, " + BORDER_WIDTH + "; any other is written"; private static final String CELL_TRANSLUCENCY = "the translucency of a cell's fill, flattened against the colour " + "under the cell, and of its rules, against its fill where it has " - + "one; any other is written"; + + "one; of its rules, " + BORDER_WIDTH + "; any other is written"; // A row in the flow is written as a panel holding its columns, its paint the panel's. private static final String ROW_PAINT = "composed in a table cell, drawn as a shape where it frames no text " @@ -119,8 +124,9 @@ private record Entry(Fate fate, String note) { + "text, with a padding below zero or a column hanging into it, and " + "with a margin below zero above or below it or at a side in a cell; " + "its translucency, as a panel's, and what of a border above or below " - + "Word draws past the panel's box nothing round it takes, as a " - + "panel's; any other is written, as a panel"; + + "Word draws past the panel's box nothing round it takes, and of " + + "a border, " + BORDER_WIDTH + ", as a panel's; any other is " + + "written, as a panel"; private static final Map, Map> NODES = new LinkedHashMap<>(); private static final Map OUTPUT_OPTIONS = fields( @@ -128,8 +134,9 @@ private record Entry(Fate fate, String note) { "watermark:REPORTED", "protection:REPORTED", "viewerPreferences:REPORTED", - "headersAndFooters:REPORTED:a band's translucent separator, flattened against white; any other is " - + "written, or reported where Word's parts cannot hold it", + "headersAndFooters:REPORTED:a band's translucent separator, flattened against white; of a separator, " + + BORDER_WIDTH + ", one of no width at Word's thinnest, and one below zero or not a number, not " + + "written; any other is written, or reported where Word's parts cannot hold it", // The node entries below are the body's. A zone is written as one line of its // paragraphs' runs, page fields, pictures and tabs, and has its own entry here. "zones:REPORTED:where its parts stand across the line, a part the page sets lower than the line " @@ -182,7 +189,9 @@ private record Entry(Fate fate, String note) { "padding:WRITTEN", "margin:WRITTEN", "clipToBounds:REPORTED:where it cuts what its layers paint; composed in a table cell, on its table"); node(LineNode.class, "name:INERT", "width:WRITTEN", "height:WRITTEN", "startX:WRITTEN", "startY:WRITTEN", - "endX:WRITTEN", "endY:WRITTEN", "stroke:REPORTED:" + RULE_TRANSLUCENCY, + "endX:WRITTEN", "endY:WRITTEN", + "stroke:REPORTED:its translucency, as a rule's, flattened against the colour under it, and as a " + + "rule, " + BORDER_WIDTH + "; drawn, its alpha is written; any other is written", "linkTarget:REPORTED", "bookmarkOptions:REPORTED", "padding:WRITTEN", "margin:WRITTEN", "transform:REPORTED", "dashPattern:REPORTED", @@ -280,10 +289,12 @@ private record Entry(Fate fate, String note) { "fillColor:REPORTED:its translucency, as a panel's, flattened against the colour under it; " + "drawn, its alpha is written; any other is written", "stroke:REPORTED:its translucency, as a panel's border, flattened against the panel's fill or " - + "the colour under it; drawn, its alpha is written; any other is written", + + "the colour under it, and as a panel's, " + BORDER_WIDTH + "; drawn, its alpha and its width " + + "are written; any other is written", "padding:WRITTEN", "margin:WRITTEN", "transform:REPORTED"); - node(ShapeNode.class, "name:INERT", "width:WRITTEN", "height:WRITTEN", "fillColor:REPORTED:" + RULE_TRANSLUCENCY, + node(ShapeNode.class, "name:INERT", "width:WRITTEN", "height:REPORTED:" + RULE_WIDTH, + "fillColor:REPORTED:" + RULE_TRANSLUCENCY, "stroke:WRITTEN", "cornerRadius:REPORTED:corners unequal once held to half its shorter side, drawn at the largest radius", "linkTarget:REPORTED", "bookmarkOptions:REPORTED", "padding:WRITTEN", "margin:WRITTEN", "transform:REPORTED", "fillPaint:REPORTED",