Search code examples
pythonwin32comvisiooffice-automation

Is it possible to manipulate Visio drawings programmatically?


I'm developing an automatic documentation application in Python. One of the required features is to draw flowcharts. As the users use Visio, I would like to generate the flowcharts in Visio format, so the user can make fine adjustments in the drawing without having programming skills. I'm searching by VSTO Add-ins for Office, and while it looks possible to be used to make Visio drawings programmatically, it's not clear if it's possible to use it with my Python application. Would it be possible to use Python to send information to a VSTO Add-in and use it to draw a flowchart in Visio based on this information? How this can be implemented? Is there any other recommendation of how to generate a flowchart programmatically in a format that users can edit using a vector graphics editor?


Solution

  • There is no need to communicate with a VSTO based add-in. You can automate any MS Office application (including Visio) from a Python script. I believe pywin32 can help with such tasks.

    from win32com.client import constants
    
    appVisio = win32com.client.Dispatch("Visio.Application")
    appVisio.Visible =1
    
    doc = appVisio.Documents.Add("Basic Diagram.vst")
    pagObj = doc.Pages.Item(1)
    
    doc.SaveAs(r'e:\temp\MyDrawing.vsd')
    doc.Close()
    

    win32com gives you back a thin Python wrapper around a COM server provided by the application. The documentation for the Visio object model is here.

    Be aware that the objects you get back are COM objects in a thin Python wrapper and so don't always behave like Python objects, and the documentation assumes you are writing in VBA not Python.