Autocad Automation

This example comes from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440493. It searches the ModelSpace collection for text objects. Once found it casts them and alter one of the text specific properties. To test this code AutoCAD must be started with a blank file open add at least one dtext object with ‘Spam’ as its value:

import win32com.client
acad = win32com.client.Dispatch("AutoCAD.Application")

doc = acad.ActiveDocument   # Document object
ms = doc.ModelSpace         # Modelspace "collection"
count = ms.Count            # Number of items in modelspace

for i in range(count):
    item = ms.Item(i)
    if 'text' in item.ObjectName.lower(): # Text objects are AcDbText
        # once we know what it is we can cast it
        text = win32com.client.CastTo(item, "IAcadText") 
        if text.TextString == "Spam":
            text.TextString = "Maps"
            text.Update()

Leave a Reply

Your email address will not be published. Required fields are marked *