From c862f29fe620693c0205ea458d0ed37f9756a2db Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Wed, 25 Nov 2026 01:03:41 -0800 Subject: [PATCH] Fix table widths: ignore nested rows and update cell widths fix_tables() walked every w:tr under a table, so a nested table's rows counted towards the outer table's column count and its grid got rescaled for nothing. Only look at the table's own rows now. When the grid does change, e.g. after {%tc for %} adds columns, each cell's w:tcW is now set to the width of the grid columns it spans. Word prefers tcW over the grid, so the old widths left the table narrower. Fixes #64 Fixes #11 --- docform/docx/template.py | 47 +++++++++++++++++++++++++++++++++++++-- tests/unit/test_render.py | 37 ++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/docform/docx/template.py b/docform/docx/template.py index 03baf53..b5657d9 100644 --- a/docform/docx/template.py +++ b/docform/docx/template.py @@ -896,10 +896,16 @@ def fix_tables(self, xml): # walk trough xml and find table for t in tree.iter(ns + "tbl"): tblGrid = t.find(ns + "tblGrid") + if tblGrid is None: + continue columns = tblGrid.findall(ns + "gridCol") + # Only this table's own rows: a nested table is fixed on its own + # and its cells must not change this table's column count. + rows = t.findall(ns + "tr") + resized = False to_add = 0 # walk trough all rows and try to find if there is higher cell count - for r in t.iter(ns + "tr"): + for r in rows: cells = r.findall(ns + "tc") if (len(columns) + to_add) < len(cells): to_add = len(cells) - len(columns) @@ -929,6 +935,7 @@ def fix_tables(self, xml): etree.SubElement( tblGrid, ns + "gridCol", {ns + "w": str(int(new_average))} ) + resized = True # Refetch columns after columns addition. columns = tblGrid.findall(ns + "gridCol") @@ -946,7 +953,7 @@ def get_cell_len(total, cell): return total + 1 # Calculate max of table cells to compare with `gridCol`. - for r in t.iter(ns + "tr"): + for r in rows: cells = r.findall(ns + "tc") cells_len = functools.reduce(get_cell_len, cells, 0) cells_len_max = max(cells_len_max, cells_len) @@ -976,9 +983,45 @@ def get_cell_len(total, cell): for c in columns_left: c.set(ns + "w", str(int(float(c.get(ns + "w")) + extra_space))) + resized = True + + if resized: + self._sync_cell_widths(rows, tblGrid, ns) return tree + @staticmethod + def _sync_cell_widths(rows, tbl_grid, ns): + """Set each cell's w:tcW to the width of the grid columns it spans. + + Word uses w:tcW over w:tblGrid, so after the grid is rescaled the + cells would keep their old widths. Only widths in twips (dxa) are + changed; percentage and auto widths still follow the grid. + """ + widths = [] + for col in tbl_grid.findall(ns + "gridCol"): + try: + widths.append(int(float(col.get(ns + "w")))) + except (TypeError, ValueError): + return + for row in rows: + start = 0 + for cell in row.findall(ns + "tc"): + tc_pr = cell.find(ns + "tcPr") + span = 1 + grid_span = None if tc_pr is None else tc_pr.find(ns + "gridSpan") + if grid_span is not None: + try: + span = int(grid_span.get(ns + "val")) + except (TypeError, ValueError): + span = 1 + tc_w = None if tc_pr is None else tc_pr.find(ns + "tcW") + fits = start + span <= len(widths) + if fits and tc_w is not None and tc_w.get(ns + "type", "dxa") == "dxa": + tc_w.set(ns + "w", str(sum(widths[start:start + span]))) + tc_w.set(ns + "type", "dxa") + start += span + # Children of w:tcPr in the order the schema (CT_TcPr) requires. TC_PR_ORDER = { name: index diff --git a/tests/unit/test_render.py b/tests/unit/test_render.py index 139740a..19eef3a 100644 --- a/tests/unit/test_render.py +++ b/tests/unit/test_render.py @@ -653,3 +653,40 @@ def test_render_async_raises_render_errors(make_docx): tpl = DocxTemplate(make_docx(["{{ broken "])) with pytest.raises(TemplateSyntaxError): asyncio.run(tpl.render_async({})) + + +def _grid_and_cell_widths(table): + grid = [int(w) for w in table._tbl.xpath("./w:tblGrid/w:gridCol/@w:w")] + cells = [[int(w) for w in tr.xpath("./w:tc/w:tcPr/w:tcW/@w:w")] for tr in table._tbl.tr_lst] + return grid, cells + + +def test_nested_table_does_not_change_outer_grid(tmp_path): + doc = Document() + outer = doc.add_table(rows=1, cols=2) + outer.cell(0, 0).text = "{{ name }}" + outer.cell(0, 1).add_table(rows=1, cols=4) + path = tmp_path / "nested.docx" + doc.save(str(path)) + before, _ = _grid_and_cell_widths(Document(str(path)).tables[0]) + + tpl = DocxTemplate(str(path)) + tpl.render({"name": "x"}) + after, _ = _grid_and_cell_widths(saved(tpl).tables[0]) + assert len(after) == 2 + assert after == before + + +def test_added_columns_update_cell_widths(make_docx): + table = [["first", "{%tc for c in cols %}", "{{ c }}", "{%tc endfor %}"]] + path = make_docx(table=table) + total, _ = _grid_and_cell_widths(Document(str(path)).tables[0]) + + tpl = DocxTemplate(str(path)) + tpl.render({"cols": ["a", "b", "c", "d", "e"]}) + out = saved(tpl).tables[0] + assert table_rows(saved(tpl)) == [["first", "a", "b", "c", "d", "e"]] + grid, cells = _grid_and_cell_widths(out) + assert len(grid) == 6 + assert cells == [grid] + assert abs(sum(grid) - sum(total)) <= len(grid)