python-openxml / python-docx

Create and modify Word documents with Python
MIT License
4.57k stars 1.12k forks source link

Rotation text in document #338

Open Dondigidol opened 7 years ago

Dondigidol commented 7 years ago

Hello! I not found such opportunities. Is it possible to rotate the text in documents to 90 degrees?

scanny commented 7 years ago

You'll need to be more specific. Do you mean making the page landscape rather than portrait?

Dondigidol commented 7 years ago

I added a table into document. In the cell(0,0) of this table can i insert text, with rotation by 90 degrees?

import docx, os from docx.api import Document

doc = Document() tab = doc.add_table(2, 15) tab.style = 'Table Grid'

tab.cell(1,0).merge(tab.cell(0,0)) tab.cell(1,1).merge(tab.cell(0,1)) tab.cell(1,2).merge(tab.cell(0,2)) tab.cell(1,3).merge(tab.cell(0,3)) tab.cell(1,4).merge(tab.cell(0,4))

tab.cell(1,8).merge(tab.cell(0,8)) tab.cell(1,9).merge(tab.cell(0,9)) tab.cell(1,10).merge(tab.cell(0,10)) tab.cell(1,11).merge(tab.cell(0,11)) tab.cell(1,12).merge(tab.cell(0,12)) tab.cell(1,13).merge(tab.cell(0,13)) tab.cell(1,14).merge(tab.cell(0,14))

tabhead = tab.cell(0,0) tabhead.text = 'Example table header'

doc.save('Examp.docx')

mattychen commented 6 years ago

Any updates on this? Looking to change the text direction in the table cell as well.

scanny commented 6 years ago

No.

keh9mark commented 4 months ago

In response to your request regarding the need to implement text rotation in a cell, I would like to share the solution to this task that I have obtained.

import docx
from lxml import etree
from docx.shared import Inches

def rotate_text_in_cell(cell):
    tcPr = cell._element.find(
        "./w:tcPr",
        namespaces={
            "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
        },
    )
    tcW = tcPr.find(
        "./w:tcW",
        namespaces={
            "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
        },
    )
    tcW.set("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}w", "4672")
    etree.SubElement(
        tcPr,
        "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}textDirection",
        attrib={
            "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val": "btLr"
        },
    )

document = docx.Document()

table = document.add_table(rows=5, cols=3)

row_cells = table.rows[0].cells
row_cells[0].text = "Name"
row_cells[1].text = "Age"
row_cells[2].text = "City"

for row in range(1, 5):
    row_cells = table.rows[row].cells
    row_cells[0].text = f"Name {row}"
    row_cells[1].text = str(20 + row)
    row_cells[2].text = f"City {row}"

for table in document.tables:
    for index, row in enumerate(table.rows):

        if index == 0:
            row.height = Inches(0.5)
            for cell in row.cells:
                rotate_text_in_cell(cell)
        else:
            row.height = Inches(0.1)

document.save("test1.docx")