Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions docform/docx/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions tests/unit/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading