Search code examples
pythonvbawin32comvisiotext-alignment

How to make text alignment of Visio shapes using Python(Win32 module)


I read the documentation of VBA and couldn't convert this to Python code. I simply created shape and tried to make its align right. If I delete alignment line of code, rest code works perfectly. I don't know, I might be using wrong VBA objects and methods. I'm open to your advices. If you provide me your solution code, I would be very appreciated.

import win32com.client
app = win32com.client.Dispatch("Visio.Application")
app.Visible = True
my_shape = page.DrawRectangle(3, 3, 5, 5)) # Draw rectangle
my_shape.Text = "Hello world!" # Add text to rectangle 
my_shape.LineStyle = "None" # Add some styling
my_shape.Characters.ParaProps['visHorzAlign'] = 'visAlignRight' #Tried alignment here
my_shape.SetCenter(4.4281, 3) # Change position of rectangle 

Here is the error enter image description here

Related documentations and forums that I found:

  1. http://www.44342.com/visio-f963-t1206-p1.htm

  2. https://learn.microsoft.com/en-us/office/vba/api/visio.selection.align


Solution

  • Try this code:

    import win32com.client as win32
    
    app = win32.Dispatch("Visio.Application")
    app.Visible = True
    page = app.Documents.AddEx("", 1, 0).Pages(1)  # create new document and get 1 page
    my_shape = page.DrawRectangle(3, 3, 5, 5)  # Draw rectangle
    my_shape.Text = "Hello world!"  # Add text to rectangle
    my_shape.LineStyle = "None"  # Add some styling
    my_shape.Cells("Para.HorzAlign").FormulaU = "2"  # 2 - right alignment
    # or use my_shape.CellsSRC(4, 0, 6).FormulaU = "2" #visSectionParagraph=4, visHorzAlign=6
    my_shape.SetCenter(4.4281, 3)  # Change position of rectangle