From b1a3a5dd465e0b91b3f3f047993f7370b7922435 Mon Sep 17 00:00:00 2001 From: Thor Date: Thu, 23 Apr 2026 12:15:25 +0200 Subject: [PATCH] Fix GetMinMergedCell for cells spanning all columns and multiple rows When a single cell spans all columns (MergeRight = columnCount - 1) and more than one row (MergeDown >= 1), GetMinMergedCell() throws InvalidOperationException because the condition resultRowIndex + cell.MergeDown == row simplifies to MergeDown == 0, which the origin cell (MergeDown >= 1) does not satisfy. All other cells in that row are excluded because they are not in _mergedCells (they are covered by the merge). Fix: add a fallback loop that finds the cell with the minimum MergeDown value in _mergedCells for the given row. This matches the behaviour of GetMinMergedCellOriginal() which handles this case correctly. --- .../Rendering/TableRenderer.cs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/foundation/src/MigraDoc/src/MigraDoc.Rendering/Rendering/TableRenderer.cs b/src/foundation/src/MigraDoc/src/MigraDoc.Rendering/Rendering/TableRenderer.cs index a28b6406..a233a635 100644 --- a/src/foundation/src/MigraDoc/src/MigraDoc.Rendering/Rendering/TableRenderer.cs +++ b/src/foundation/src/MigraDoc/src/MigraDoc.Rendering/Rendering/TableRenderer.cs @@ -903,6 +903,37 @@ Cell GetMinMergedCell(int row) return cell; } } + + // Fallback: all cells in this row begin multi-row spans (MergeDown > 0), + // so no cell satisfies `resultRowIndex + MergeDown == row`. + // This occurs when a single cell spans all columns and more than one row + // (e.g. MergeRight = columnCount - 1, MergeDown >= 1). + // Find the cell with the minimum MergeDown instead — + // this matches the behaviour of GetMinMergedCellOriginal. + int minMergeDown = int.MaxValue; + Cell? minCell = null; + for (int idx = 0; idx < clsCount; idx++) + { + var cell = resultRow[idx]; + if (!_mergedCells.Contains(cell)) + continue; + if (cell.MergeDown < minMergeDown) + { + minMergeDown = cell.MergeDown; + minCell = cell; + if (minMergeDown == 0) + break; // Can't get better. + } + } + if (minCell is not null) + { +#if DEBUG + Debug.Assert(originalResult.Row!.Index + originalResult.MergeDown == + minCell.Row!.Index + minCell.MergeDown); +#endif + return minCell; + } + throw new InvalidOperationException("GetMinMergedCell: Unexpected problem #1"); }